Skip to content

Commit

Permalink
feat: development config
Browse files Browse the repository at this point in the history
  • Loading branch information
whilefoo committed Oct 7, 2024
1 parent 024dd90 commit 94e2685
Show file tree
Hide file tree
Showing 8 changed files with 113 additions and 21 deletions.
Binary file modified bun.lockb
Binary file not shown.
3 changes: 3 additions & 0 deletions src/github/github-event-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { CloudflareKv } from "./utils/cloudflare-kv";
import { PluginChainState } from "./types/plugin";

export type Options = {
environment: "production" | "development";
webhookSecret: string;
appId: string | number;
privateKey: string;
Expand All @@ -19,11 +20,13 @@ export class GitHubEventHandler {
public onError: Webhooks<SimplifiedContext>["onError"];
public pluginChainState: CloudflareKv<PluginChainState>;

readonly environment: "production" | "development";
private readonly _webhookSecret: string;
private readonly _privateKey: string;
private readonly _appId: number;

constructor(options: Options) {
this.environment = options.environment;
this._privateKey = options.privateKey;
this._appId = Number(options.appId);
this._webhookSecret = options.webhookSecret;
Expand Down
1 change: 1 addition & 0 deletions src/github/types/env.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Type as T, type Static } from "@sinclair/typebox";

export const envSchema = T.Object({
ENVIRONMENT: T.Union([T.Literal("production"), T.Literal("development")]),
APP_WEBHOOK_SECRET: T.String({ minLength: 1 }),
APP_ID: T.String({ minLength: 1 }),
APP_PRIVATE_KEY: T.String({ minLength: 1 }),
Expand Down
3 changes: 2 additions & 1 deletion src/github/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { configSchema, configSchemaValidator, PluginConfiguration } from "../typ
import { getManifest } from "./plugins";

export const CONFIG_FULL_PATH = ".github/.ubiquibot-config.yml";
export const DEV_CONFIG_FULL_PATH = ".github/.ubiquibot-config.dev.yml";
export const CONFIG_ORG_REPO = "ubiquibot-config";

export async function getConfigurationFromRepo(context: GitHubContext, repository: string, owner: string) {
Expand Down Expand Up @@ -143,7 +144,7 @@ async function download({ context, repository, owner }: { context: GitHubContext
const { data } = await context.octokit.rest.repos.getContent({
owner,
repo: repository,
path: CONFIG_FULL_PATH,
path: context.eventHandler.environment === "production" ? CONFIG_FULL_PATH : DEV_CONFIG_FULL_PATH,
mediaType: { format: "raw" },
});
return data as unknown as string; // this will be a string if media format is raw
Expand Down
1 change: 1 addition & 0 deletions src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default {
const signatureSha256 = getSignature(request);
const id = getId(request);
const eventHandler = new GitHubEventHandler({
environment: env.ENVIRONMENT,
webhookSecret: env.APP_WEBHOOK_SECRET,
appId: env.APP_ID,
privateKey: env.APP_PRIVATE_KEY,
Expand Down
106 changes: 91 additions & 15 deletions tests/configuration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "@jest/glob
import { config } from "dotenv";
import { server } from "./__mocks__/node";
import "./__mocks__/webhooks";
import { getConfig } from "../src/github/utils/config";
import { CONFIG_FULL_PATH, DEV_CONFIG_FULL_PATH, getConfig } from "../src/github/utils/config";
import { GitHubContext } from "../src/github/github-context";
import { GitHubEventHandler } from "../src/github/github-event-handler";
import { getManifest } from "../src/github/utils/plugins";
Expand All @@ -12,6 +12,15 @@ import { shouldSkipPlugin } from "../src/github/handlers";
config({ path: ".dev.vars" });

const issueOpened = "issues.opened";
const manifestPath = "manifest.json";
const repo = {
owner: { login: "ubiquity" },
name: "conversation-rewards",
};

const eventHandler = {
environment: "production",
} as GitHubEventHandler;

beforeAll(() => {
server.listen();
Expand All @@ -27,7 +36,7 @@ describe("Configuration tests", () => {
it("Should properly parse the Action path if a branch and workflow are specified", async () => {
function getContent(args: RestEndpointMethodTypes["repos"]["getContent"]["parameters"]) {
let data: string;
if (args.path === "manifest.json") {
if (args.path === manifestPath) {
data = `
{
"name": "plugin",
Expand All @@ -39,14 +48,16 @@ describe("Configuration tests", () => {
}
}
`;
} else {
} else if (args.path === CONFIG_FULL_PATH) {
data = `
plugins:
- uses:
- plugin: ubiquity/user-activity-watcher:compute.yml@fork/pull/1
with:
settings1: 'enabled'
skipBotEvents: false`;
} else {
throw new Error("Not Found");
}

if (args.mediaType === undefined || args.mediaType?.format === "base64") {
Expand All @@ -65,10 +76,7 @@ describe("Configuration tests", () => {
name: issueOpened,
id: "",
payload: {
repository: {
owner: { login: "ubiquity" },
name: "conversation-rewards",
},
repository: repo,
} as unknown as GitHubContext<"issues.closed">["payload"],
octokit: {
rest: {
Expand All @@ -77,7 +85,7 @@ describe("Configuration tests", () => {
},
},
},
eventHandler: {} as GitHubEventHandler,
eventHandler: eventHandler,
} as unknown as GitHubContext);
expect(cfg.plugins[0]).toEqual({
uses: [
Expand Down Expand Up @@ -167,7 +175,7 @@ describe("Configuration tests", () => {
it("should not skip bot event if skipBotEvents is set to false", async () => {
function getContent(args: RestEndpointMethodTypes["repos"]["getContent"]["parameters"]) {
let data: string;
if (args.path === "manifest.json") {
if (args.path === manifestPath) {
data = `
{
"name": "plugin",
Expand All @@ -179,14 +187,16 @@ describe("Configuration tests", () => {
}
}
`;
} else {
} else if (args.path === CONFIG_FULL_PATH) {
data = `
plugins:
- uses:
- plugin: ubiquity/test-plugin
with:
settings1: 'enabled'
skipBotEvents: false`;
} else {
throw new Error("Not Found");
}

if (args.mediaType === undefined || args.mediaType?.format === "base64") {
Expand All @@ -205,10 +215,7 @@ describe("Configuration tests", () => {
name: issueOpened,
id: "",
payload: {
repository: {
owner: { login: "ubiquity" },
name: "conversation-rewards",
},
repository: repo,
sender: {
type: "Bot",
},
Expand All @@ -220,11 +227,80 @@ describe("Configuration tests", () => {
},
},
},
eventHandler: {} as GitHubEventHandler,
eventHandler: eventHandler,
} as unknown as GitHubContext;

const cfg = await getConfig(context);
expect(cfg.plugins[0].skipBotEvents).toEqual(false);
await expect(shouldSkipPlugin(context, cfg.plugins[0])).resolves.toEqual(false);
});
it("should return dev config if environment is not production", async () => {
function getContent(args: RestEndpointMethodTypes["repos"]["getContent"]["parameters"]) {
let data: string;
if (args.path === manifestPath) {
data = `
{
"name": "plugin",
"commands": {
"command": {
"description": "description",
"ubiquity:example": "example"
}
}
}
`;
} else if (args.path === CONFIG_FULL_PATH) {
data = `
plugins:
- uses:
- plugin: ubiquity/production-plugin
with:
settings1: 'enabled'`;
} else if (args.path === DEV_CONFIG_FULL_PATH) {
data = `
plugins:
- uses:
- plugin: ubiquity/test-plugin
with:
settings1: 'enabled'`;
} else {
throw new Error("Not Found");
}

if (args.mediaType === undefined || args.mediaType?.format === "base64") {
return {
data: {
content: Buffer.from(data).toString("base64"),
},
};
} else if (args.mediaType?.format === "raw") {
return { data };
}
}

const context = {
key: issueOpened,
name: issueOpened,
id: "",
payload: {
repository: repo,
} as unknown as GitHubContext<"issues.closed">["payload"],
octokit: {
rest: {
repos: {
getContent,
},
},
},
eventHandler: { environment: "development" } as GitHubEventHandler,
} as unknown as GitHubContext;

const cfg = await getConfig(context);
expect(cfg.plugins[0].uses[0].plugin).toMatchObject({ owner: "ubiquity", repo: "test-plugin" });

context.eventHandler = { environment: "production" } as GitHubEventHandler;

const cfg2 = await getConfig(context);
expect(cfg2.plugins[0].uses[0].plugin).toMatchObject({ owner: "ubiquity", repo: "production-plugin" });
});
});
6 changes: 5 additions & 1 deletion tests/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ afterAll(() => {
server.close();
});

const eventHandler = {
environment: "production",
} as GitHubEventHandler;

describe("Event related tests", () => {
beforeEach(() => {
server.use(
Expand Down Expand Up @@ -99,7 +103,7 @@ describe("Event related tests", () => {
},
},
},
eventHandler: {} as GitHubEventHandler,
eventHandler: eventHandler,
payload: {
repository: {
owner: { login: "ubiquity" },
Expand Down
14 changes: 10 additions & 4 deletions tests/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ jest.mock("@octokit/core", () => ({

const issueOpened = "issues.opened";

const eventHandler = {
environment: "production",
} as GitHubEventHandler;

config({ path: ".dev.vars" });

beforeAll(() => {
Expand Down Expand Up @@ -58,6 +62,7 @@ describe("Worker tests", () => {
const req = new Request("http://localhost:8080");
const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => jest.fn());
const res = await worker.fetch(req, {
ENVIRONMENT: "production",
APP_WEBHOOK_SECRET: "",
APP_ID: "",
APP_PRIVATE_KEY: "",
Expand All @@ -76,6 +81,7 @@ describe("Worker tests", () => {
},
});
const res = await worker.fetch(req, {
ENVIRONMENT: "production",
APP_WEBHOOK_SECRET: "webhook-secret",
APP_ID: "app-id",
APP_PRIVATE_KEY: "private-key",
Expand All @@ -95,7 +101,7 @@ describe("Worker tests", () => {
repository: "",
},
octokit: {},
eventHandler: {} as GitHubEventHandler,
eventHandler: eventHandler,
} as unknown as GitHubContext);
expect(cfg).toBeTruthy();
});
Expand All @@ -119,7 +125,7 @@ describe("Worker tests", () => {
},
},
},
eventHandler: {} as GitHubEventHandler,
eventHandler: eventHandler,
} as unknown as GitHubContext);
expect(cfg).toBeTruthy();
});
Expand Down Expand Up @@ -151,7 +157,7 @@ describe("Worker tests", () => {
},
},
},
eventHandler: {} as GitHubEventHandler,
eventHandler: eventHandler,
} as unknown as GitHubContext);
expect(cfg).toBeTruthy();
const pluginChain = cfg.plugins;
Expand Down Expand Up @@ -233,7 +239,7 @@ describe("Worker tests", () => {
},
},
},
eventHandler: {} as GitHubEventHandler,
eventHandler: eventHandler,
} as unknown as GitHubContext);
expect(cfg.plugins[0]).toEqual({
uses: [
Expand Down

0 comments on commit 94e2685

Please sign in to comment.