Skip to content

Commit

Permalink
Prepare docs and release v1.0.0 (#12)
Browse files Browse the repository at this point in the history
* Add individual modules to package exports

* Import getOctokit from root of package

* Clean up interfaces & arguments

* Add initial documentation

* Add changeset

* Bump version

* Additional docs improvements
  • Loading branch information
s0 authored Aug 23, 2024
1 parent 0f8c582 commit b127b6e
Show file tree
Hide file tree
Showing 13 changed files with 398 additions and 96 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# @s0/ghcommit

## 1.0.0

### Major Changes

- be55175: First major release

## 0.1.0

### Minor Changes
Expand Down
256 changes: 256 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
# `@s0/ghcommit`

[![View on NPM](https://badgen.net/npm/v/@s0/ghcommit)](https://www.npmjs.com/package/@s0/ghcommit)

NPM / TypeScript package to commit changes GitHub repositories using the GraphQL API.

## Why?

If you or your organisation has strict requirements
around requiring signed commits (i.e. via Branch Protection or Repo Rulesets), then this can make integrating CI workflows or applications that are designed to make changes to your repos quite difficult. This is because you will need to manage your own GPG keys, assign them to machine accounts (which also means it doesn't work with GitHub Apps), and securely manage and rotate them.

Instead of doing this, if you use the GitHub API to make changes to files (such as what happens when making changes to files directly in the web UI), then GitHub's internal GPG key is used, and commits are all signed and associated with the user of the access token that was used.

(And this also works with GitHub Apps too, including the GitHub Actions app).

![](docs/verified.png)

This library has primarily been designed for use in custom Node GitHub Actions, but can be used in any Node.js or JavaScript project that needs to directly modify files in GitHub repositories.

## Usage

### Installation

Install using your favourite package manager:

```
pnpm install @s0/ghcommit
```

### Usage in github actions

All functions in this library that interact with the GitHub API require an octokit client that can execute GraphQL. If you are writing code that is designed to be run from within a GitHub Action, this can be done using the `@actions.github` library:

```ts
import { getOctokit } from "@actions/github";

const octokit = getOctokit(process.env.GITHUB_TOKEN);
```

### Importing specific modules

To allow for you to produce smaller bundle sizes, the functionality exposed in this package is grouped into specific modules that only import the packages required for their use. We recommend that you import from the specific modules rather than the root of the package.

## API

All the functions below accept a single object as its argument, and share the following base arguments:

<!-- TODO: point to some generated docs instead of including a code snippet -->

```ts
{
octokit: GitHubClient;
owner: string;
repository: string;
branch: string;
/**
* Push the commit even if the branch exists and does not match what was
* specified as the base.
*/
force?: boolean;
/**
* The commit message
*/
message: CommitMessage;
log?: Logger;
}
```

### `commitChangesFromRepo`

This function will take an existing repository on your filesystem (defaulting to the current working directory). This function is good to use if you're usually working within the context of a git repository, such as after running `@actions/checkout` in github actions.

In addition to `CommitFilesBasedArgs`, this function has the following arguments:

```ts
{
/**
* The root of the repository.
*
* @default process.cwd()
*/
repoDirectory?: string;
}
```

Example:

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

const octokit = getOctokit(process.env.GITHUB_TOKEN);

// Commit & push the files from the current directory
// e.g. if you're just using @ations/checkout
await commitChangesFromRepo({
octokit,
owner: "my-org",
repository: "my-repo",
branch: "new-branch-to-create",
message: {
headline: "[chore] do something",
},
});

// Commit & push the files from ta specific directory
// where we've cloned a repo, and made changes to files
await commitChangesFromRepo({
octokit,
owner: "my-org",
repository: "my-repo",
branch: "another-new-branch-to-create",
message: {
headline: "[chore] do something else",
},
repoDirectory: "/tmp/some-repo",
});
```

### `commitFilesFromDirectory`

This function will add or delete specific files from a repository's branch based on files found on the local filesystem. This is good to use when there are specific files that need to be updated on a branch, or if many changes may have been made locally, but only some files need to be pushed.

In addition to `CommitFilesBasedArgs`, this function has the following arguments:

```ts
{
/**
* The current branch, tag or commit that the new branch should be based on.
*/
base: GitBase;
/**
* The directory to consider the root of the repository when calculating
* file paths
*/
workingDirectory?: string;
/**
* The file paths, relative to {@link workingDirectory},
* to add or delete from the branch on GitHub.
*/
fileChanges: {
/** File paths, relative to {@link workingDirectory}, to remove from the repo. */
additions?: string[];
/** File paths, relative to the repository root, to remove from the repo. */
deletions?: string[];
};
}
```

Example:

```ts
import { getOctokit } from "@actions/github";
import { commitFilesFromDirectory } from "@s0/ghcommit/fs";

const octokit = getOctokit(process.env.GITHUB_TOKEN);

// Commit the changes to package.json and package-lock.json
// based on the main branch
await commitFilesFromDirectory({
octokit,
owner: "my-org",
repository: "my-repo",
branch: "new-branch-to-create",
message: {
headline: "[chore] do something",
},
base: {
branch: "main",
},
workingDirectory: "foo/bar",
fileChanges: {
additions: ["package-lock.json", "package.json"],
},
});

// Push just the index.html file to a new branch called docs, based off the tag v1.0.0
await commitFilesFromDirectory({
octokit,
owner: "my-org",
repository: "my-repo",
branch: "docs",
message: {
headline: "[chore] do something",
},
force: true, // Overwrite any existing branch
base: {
tag: "v1.0.0",
},
workingDirectory: "some-dir",
fileChanges: {
additions: ["index.html"],
},
});
```

### `commitFilesFromBuffers`

This function will add or delete specific files from a repository's branch based on Node.js `Buffers` that can be any binary data in memory. This is useful for when you want to make changes to a repository / branch without cloning a repo or interacting with a filesystem.

In addition to `CommitFilesBasedArgs`, this function has the following arguments:

```ts
{
/**
* The current branch, tag or commit that the new branch should be based on.
*/
base: GitBase;
/**
* The file changes, relative to the repository root, to make to the specified branch.
*/
fileChanges: {
additions?: Array<{
path: string;
contents: Buffer;
}>;
deletions?: string[];
};
}
```

Example:

```ts
import { getOctokit } from "@actions/github";
import { commitFilesFromBuffers } from "@s0/ghcommit/node";

const octokit = getOctokit(process.env.GITHUB_TOKEN);

// Add a file called hello-world
await commitFilesFromBuffers({
octokit,
owner: "my-org",
repository: "my-repo",
branch: "new-branch-to-create",
message: {
headline: "[chore] do something",
},
base: {
branch: "main",
},
fileChanges: {
additions: [
{
path: "hello/world.txt",
contents: Buffer.alloc(1024, "Hello, world!"),
},
],
},
});
```

## Other Tools / Alternatives

- [planetscale/ghcommit](https://github.com/planetscale/ghcommit) - Go library for committing to GitHub using graphql
- [planetscale/ghcommit-action](https://github.com/planetscale/ghcommit-action) - GitHub Action to detect file changes and commit using the above library
Binary file added docs/verified.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 21 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@s0/ghcommit",
"version": "0.1.0",
"version": "1.0.0",
"private": false,
"description": "Directly change files on github using the github API, to support GPG signing",
"keywords": [
Expand All @@ -23,6 +23,26 @@
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./core": {
"import": "./dist/core.mjs",
"require": "./dist/core.js",
"types": "./dist/core.d.ts"
},
"./fs": {
"import": "./dist/fs.mjs",
"require": "./dist/fs.js",
"types": "./dist/fs.d.ts"
},
"./git": {
"import": "./dist/git.mjs",
"require": "./dist/git.js",
"types": "./dist/git.d.ts"
},
"./node": {
"import": "./dist/node.mjs",
"require": "./dist/node.js",
"types": "./dist/node.d.ts"
}
},
"scripts": {
Expand Down
48 changes: 5 additions & 43 deletions src/core.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,18 @@
import type {
CommitMessage,
FileChanges,
} from "./github/graphql/generated/types.js";
import {
createCommitOnBranchQuery,
createRefMutation,
getRepositoryMetadata,
GitHubClient,
updateRefMutation,
} from "./github/graphql/queries.js";
import type {
CreateCommitOnBranchMutationVariables,
GetRepositoryMetadataQuery,
} from "./github/graphql/generated/operations.js";
import type { Logger } from "./logging.js";

export type CommitFilesResult = {
refId: string | null;
};

export type GitBase =
| {
branch: string;
}
| {
tag: string;
}
| {
commit: string;
};

export type CommitFilesFromBase64Args = {
octokit: GitHubClient;
owner: string;
repository: string;
branch: string;
/**
* The current branch, tag or commit that the new branch should be based on.
*/
base: GitBase;
/**
* Push the commit even if the branch exists and does not match what was
* specified as the base.
*/
force?: boolean;
/**
* The commit message
*/
message: CommitMessage;
fileChanges: FileChanges;
log?: Logger;
};
import {
CommitFilesFromBase64Args,
CommitFilesResult,
GitBase,
} from "./interface.js";

const getBaseRef = (base: GitBase): string => {
if ("branch" in base) {
Expand Down
20 changes: 4 additions & 16 deletions src/fs.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,11 @@
import { promises as fs } from "fs";
import * as path from "path";
import type { FileAddition } from "./github/graphql/generated/types.js";
import { CommitFilesFromBase64Args, CommitFilesResult } from "./core.js";
import { commitFilesFromBuffers } from "./node.js";

export type CommitFilesFromDirectoryArgs = Omit<
CommitFilesFromBase64Args,
"fileChanges"
> & {
/**
* The directory to consider the root of the repository when calculating
* file paths
*/
workingDirectory?: string;
fileChanges: {
additions?: string[];
deletions?: string[];
};
};
import {
CommitFilesFromDirectoryArgs,
CommitFilesResult,
} from "./interface.js";

export const commitFilesFromDirectory = async ({
workingDirectory = process.cwd(),
Expand Down
Loading

0 comments on commit b127b6e

Please sign in to comment.