Skip to content

Commit bf6c461

Browse files
authored
fix: update existing file at a custom branch (#37)
1 parent 70c5a45 commit bf6c461

File tree

2 files changed

+71
-2
lines changed

2 files changed

+71
-2
lines changed

src/get-file-content.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@ type Options = {
99
branch?: string;
1010
};
1111

12+
type GetContentsParameters = {
13+
owner: string;
14+
repo: string;
15+
path: string;
16+
ref?: string;
17+
};
18+
1219
type Result = {
1320
content: string | null;
1421
sha?: string;
@@ -36,10 +43,17 @@ export async function getFileContents(
3643
options: Options
3744
): Promise<Result> {
3845
const route = "GET /repos/{owner}/{repo}/contents/{path}";
39-
const requestOptions = octokit.request.endpoint(route, options);
46+
47+
const { branch, ...parameters } = options;
48+
const getContentsParameters: GetContentsParameters = {
49+
...parameters,
50+
ref: branch,
51+
};
52+
53+
const requestOptions = octokit.request.endpoint(route, getContentsParameters);
4054

4155
const { data } = await octokit
42-
.request(route, options)
56+
.request(route, getContentsParameters)
4357
.catch((error: RequestError) => {
4458
/* istanbul ignore if */
4559
if (error.status !== 404) throw error;

test/create-or-update-text-file.test.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,61 @@ describe("README usage examples", () => {
289289
expect(updated).toEqual(true);
290290
expect(data).toStrictEqual({ ok: true });
291291
});
292+
293+
it("Creates file with static content if file exists at given path and branch", async () => {
294+
const mock = fetchMock
295+
.sandbox()
296+
297+
// file exists
298+
.getOnce(
299+
"https://api.github.com/repos/octocat/hello-world/contents/test.txt?ref=custom-branch",
300+
{
301+
body: {
302+
content: utf8ToBase64("current content"),
303+
sha: "sha123",
304+
ref: "custom-branch",
305+
},
306+
status: 200,
307+
}
308+
)
309+
310+
// update file
311+
.putOnce(
312+
"https://api.github.com/repos/octocat/hello-world/contents/test.txt",
313+
{
314+
body: {
315+
ok: true,
316+
},
317+
status: 200,
318+
},
319+
{
320+
body: {
321+
content: utf8ToBase64("content here"),
322+
message: "update test.txt",
323+
sha: "sha123",
324+
branch: "custom-branch",
325+
},
326+
}
327+
);
328+
329+
const octokit = new MyOctokit({
330+
request: {
331+
fetch: mock,
332+
},
333+
});
334+
335+
const { updated, data } = await octokit.createOrUpdateTextFile({
336+
owner: "octocat",
337+
repo: "hello-world",
338+
path: "test.txt",
339+
content: "content here",
340+
message: "update test.txt",
341+
branch: "custom-branch",
342+
});
343+
344+
expect(updated).toEqual(true);
345+
expect(data).toStrictEqual({ ok: true });
346+
});
292347
});
293348

294349
// TODO: add test for browsers

0 commit comments

Comments
 (0)