|
15 | 15 | package gitrepo |
16 | 16 |
|
17 | 17 | import ( |
| 18 | + "errors" |
18 | 19 | "fmt" |
19 | 20 | "os" |
20 | 21 | "path/filepath" |
@@ -1274,6 +1275,60 @@ func TestCleanUntracked(t *testing.T) { |
1274 | 1275 | } |
1275 | 1276 | } |
1276 | 1277 |
|
| 1278 | +func TestGetLatestCommit(t *testing.T) { |
| 1279 | + t.Parallel() |
| 1280 | + for _, test := range []struct { |
| 1281 | + name string |
| 1282 | + path string |
| 1283 | + setup func(t *testing.T, repo *git.Repository, path string) |
| 1284 | + want *Commit |
| 1285 | + wantErr error |
| 1286 | + }{ |
| 1287 | + { |
| 1288 | + name: "get_latest_commit_of_a_path", |
| 1289 | + path: "a/path/example.txt", |
| 1290 | + setup: func(t *testing.T, repo *git.Repository, path string) { |
| 1291 | + createAndCommit(t, repo, path, []byte("1st content"), "first commit") |
| 1292 | + createAndCommit(t, repo, path, []byte("2nd content"), "second commit") |
| 1293 | + createAndCommit(t, repo, "another/path/example.txt", []byte("2nd content"), "second commit") |
| 1294 | + }, |
| 1295 | + want: &Commit{ |
| 1296 | + Message: "second commit", |
| 1297 | + }, |
| 1298 | + }, |
| 1299 | + { |
| 1300 | + name: "no_commit_of_a_path", |
| 1301 | + path: "a/path/example.txt", |
| 1302 | + setup: func(t *testing.T, repo *git.Repository, path string) { |
| 1303 | + // Do nothing. |
| 1304 | + }, |
| 1305 | + wantErr: plumbing.ErrReferenceNotFound, |
| 1306 | + }, |
| 1307 | + } { |
| 1308 | + t.Run(test.name, func(t *testing.T) { |
| 1309 | + t.Parallel() |
| 1310 | + repo, dir := initTestRepo(t) |
| 1311 | + test.setup(t, repo, test.path) |
| 1312 | + localRepo := &LocalRepository{Dir: dir, repo: repo} |
| 1313 | + got, err := localRepo.GetLatestCommit(test.path) |
| 1314 | + if test.wantErr != nil { |
| 1315 | + if !errors.Is(err, test.wantErr) { |
| 1316 | + t.Errorf("unexpected error type: got %v, want %v", err, test.wantErr) |
| 1317 | + } |
| 1318 | + |
| 1319 | + return |
| 1320 | + } |
| 1321 | + if err != nil { |
| 1322 | + t.Error(err) |
| 1323 | + return |
| 1324 | + } |
| 1325 | + if diff := cmp.Diff(test.want, got, cmpopts.IgnoreFields(Commit{}, "When", "Hash")); diff != "" { |
| 1326 | + t.Errorf("GetLatestCommit() mismatch in %s (-want +got):\n%s", test.name, diff) |
| 1327 | + } |
| 1328 | + }) |
| 1329 | + } |
| 1330 | +} |
| 1331 | + |
1277 | 1332 | // initTestRepo creates a new git repository in a temporary directory. |
1278 | 1333 | func initTestRepo(t *testing.T) (*git.Repository, string) { |
1279 | 1334 | t.Helper() |
|
0 commit comments