Handle bad git revisions (#3791)

diff --git a/lib/src/source/git.dart b/lib/src/source/git.dart
index 1c4b2ac..36401d6 100644
--- a/lib/src/source/git.dart
+++ b/lib/src/source/git.dart
@@ -10,6 +10,7 @@
 import 'package:pool/pool.dart';
 import 'package:pub_semver/pub_semver.dart';
 
+import '../exceptions.dart';
 import '../git.dart' as git;
 import '../io.dart';
 import '../language_version.dart';
@@ -624,8 +625,18 @@
   ///
   /// This assumes that the canonical clone already exists.
   Future<String> _firstRevision(String path, String reference) async {
-    var lines = await git
-        .run(['rev-list', '--max-count=1', reference], workingDir: path);
+    final List<String> lines;
+    try {
+      lines = await git
+          .run(['rev-list', '--max-count=1', reference], workingDir: path);
+    } on git.GitException catch (e) {
+      throw PackageNotFoundException(
+        "Could not find git ref '$reference' (${e.stderr})",
+      );
+    }
+    if (lines.isEmpty) {
+      throw PackageNotFoundException("Could not find git ref '$reference'.");
+    }
     return lines.first;
   }
 
diff --git a/test/add/git/ref_test.dart b/test/add/git/ref_test.dart
index 5db6d1a..65e430d 100644
--- a/test/add/git/ref_test.dart
+++ b/test/add/git/ref_test.dart
@@ -65,8 +65,10 @@
 
     await pubAdd(
       args: ['foo', '--git-url', '../foo.git', '--git-ref', 'old'],
-      error: contains('Unable to resolve package "foo" with the given '
-          'git parameters'),
+      error: contains(
+        'Because myapp depends on foo from git which doesn\'t exist '
+        '(Could not find git ref \'old\' (fatal:',
+      ),
       exitCode: exit_codes.DATA,
     );
 
diff --git a/test/get/git/get_test.dart b/test/get/git/get_test.dart
new file mode 100644
index 0000000..1807389
--- /dev/null
+++ b/test/get/git/get_test.dart
@@ -0,0 +1,35 @@
+// Copyright (c) 2023, the Dart project authors.  Please see the AUTHORS file
+// for details. 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:pub/src/exit_codes.dart';
+import 'package:test/test.dart';
+
+import '../../descriptor.dart' as d;
+import '../../test_pub.dart';
+
+void main() {
+  test('Gives nice error message when git ref is bad', () async {
+    ensureGit();
+
+    await d.git(
+      'foo.git',
+      [d.libDir('foo'), d.libPubspec('foo', '1.0.0')],
+    ).create();
+
+    await d.appDir(
+      dependencies: {
+        'foo': {
+          'git': {'url': '../foo.git', 'ref': '^BAD_REF'}
+        }
+      },
+    ).create();
+
+    await pubGet(
+      error:
+          contains("Because myapp depends on foo from git which doesn't exist "
+              "(Could not find git ref '^BAD_REF' (fatal: "),
+      exitCode: UNAVAILABLE,
+    );
+  });
+}