Commit c7fe698a2b93683b520dc17f1f5e54299ee613ef

Stefan Sperling 2018-01-23T18:07:21

add a helper function for opening a pack file

diff --git a/lib/pack.c b/lib/pack.c
index 5f0f002..e3805da 100644
--- a/lib/pack.c
+++ b/lib/pack.c
@@ -361,7 +361,7 @@ done:
 	return err;
 }
 
-const struct got_error *
+static const struct got_error *
 get_packfile_path(char **path_packfile, struct got_repository *repo,
     struct got_packidx_v2_hdr *packidx)
 {
@@ -411,6 +411,33 @@ read_packfile_hdr(FILE *f, struct got_packidx_v2_hdr *packidx)
 }
 
 static const struct got_error *
+open_packfile(FILE **packfile, char **path_packfile,
+    struct got_repository *repo, struct got_packidx_v2_hdr *packidx)
+{
+	const struct got_error *err;
+
+	*packfile = NULL;
+
+	err = get_packfile_path(path_packfile, repo, packidx);
+	if (err)
+		return err;
+
+	*packfile = fopen(*path_packfile, "rb");
+	if (*packfile == NULL) {
+		err = got_error_from_errno();
+		free(*path_packfile);
+		return err;
+	}
+
+	err = read_packfile_hdr(*packfile, packidx);
+	if (err) {
+		fclose(*packfile);
+		*packfile = NULL;
+	}
+	return err;
+}
+
+static const struct got_error *
 parse_object_type_and_size(uint8_t *type, uint64_t *size, size_t *len,
     FILE *packfile)
 {
@@ -583,17 +610,11 @@ resolve_ref_delta(struct got_delta_chain *deltas, struct got_repository *repo,
 		return got_error(GOT_ERR_BAD_PACKIDX);
 	}
 
-	err = get_packfile_path(&path_base_packfile, repo, packidx);
+	err = open_packfile(&base_packfile, &path_base_packfile, repo, packidx);
 	got_packidx_close(packidx);
 	if (err)
 		return err;
 
-	base_packfile = fopen(path_base_packfile, "rb");
-	if (base_packfile == NULL) {
-		err = got_error_from_errno();
-		goto done;
-	}
-
 	if (fseeko(base_packfile, base_offset, SEEK_SET) != 0) {
 		err = got_error_from_errno();
 		goto done;
@@ -720,20 +741,10 @@ open_packed_object(struct got_object **obj, struct got_repository *repo,
 	if (offset == (uint64_t)-1)
 		return got_error(GOT_ERR_BAD_PACKIDX);
 
-	err = get_packfile_path(&path_packfile, repo, packidx);
+	err = open_packfile(&packfile, &path_packfile, repo, packidx);
 	if (err)
 		return err;
 
-	packfile = fopen(path_packfile, "rb");
-	if (packfile == NULL) {
-		err = got_error_from_errno();
-		goto done;
-	}
-
-	err = read_packfile_hdr(packfile, packidx);
-	if (err)
-		goto done;
-
 	if (fseeko(packfile, offset, SEEK_SET) != 0) {
 		err = got_error_from_errno();
 		goto done;