Skip to content

Add base arg for commitChangesFromRepo #13

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 2 commits into from
Aug 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions .changeset/tiny-days-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@s0/ghcommit": minor
---

Allow for base commit to be specified with commitChangesFromRepo
2 changes: 2 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
with:
fetch-depth: 2
- name: Use Node.js
uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2
with:
Expand Down
29 changes: 27 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ In addition to `CommitFilesBasedArgs`, this function has the following arguments

```ts
{
/**
* The base commit to build your changes on-top of
*
* @default HEAD
*/
base?: {
commit: string;
};
/**
* The root of the repository.
*
Expand All @@ -86,7 +94,7 @@ In addition to `CommitFilesBasedArgs`, this function has the following arguments
Example:

```ts
import { getOctokit } from "@actions/github";
import { context, getOctokit } from "@actions/github";
import { commitChangesFromRepo } from "@s0/ghcommit/git";

const octokit = getOctokit(process.env.GITHUB_TOKEN);
Expand All @@ -103,7 +111,7 @@ await commitChangesFromRepo({
},
});

// Commit & push the files from ta specific directory
// Commit & push the files from a specific directory
// where we've cloned a repo, and made changes to files
await commitChangesFromRepo({
octokit,
Expand All @@ -115,6 +123,23 @@ await commitChangesFromRepo({
},
repoDirectory: "/tmp/some-repo",
});

// Commit & push the files from the current directory,
// but ensure changes from any locally-made commits are also included
await commitChangesFromRepo({
octokit,
owner: "my-org",
repository: "my-repo",
branch: "another-new-branch-to-create",
message: {
headline: "[chore] do something else",
},
base: {
// This will be the original sha from the workflow run,
// even if we've made commits locally
commit: context.sha,
},
});
```

### `commitFilesFromDirectory`
Expand Down
6 changes: 4 additions & 2 deletions src/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,23 @@ import {
} from "./interface";

export const commitChangesFromRepo = async ({
base,
repoDirectory = process.cwd(),
log,
...otherArgs
}: CommitChangesFromRepoArgs): Promise<CommitFilesResult> => {
const ref = base?.commit ?? "HEAD";
const gitLog = await git.log({
fs,
dir: repoDirectory,
ref: "HEAD",
ref,
depth: 1,
});

const oid = gitLog[0]?.oid;

if (!oid) {
throw new Error("Could not determine oid for current branch");
throw new Error(`Could not determine oid for ${ref}`);
}

// Determine changed files
Expand Down
5 changes: 5 additions & 0 deletions src/github/graphql/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ const GET_REF_TREE = /* GraphQL */ `
tree {
oid
}
parents(first: 10) {
nodes {
oid
}
}
file(path: $path) {
oid
}
Expand Down
18 changes: 18 additions & 0 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,24 @@ export interface CommitFilesFromDirectoryArgs
}

export interface CommitChangesFromRepoArgs extends CommitFilesBasedArgs {
/**
* The base commit to build your changes on-top of.
*
* By default, this commit will be the HEAD of the local repository,
* meaning that if any commits have been made locally and not pushed,
* this command will fail.
*
* To include all changes, this should be set to a commit that is known
* to be in the remote repository (such as the default branch).
*
* If you want to base the changes on a different commit to one checked out,
* make sure that you also pull this commit from the remote.
*
* @default HEAD
*/
base?: {
commit: string;
};
/**
* The root of the repository.
*
Expand Down
217 changes: 159 additions & 58 deletions src/test/integration/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { getOctokit } from "@actions/github";
import { commitChangesFromRepo } from "../../git";
import { getRefTreeQuery } from "../../github/graphql/queries";
import { deleteBranches } from "./util";
import git from "isomorphic-git";

const octokit = getOctokit(ENV.GITHUB_TOKEN);

Expand Down Expand Up @@ -57,6 +58,96 @@ const expectBranchHasFile = async ({
}
};

const expectParentHasOid = async ({
branch,
oid,
}: {
branch: string;
oid: string;
}) => {
const commit = (
await getRefTreeQuery(octokit, {
owner: REPO.owner,
name: REPO.repository,
ref: `refs/heads/${branch}`,
path: "README.md",
})
).repository?.ref?.target;

if (!commit || !("parents" in commit)) {
throw new Error("Expected commit to have a parent");
}

expect(commit.parents.nodes).toEqual([{ oid }]);
};

const makeFileChanges = async (repoDirectory: string) => {
// Update an existing file
await fs.promises.writeFile(
path.join(repoDirectory, "LICENSE"),
"This is a new license",
);
// Remove a file
await fs.promises.rm(path.join(repoDirectory, "package.json"));
// Remove a file nested in a directory
await fs.promises.rm(path.join(repoDirectory, "src", "index.ts"));
// Add a new file
await fs.promises.writeFile(
path.join(repoDirectory, "new-file.txt"),
"This is a new file",
);
// Add a new file nested in a directory
await fs.promises.mkdir(path.join(repoDirectory, "nested"), {
recursive: true,
});
await fs.promises.writeFile(
path.join(repoDirectory, "nested", "nested-file.txt"),
"This is a nested file",
);
// Add files that should be ignored
await fs.promises.writeFile(
path.join(repoDirectory, ".env"),
"This file should be ignored",
);
await fs.promises.mkdir(path.join(repoDirectory, "coverage", "foo"), {
recursive: true,
});
await fs.promises.writeFile(
path.join(repoDirectory, "coverage", "foo", "bar"),
"This file should be ignored",
);
};

const makeFileChangeAssertions = async (branch: string) => {
// Expect the deleted files to not exist
await expectBranchHasFile({ branch, path: "package.json", oid: null });
await expectBranchHasFile({ branch, path: "src/index.ts", oid: null });
// Expect updated file to have new oid
await expectBranchHasFile({
branch,
path: "LICENSE",
oid: "8dd03bb8a1d83212f3667bd2eb8b92746120ab8f",
});
// Expect new files to have correct oid
await expectBranchHasFile({
branch,
path: "new-file.txt",
oid: "be5b944ff55ca7569cc2ae34c35b5bda8cd5d37e",
});
await expectBranchHasFile({
branch,
path: "nested/nested-file.txt",
oid: "60eb5af9a0c03dc16dc6d0bd9a370c1aa4e095a3",
});
// Expect ignored files to not exist
await expectBranchHasFile({ branch, path: ".env", oid: null });
await expectBranchHasFile({
branch,
path: "coverage/foo/bar",
oid: null,
});
};

describe("git", () => {
const branches: string[] = [];

Expand All @@ -72,7 +163,7 @@ describe("git", () => {
await fs.promises.mkdir(testDir, { recursive: true });
const repoDirectory = path.join(testDir, "repo-1");

// Clone the git repo locally usig the git cli and child-process
// Clone the git repo locally using the git cli and child-process
await new Promise<void>((resolve, reject) => {
const p = exec(
`git clone ${process.cwd()} repo-1`,
Expand All @@ -89,40 +180,7 @@ describe("git", () => {
p.stderr?.pipe(process.stderr);
});

// Update an existing file
await fs.promises.writeFile(
path.join(repoDirectory, "LICENSE"),
"This is a new license",
);
// Remove a file
await fs.promises.rm(path.join(repoDirectory, "package.json"));
// Remove a file nested in a directory
await fs.promises.rm(path.join(repoDirectory, "src", "index.ts"));
// Add a new file
await fs.promises.writeFile(
path.join(repoDirectory, "new-file.txt"),
"This is a new file",
);
// Add a new file nested in a directory
await fs.promises.mkdir(path.join(repoDirectory, "nested"), {
recursive: true,
});
await fs.promises.writeFile(
path.join(repoDirectory, "nested", "nested-file.txt"),
"This is a nested file",
);
// Add files that should be ignored
await fs.promises.writeFile(
path.join(repoDirectory, ".env"),
"This file should be ignored",
);
await fs.promises.mkdir(path.join(repoDirectory, "coverage", "foo"), {
recursive: true,
});
await fs.promises.writeFile(
path.join(repoDirectory, "coverage", "foo", "bar"),
"This file should be ignored",
);
await makeFileChanges(repoDirectory);

// Push the changes
await commitChangesFromRepo({
Expand All @@ -137,33 +195,76 @@ describe("git", () => {
log,
});

// Expect the deleted files to not exist
await expectBranchHasFile({ branch, path: "package.json", oid: null });
await expectBranchHasFile({ branch, path: "src/index.ts", oid: null });
// Expect updated file to have new oid
await expectBranchHasFile({
branch,
path: "LICENSE",
oid: "8dd03bb8a1d83212f3667bd2eb8b92746120ab8f",
});
// Expect new files to have correct oid
await expectBranchHasFile({
branch,
path: "new-file.txt",
oid: "be5b944ff55ca7569cc2ae34c35b5bda8cd5d37e",
await makeFileChangeAssertions(branch);

// Expect the OID to be the HEAD commit
const oid =
(
await git.log({
fs,
dir: repoDirectory,
ref: "HEAD",
depth: 1,
})
)[0]?.oid ?? "NO_OID";

await expectParentHasOid({ branch, oid });
});

it("should correctly be able to base changes off specific commit", async () => {
const branch = `${TEST_BRANCH_PREFIX}-specific-base`;

await fs.promises.mkdir(testDir, { recursive: true });
const repoDirectory = path.join(testDir, "repo-2");

// Clone the git repo locally usig the git cli and child-process
await new Promise<void>((resolve, reject) => {
const p = exec(
`git clone ${process.cwd()} repo-2`,
{ cwd: testDir },
(error) => {
if (error) {
reject(error);
} else {
resolve();
}
},
);
p.stdout?.pipe(process.stdout);
p.stderr?.pipe(process.stderr);
});
await expectBranchHasFile({
branch,
path: "nested/nested-file.txt",
oid: "60eb5af9a0c03dc16dc6d0bd9a370c1aa4e095a3",

makeFileChanges(repoDirectory);

// Determine the previous commit hash
const gitLog = await git.log({
fs,
dir: repoDirectory,
ref: "HEAD",
depth: 2,
});
// Expect ignored files to not exist
await expectBranchHasFile({ branch, path: ".env", oid: null });
await expectBranchHasFile({

const oid = gitLog[1]?.oid ?? "";

// Push the changes
await commitChangesFromRepo({
octokit,
...REPO,
branch,
path: "coverage/foo/bar",
oid: null,
message: {
headline: "Test commit",
body: "This is a test commit",
},
repoDirectory,
log,
base: {
commit: oid,
},
});

await makeFileChangeAssertions(branch);

await expectParentHasOid({ branch, oid });
});
});

Expand Down