Skip to content

Add 'tag_pattern' feature to git dependencies #4427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 31 commits into from
May 16, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
a3b6b92
Add 'tag_pattern' feature
sigurdm Nov 15, 2024
a482697
Test for interdependencies
sigurdm Nov 15, 2024
4cb927e
Fix `pub add --git-tag-pattern`
sigurdm Nov 15, 2024
9bc9e65
Make `hasMultipleVersions` a property of the description
sigurdm Nov 15, 2024
9a6517e
{{version}}
sigurdm Mar 27, 2025
49978b4
merge
sigurdm Mar 27, 2025
71e0f0f
Format
sigurdm Mar 27, 2025
6124471
Validate tag_pattern early
sigurdm Mar 28, 2025
2c7fb43
not coming until 3.9...
sigurdm Mar 28, 2025
6960eb7
windows compatz2
sigurdm Mar 28, 2025
03ba0ef
Windows compatz in tests
sigurdm Apr 1, 2025
4e8de79
Fix test sdk version
sigurdm Apr 1, 2025
b57d89a
Escaping
sigurdm Apr 1, 2025
3d33d64
Update lib/src/source/git.dart
sigurdm May 12, 2025
8ff2d3f
Fix serializeForPubspec
sigurdm May 12, 2025
e630352
Merge
sigurdm May 12, 2025
3e98819
Don't print ref in pubspec lock when using tag_pattern
sigurdm May 12, 2025
8c97b20
Remove TODO
sigurdm May 12, 2025
da21216
Fill in missing dartdoc
sigurdm May 12, 2025
b576aed
Fix test expectation
sigurdm May 12, 2025
892e066
Use version constraint when adding a git dependency with a tag pattern
sigurdm May 12, 2025
b2231d1
Test for `add`ing with a `tag_pattern`
sigurdm May 12, 2025
0ffc5d1
Test shape of pubspec.lock
sigurdm May 12, 2025
cad4daf
More tests
sigurdm May 12, 2025
2ba15cb
Windows paths in test
sigurdm May 12, 2025
c5ca0bf
Merge remote-tracking branch 'origin/master' into git_version_by_tag
sigurdm May 13, 2025
520b299
Merge
sigurdm May 15, 2025
d2b4966
Address some of review
sigurdm May 15, 2025
e1d51ed
Only allow single {{version}} marker
sigurdm May 15, 2025
0fd0394
Revert hack
sigurdm May 15, 2025
bab5b82
lints
sigurdm May 15, 2025
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
3 changes: 3 additions & 0 deletions lib/src/command/add.dart
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,7 @@ Specify multiple sdk packages with descriptors.''');
containingDir: p.current,
ref: argResults.gitRef,
path: argResults.gitPath,
tagPattern: argResults.tagPattern,
),
);
} on FormatException catch (e) {
Expand Down Expand Up @@ -775,6 +776,8 @@ extension on ArgResults {
bool get isDryRun => flag('dry-run');
String? get gitUrl => this['git-url'] as String?;
String? get gitPath => this['git-path'] as String?;
String? get tagPattern => this['tag-pattern'] as String?;

String? get gitRef => this['git-ref'] as String?;
String? get hostedUrl => this['hosted-url'] as String?;
String? get path => this['path'] as String?;
Expand Down
2 changes: 2 additions & 0 deletions lib/src/command/dependency_services.dart
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ class DependencyServicesApplyCommand extends PubCommand {
} else if (targetRevision != null &&
(lockFileYaml['packages'] as Map).containsKey(targetPackage)) {
final ref = entrypoint.lockFile.packages[targetPackage]!.toRef();

final currentDescription = ref.description as GitDescription;
final updatedRef = PackageRef(
targetPackage,
Expand All @@ -405,6 +406,7 @@ class DependencyServicesApplyCommand extends PubCommand {
path: currentDescription.path,
ref: targetRevision,
containingDir: directory,
tagPattern: currentDescription.tagPattern,
),
);
final versions = await cache.getVersions(updatedRef);
Expand Down
7 changes: 3 additions & 4 deletions lib/src/command/upgrade.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import '../package_name.dart';
import '../pubspec.dart';
import '../pubspec_utils.dart';
import '../solver.dart';
import '../source/hosted.dart';
import '../utils.dart';

/// Handles the `upgrade` pub command.
Expand Down Expand Up @@ -247,11 +246,11 @@ be direct 'dependencies' or 'dev_dependencies', following packages are not:
// Mapping from original to changed value.
var changes = <Package, Map<PackageRange, PackageRange>>{};
for (final package in entrypoint.workspaceRoot.transitiveWorkspace) {
final declaredHostedDependencies = [
final declaredUpgradableDependencies = [
...package.dependencies.values,
...package.devDependencies.values,
].where((dep) => dep.source is HostedSource);
for (final dep in declaredHostedDependencies) {
].where((dep) => dep.source.hasMultipleVersions);
for (final dep in declaredUpgradableDependencies) {
final resolvedPackage = resolvedPackages[dep.name]!;
if (!toUpgrade.contains(dep.name)) {
// If we're not trying to upgrade this package, or it wasn't in the
Expand Down
2 changes: 2 additions & 0 deletions lib/src/global_packages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,15 @@ class GlobalPackages {
required bool overwriteBinStubs,
String? path,
String? ref,
String? tagPattern,
}) async {
final name = await cache.git.getPackageNameFromRepo(
repo,
ref,
path,
cache,
relativeTo: p.current,
tagPattern: tagPattern,
);

// TODO(nweiz): Add some special handling for git repos that contain path
Expand Down
3 changes: 3 additions & 0 deletions lib/src/language_version.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ class LanguageVersion implements Comparable<LanguageVersion> {

bool get supportsWorkspaces => this >= firstVersionWithWorkspaces;

bool get supportsTagPattern => this >= firstVersionWithTagPattern;

/// Minimum language version at which short hosted syntax is supported.
///
/// This allows `hosted` dependencies to be expressed as:
Expand Down Expand Up @@ -109,6 +111,7 @@ class LanguageVersion implements Comparable<LanguageVersion> {
static const firstVersionWithNullSafety = LanguageVersion(2, 12);
static const firstVersionWithShorterHostedSyntax = LanguageVersion(2, 15);
static const firstVersionWithWorkspaces = LanguageVersion(3, 5);
static const firstVersionWithTagPattern = LanguageVersion(3, 7);

/// Transform language version to string that can be parsed with
/// [LanguageVersion.parse].
Expand Down
139 changes: 118 additions & 21 deletions lib/src/source/git.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class GitSource extends CachedSource {

@override
final name = 'git';
@override
final hasMultipleVersions = true;

@override
PackageRef parseRef(
Expand All @@ -43,6 +45,7 @@ class GitSource extends CachedSource {
String url;
String? ref;
String? path;
String? tagPattern;
if (description is String) {
url = description;
} else if (description is! Map) {
Expand Down Expand Up @@ -72,6 +75,32 @@ class GitSource extends CachedSource {
'string.');
}
path = descriptionPath;

// TODO: can we avoid relying on key presence?
if (description.containsKey('tag_pattern')) {
if (languageVersion != null && !languageVersion.supportsWorkspaces) {
throw FormatException(
'Using `git: {tagPattern: }` is only supported with a minimum SDK '
'constraint of ${LanguageVersion.firstVersionWithTagPattern}.',
);
}
switch (description['tag_pattern']) {
case final String descriptionTagPattern:
tagPattern = descriptionTagPattern;
case null:
tagPattern = 'v*';
default:
throw const FormatException(
"The 'tagPattern' field of the description "
'must be a string or null.');
}
}

if (ref != null && tagPattern != null) {
throw const FormatException(
'A git description cannot have both a ref and a `tagPattern`.',
);
}
}

final containingDir = switch (containingDescription) {
Expand All @@ -87,6 +116,7 @@ class GitSource extends CachedSource {
containingDir: containingDir,
ref: ref,
path: _validatedPath(path),
tagPattern: tagPattern,
),
);
}
Expand Down Expand Up @@ -121,6 +151,13 @@ class GitSource extends CachedSource {
throw const FormatException("The 'url' field of the description "
'must be a string.');
}

final tagPattern = description['tag_pattern'];
if (tagPattern is! String?) {
throw const FormatException("The 'tag_pattern' field of the description "
'must be a string.');
}

return PackageId(
name,
version,
Expand All @@ -132,6 +169,7 @@ class GitSource extends CachedSource {
description['path'],
),
containingDir: containingDir,
tagPattern: tagPattern,
),
resolvedRef,
),
Expand Down Expand Up @@ -230,17 +268,25 @@ class GitSource extends CachedSource {
String? path,
SystemCache cache, {
required String relativeTo,
required String? tagPattern,
}) async {
if (ref != null && tagPattern != null) {
fail('Cannot have both a `tagPattern` and a `ref`');
}
final description = GitDescription(
url: url,
ref: ref,
path: path,
containingDir: relativeTo,
tagPattern: tagPattern, // TODO
);
return await _pool.withResource(() async {
await _ensureRepoCache(description, cache);
final path = _repoCachePath(description, cache);
final revision = await _firstRevision(path, description.ref);

final revision = tagPattern != null
? (await _listRevisionsWithTagPattern(path, tagPattern)).last
: await _firstRevision(path, description.ref);
final resolvedDescription = ResolvedGitDescription(description, revision);

return Pubspec.parse(
Expand Down Expand Up @@ -297,16 +343,42 @@ class GitSource extends CachedSource {
return await _pool.withResource(() async {
await _ensureRepoCache(description, cache);
final path = _repoCachePath(description, cache);
final revision = await _firstRevision(path, description.ref);
final pubspec = await _describeUncached(ref, revision, cache);
final List<String> revisions;
if (description.tagPattern case final String tagPattern) {
revisions = await _listRevisionsWithTagPattern(path, tagPattern);
} else {
revisions = [await _firstRevision(path, description.ref)];
}

return [
PackageId(
ref.name,
pubspec.version,
ResolvedGitDescription(description, revision),
),
];
final result = <PackageId>[];
final seenVersions = <Version, String>{};
for (final revision in revisions) {
final Pubspec pubspec;
try {
pubspec = await _describeUncached(ref, revision, cache);
} on Exception {
log.fine(
'Found no valid pubspec of ${ref.name} at $revision, ignoring,',
);
continue;
}
final prev = seenVersions[pubspec.version];
if (prev != null) {
log.fine(
'Repeated version ${pubspec.version} of ${ref.name} '
'at $revision and $prev',
);
}
seenVersions[pubspec.version] = revision;
result.add(
PackageId(
ref.name,
pubspec.version,
ResolvedGitDescription(description, revision),
),
);
}
return result;
});
}

Expand All @@ -327,6 +399,8 @@ class GitSource extends CachedSource {
);
}

final Map<(PackageRef, String), Pubspec> _pubspecAtRevisionCache = {};

/// Like [describeUncached], but takes a separate [ref] and Git [revision]
/// rather than a single ID.
Future<Pubspec> _describeUncached(
Expand All @@ -338,18 +412,20 @@ class GitSource extends CachedSource {
if (description is! GitDescription) {
throw ArgumentError('Wrong source');
}
await _ensureRevision(description, revision, cache);
return _pubspecAtRevisionCache[(ref, revision)] ??= await () async {
await _ensureRevision(description, revision, cache);

return Pubspec.parse(
await _showFileAtRevision(
ResolvedGitDescription(description, revision),
'pubspec.yaml',
cache,
),
cache.sources,
expectedName: ref.name,
containingDescription: ref.description,
);
return Pubspec.parse(
await _showFileAtRevision(
ResolvedGitDescription(description, revision),
'pubspec.yaml',
cache,
),
cache.sources,
expectedName: ref.name,
containingDescription: ref.description,
);
}();
}

/// Clones a Git repo to the local filesystem.
Expand Down Expand Up @@ -647,6 +723,19 @@ class GitSource extends CachedSource {
String _packageListPath(String revisionCachePath) =>
p.join(revisionCachePath, '.git/pub-packages');

///
Future<List<String>> _listRevisionsWithTagPattern(
String path,
String tagPattern,
) async {
return (await git.run(
['tag', '--list', tagPattern, '--format', '%(objectname)'],
workingDir: path,
))
.trim()
.split('\n');
}

/// Runs "git rev-list" on [reference] in [path] and returns the first result.
///
/// This assumes that the canonical clone already exists.
Expand Down Expand Up @@ -761,6 +850,8 @@ class GitDescription extends Description {
/// not allow strings of the form: '[email protected]:dart-lang/pub.git'.
final String url;

final String? tagPattern;

/// `true` if [url] was parsed from a relative url.
final bool relative;

Expand All @@ -777,6 +868,7 @@ class GitDescription extends Description {
required this.relative,
required String? ref,
required String? path,
required this.tagPattern,
}) : ref = ref ?? 'HEAD',
path = path ?? '.';

Expand All @@ -785,13 +877,15 @@ class GitDescription extends Description {
required String? ref,
required String? path,
required String? containingDir,
required String? tagPattern,
}) {
final validatedUrl = GitSource._validatedUrl(url, containingDir);
return GitDescription.raw(
url: validatedUrl.url,
relative: validatedUrl.wasRelative,
ref: ref,
path: path,
tagPattern: tagPattern,
);
}

Expand Down Expand Up @@ -819,6 +913,7 @@ class GitDescription extends Description {
'url': relativeUrl,
if (ref != 'HEAD') 'ref': ref,
if (path != '.') 'path': path,
if (tagPattern != null) 'tag_pattern': tagPattern,
};
}

Expand All @@ -838,6 +933,7 @@ class GitDescription extends Description {
relative: relative,
ref: newRef,
path: path,
tagPattern: tagPattern,
);

@override
Expand Down Expand Up @@ -883,6 +979,7 @@ class ResolvedGitDescription extends ResolvedDescription {
return {
'url': url,
'ref': description.ref,
'tag_pattern': description.tagPattern,
'resolved-ref': resolvedRef,
'path': description.path,
};
Expand Down
1 change: 1 addition & 0 deletions lib/src/source/path.dart
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ class PathSource extends Source {
url: containingDescription.url,
relative: containingDescription.relative,
ref: containingDescription.ref,
tagPattern: containingDescription.tagPattern,
path: resolvedPath,
),
);
Expand Down
9 changes: 9 additions & 0 deletions test/descriptor/git.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ class GitRepoDescriptor extends DirectoryDescriptor {
]);
}

/// Adds a tag named [tag] to the repo described by `this`.
///
/// [parent] defaults to [sandbox].
Future tag(String tag, [String? parent]) async {
await _runGitCommands(parent, [
['tag', '-a', tag, '-m', 'Some message'],
]);
}

/// Return a Future that completes to the commit in the git repository
/// referred to by [ref].
///
Expand Down
Loading
Loading