Skip to content

Commit

Permalink
Merge pull request #4 from Meniole/main
Browse files Browse the repository at this point in the history
Merge main into development
  • Loading branch information
ubiquity-os-main[bot] authored Jul 7, 2024
2 parents 5a87d32 + ff9e6eb commit 318503d
Show file tree
Hide file tree
Showing 36 changed files with 1,852 additions and 524 deletions.
2 changes: 1 addition & 1 deletion .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"ignorePaths": ["**/*.json", "**/*.css", "node_modules", "**/*.log", "./src/adapters/supabase/**/**.ts"],
"useGitignore": true,
"language": "en",
"words": ["Nektos", "dataurl", "devpool", "outdir", "servedir", "Supabase", "SUPABASE", "typebox", "ubiquibot", "Smee"],
"words": ["Nektos", "dataurl", "devpool", "outdir", "servedir", "Supabase", "SUPABASE", "typebox", "ubiquibot", "Smee", "typeorm", "timespan", "mswjs"],
"dictionaries": ["typescript", "node", "software-terms"],
"import": ["@cspell/dict-typescript/cspell-ext.json", "@cspell/dict-node/cspell-ext.json", "@cspell/dict-software-terms"],
"ignoreRegExpList": ["[0-9a-fA-F]{6}"]
Expand Down
2 changes: 1 addition & 1 deletion .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -1 +1 @@

./** @gentlementlegen
2 changes: 1 addition & 1 deletion .github/knip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const config: KnipConfig = {
ignore: ["src/types/config.ts", "**/__mocks__/**", "**/__fixtures__/**"],
ignoreExportsUsedInFile: true,
// eslint can also be safely ignored as per the docs: https://knip.dev/guides/handling-issues#eslint--jest
ignoreDependencies: ["eslint-config-prettier", "eslint-plugin-prettier", "@mswjs/data"],
ignoreDependencies: ["eslint-config-prettier", "eslint-plugin-prettier"],
eslint: true,
};

Expand Down
42 changes: 30 additions & 12 deletions .github/workflows/compute.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: "the name of the plugin"
name: "Automated Merging"

on:
workflow_dispatch:
Expand All @@ -16,29 +16,47 @@ on:
ref:
description: "Ref"

# Limits to one job at a time
#concurrency:
# group: ${{ github.workflow }}


jobs:
compute:
name: "plugin name"
name: "Automated Merging"
runs-on: ubuntu-latest
permissions: write-all
env:
SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }}

steps:
- uses: actions/checkout@v4

- name: setup node
- name: Setup node
uses: actions/setup-node@v4
with:
node-version: "20.10.0"

- name: install dependencies
run: yarn
- name: Install dependencies
run: yarn install --immutable --immutable-cache --check-cache

- name: execute directive
- run: ${{ toJSON(inputs) }}
shell: cat {0}

- name: Execute directive
run: npx tsx ./src/main.ts
id: plugin-name
id: automated-merging

- name: Commit and Push DB updates
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git config --global pull.rebase false
git add database/sql.db
if [ -n "$(git diff-index --cached --name-only HEAD)" ]; then
git commit -m "chore: [skip ci] updated database" || echo "Lint-staged check failed"
git pull -X ours
git push origin main
else
echo "No changes to commit"
fi
env:
SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
1 change: 1 addition & 0 deletions .github/workflows/release-please.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ jobs:
- uses: googleapis/release-please-action@v4
with:
release-type: simple
target-branch: main
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ coverage
junit.xml
cypress/screenshots
script.ts
.wrangler
.wrangler
test-dashboard.md
database/tests/*
99 changes: 15 additions & 84 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,93 +1,24 @@
# `@ubiquibot/plugin-template`
# `@ubiquibot/automated-merging`

## Prerequisites
Automatically merge pull-requests based on the reviewer count, the time elapsed since the last activity, depending
on the association of the pull-request author.

- A good understanding of how the [kernel](https://github.com/ubiquity/ubiquibot-kernel) works and how to interact with it.
- A basic understanding of the Ubiquibot configuration and how to define your plugin's settings.

## Getting Started

1. Create a new repository using this template.
2. Clone the repository to your local machine.
3. Install the dependencies preferably using `yarn` or `bun`.

## Creating a new plugin

- If your plugin is to be used as a slash command which should have faster response times as opposed to longer running GitHub action tasks, you should use the `worker` type.

1. Ensure you understand and have setup the [kernel](https://github.com/ubiquity/ubiquibot-kernel).
2. Update [compute.yml](./.github/workflows/compute.yml) with your plugin's name and update the `id`.
3. Update [context.ts](./src/types/context.ts) with the events that your plugin will fire on.
4. Update [plugin-inputs.ts](./src/types/plugin-inputs.ts) to match the `with:` settings in your org or repo level configuration.

- Your plugin config should look similar to this:
## Configuration example

```yml
- plugin: <plugin-org/owner>/<plugin-repo-name>:compute.yml@development
name: plugin-name
id: plugin-name-command
description: "Plugin description" # small description of what the plugin does
command: "<regex for command>" # if you are creating a plugin with a slash command
example: "<example usage>" # how to invoke the slash command
- plugin: ubiquibot/automated-merging
name: automated-merging
id: automated-merging
description: "Automatically merge pull-requests"
with: # these are the example settings, the kernel passes these to the plugin.
disabledCommands: []
timers:
reviewDelayTolerance: 86000
taskStaleTimeoutDuration: 2580000
miscellaneous:
maxConcurrentTasks: 3
labels:
time: []
priority: []
collaboratorMinimumApprovalsRequired: 1
contributorMinimumApprovalsRequired: 2
collaboratorMergeTimeout: "3.5 days"
contributorMergeTimeout: "7 days"
```
###### At this stage, your plugin will fire on your defined events with the required settings passed in from the kernel. You can now start writing your plugin's logic.
5. Start building your plugin by adding your logic to the [plugin.ts](./src/plugin.ts) file.
## Testing a plugin
### Worker Plugins
## Testing
- `yarn/bun worker` - to run the worker locally.
- To trigger the worker, `POST` requests to http://localhost:4000/ with an event payload similar to:

```ts
await fetch("http://localhost:4000/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
stateId: "",
eventName: "",
eventPayload: "",
settings: "",
ref: "",
authToken: "",
}),
});
```shell
yarn test
```

A full example can be found [here](https://github.com/ubiquibot/assistive-pricing/blob/623ea3f950f04842f2d003bda3fc7b7684e41378/tests/http/request.http).

### Action Plugins

- Ensure the kernel is running and listening for events.
- Fire an event in/to the repo where the kernel is installed. This can be done in a number of ways, the easiest being via the GitHub UI or using the GitHub API, such as posting a comment, opening an issue, etc in the org/repo where the kernel is installed.
- The kernel will process the event and dispatch it using the settings defined in your `.ubiquibot-config.yml`.
- The `compute.yml` workflow will run and execute your plugin's logic.
- You can view the logs in the Actions tab of your repo.

[Nektos Act](https://github.com/nektos/act) - a tool for running GitHub Actions locally.

## More information

- [Full Ubiquibot Configuration](https://github.com/ubiquity/ubiquibot/blob/0fde7551585499b1e0618ec8ea5e826f11271c9c/src/types/configuration-types.ts#L62) - helpful for defining your plugin's settings as they are strongly typed and will be validated by the kernel.
- [Ubiquibot V1](https://github.com/ubiquity/ubiquibot) - helpful for porting V1 functionality to V2, helper/utility functions, types, etc. Everything is based on the V1 codebase but with a more modular approach. When using V1 code, keep in mind that most all code will need refactored to work with the new V2 architecture.

## Examples

- [Start/Stop Slash Command](https://github.com/ubq-testing/start-stop-module) - simple
- [Assistive Pricing Plugin](https://github.com/ubiquibot/assistive-pricing) - complex
- [Conversation Rewards](https://github.com/ubiquibot/conversation-rewards) - really complex
Binary file added database/sql.db
Binary file not shown.
15 changes: 11 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "plugin-template",
"name": "@ubiquibot/automated-merging",
"version": "1.0.0",
"description": "Ubiquibot plugin template repository with TypeScript support.",
"description": "Automatically merge pull-requests.",
"author": "Ubiquity DAO",
"license": "MIT",
"main": "src/worker.ts",
Expand Down Expand Up @@ -32,9 +32,14 @@
"@octokit/rest": "20.1.1",
"@octokit/webhooks": "13.2.7",
"@sinclair/typebox": "0.32.33",
"@supabase/supabase-js": "2.43.5",
"@ubiquity-dao/ubiquibot-logger": "1.2.0",
"dotenv": "16.4.5",
"typebox-validators": "0.3.5"
"ms": "2.1.3",
"reflect-metadata": "0.2.2",
"sqlite3": "5.1.7",
"ts-retry": "4.2.5",
"typebox-validators": "0.3.5",
"typeorm": "0.3.20"
},
"devDependencies": {
"@commitlint/cli": "19.3.0",
Expand All @@ -45,6 +50,7 @@
"@eslint/js": "9.5.0",
"@jest/globals": "29.7.0",
"@mswjs/data": "0.16.1",
"@types/ms": "0.7.34",
"@types/node": "20.14.5",
"cspell": "8.9.0",
"eslint": "9.5.0",
Expand All @@ -58,6 +64,7 @@
"jest-md-dashboard": "0.8.0",
"knip": "5.21.2",
"lint-staged": "15.2.7",
"msw": "2.3.1",
"npm-run-all": "4.1.5",
"prettier": "3.3.2",
"ts-jest": "29.1.5",
Expand Down
52 changes: 52 additions & 0 deletions src/action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import * as github from "@actions/github";
import { Octokit } from "@octokit/rest";
import { Value } from "@sinclair/typebox/value";
import { plugin } from "./plugin";
import { envSchema, PluginInputs, pluginSettingsSchema, pluginSettingsValidator } from "./types";

/**
* How a GitHub action executes the plugin.
*/
export async function run() {
const payload = github.context.payload.inputs;

payload.env = { ...(payload.env || {}), workflowName: github.context.workflow };
const env = Value.Decode(envSchema, payload.env || {});

payload.settings = Value.Default(pluginSettingsSchema, JSON.parse(payload.settings));
if (!pluginSettingsValidator.test(payload.settings)) {
const errors: string[] = [];
for (const error of pluginSettingsValidator.errors(payload.settings)) {
console.error(error);
errors.push(`${error.path}: ${error.message}`);
}
throw new Error(`Invalid settings provided:\n${errors.join(";\n")}`);
}

const settings = Value.Decode(pluginSettingsSchema, payload.settings);
const inputs: PluginInputs = {
stateId: payload.stateId,
eventName: payload.eventName,
eventPayload: JSON.parse(payload.eventPayload),
settings,
authToken: payload.authToken,
ref: payload.ref,
};

await plugin(inputs, env);

return returnDataToKernel(inputs.authToken, inputs.stateId, {});
}

async function returnDataToKernel(repoToken: string, stateId: string, output: object) {
const octokit = new Octokit({ auth: repoToken });
return octokit.repos.createDispatchEvent({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
event_type: "return_data_to_ubiquibot_kernel",
client_payload: {
state_id: stateId,
output: JSON.stringify(output),
},
});
}
18 changes: 6 additions & 12 deletions src/adapters/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
import { SupabaseClient } from "@supabase/supabase-js";
import { Context } from "../types/context";
import { Access } from "./supabase/helpers/access";
import { User } from "./supabase/helpers/user";
import { Label } from "./supabase/helpers/label";
import { Super } from "./supabase/helpers/supabase";
import { DataSource } from "typeorm";
import { Context } from "../types";
import { PullRequestAdapter } from "./sqlite/helpers/pull-request-adapter";

export function createAdapters(supabaseClient: SupabaseClient, context: Context) {
export function createAdapters(sqlClient: DataSource, context: Context) {
return {
supabase: {
access: new Access(supabaseClient, context),
user: new User(supabaseClient, context),
label: new Label(supabaseClient, context),
super: new Super(supabaseClient, context),
sqlite: {
pullRequest: new PullRequestAdapter(sqlClient, context),
},
};
}
15 changes: 15 additions & 0 deletions src/adapters/sqlite/data-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { DataSource } from "typeorm";
import { PullRequest } from "./entities/pull-request";

export async function initializeDataSource(databaseUrl: string) {
const dataSource = new DataSource({
type: "sqlite",
database: databaseUrl,
synchronize: true,
logging: true,
entities: [PullRequest],
subscribers: [],
migrations: [],
});
return dataSource.initialize();
}
13 changes: 13 additions & 0 deletions src/adapters/sqlite/entities/pull-request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class PullRequest extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;

@Column({ unique: true, type: "text" })
url: string;

@Column({ type: "datetime" })
lastActivity: Date;
}
Loading

0 comments on commit 318503d

Please sign in to comment.