Skip to content
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

Feat/quick demo #256

Merged
merged 2 commits into from
Sep 7, 2023
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
52 changes: 26 additions & 26 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,32 +37,32 @@ module.exports = {
},
],
"prefer-const": "error",
"import/order": [
"error",
{
groups: [
["external", "builtin"],
"unknown",
"internal",
["parent", "sibling", "index"],
],
alphabetize: {
order: "asc",
caseInsensitive: false,
},
"newlines-between": "always",
pathGroupsExcludedImportTypes: ["builtin"],
},
],
"sort-imports": [
"error",
{
ignoreCase: true,
ignoreDeclarationSort: true,
ignoreMemberSort: false,
memberSyntaxSortOrder: ["none", "all", "multiple", "single"],
},
],
// "import/order": [
// "error",
// {
// groups: [
// ["external", "builtin"],
// "unknown",
// "internal",
// ["parent", "sibling", "index"],
// ],
// alphabetize: {
// order: "asc",
// caseInsensitive: false,
// },
// "newlines-between": "always",
// pathGroupsExcludedImportTypes: ["builtin"],
// },
// ],
// "sort-imports": [
// "error",
// {
// ignoreCase: true,
// ignoreDeclarationSort: true,
// ignoreMemberSort: false,
// memberSyntaxSortOrder: ["none", "all", "multiple", "single"],
// },
// ],
"padding-line-between-statements": [
"error",
{
Expand Down
35 changes: 15 additions & 20 deletions services/core/functions/demo-review-lambda/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { logger } from "../../../../src/common/utils/logger";
import { askAI } from "../../../../src/review/llm/askAI";
import { demoPrompt } from "../../../../src/review/prompt/prompts";
import { ReviewDemoCounterEntity } from "../../entities";
import { formatResponse } from "../utils/format-response";
import { getEnvVariable, getVariableFromSSM } from "../utils/getVariable";
import { saveInputAndResponseToS3 } from "./saveInputAndResponseToS3";

Expand Down Expand Up @@ -38,10 +39,10 @@ export const main = async (
const demoReviewId = uuidv4();

if (event.body === null) {
return {
statusCode: 400,
body: "The request does not contain a body as expected.",
};
return formatResponse(
"The request does not contain a body as expected.",
400
);
}

try {
Expand All @@ -56,10 +57,10 @@ export const main = async (
const inputBody: unknown = JSON.parse(event.body);

if (!isReviewLambdaInput(inputBody)) {
return {
statusCode: 400,
body: "The request body does not contain the expected data.",
};
return formatResponse(
"The request body does not contain the expected data.",
400
);
}

await ReviewDemoCounterEntity.update({
Expand All @@ -70,10 +71,10 @@ export const main = async (
const prompt = demoPrompt + inputBody.code;

if (prompt.length > maxPromptLength) {
return {
statusCode: 400,
body: `The provided code is too large for the model ${DEFAULT_DEMO_MODEL}. Please try and provide a smaller code snippet.`,
};
return formatResponse(
`The provided code is too large for the model ${DEFAULT_DEMO_MODEL}. Please try and provide a smaller code snippet.`,
400
);
}

const { markdownReport } = await askAI(
Expand All @@ -91,16 +92,10 @@ export const main = async (
markdownReport
);

return {
statusCode: 200,
body: markdownReport,
};
return formatResponse(markdownReport, 200);
} catch (err) {
console.error(err);

return {
statusCode: 500,
body: "Error when reviewing code.",
};
return formatResponse("Error when reviewing code.", 500);
}
};
2 changes: 1 addition & 1 deletion services/core/functions/get-user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { UserEntity } from "../../entities";
import {
formatResponse,
FormattedHandlerResponse,
} from "../../helpers/format-response";
} from "../utils/format-response";

export const main = async (
event: APIGatewayProxyEvent
Expand Down
6 changes: 3 additions & 3 deletions services/core/functions/update-user/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { APIGatewayProxyEvent } from "aws-lambda";

import { encryptKey } from "./encryptKey";
import { UserEntity } from "../../entities";
import {
formatResponse,
FormattedHandlerResponse,
} from "../../helpers/format-response";
} from "../utils/format-response";
import { encryptKey } from "./encryptKey";

type UpdateUserLambdaInput = {
apiKey: string;
userId: string;
}
};

const isValidEventBody = (input: unknown): input is UpdateUserLambdaInput =>
typeof input === "object" &&
Expand Down
2 changes: 1 addition & 1 deletion services/core/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export * from "../functions/utils/format-response";
export * from "./certificates";
export * from "./domains";
export * from "./env-helpers";
export * from "./env-helpers/environment";
export * from "./format-response";
export * from "./lambda";
2 changes: 1 addition & 1 deletion services/core/helpers/lambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const cdkEsbuildConfig = {
minify: true,
keepNames: true,
sourceMap: true,
externalModules: ["aws-sdk", "aws-cdk-lib"],
externalModules: ["aws-sdk"],
platform: "node",
metafile: true,
mainFields: ["module", "main"],
Expand Down
18 changes: 11 additions & 7 deletions services/web-app/src/app/demo/page.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
"use client";
import { useSession } from "next-auth/react";
import React, { useState } from "react";
import { useState } from "react";

import BasicButton from "../../components/buttons/basicButton";
import Loading from "../../components/loading/loading";
import CodeTextArea from "../../components/textFields/codeBox";
import ReviewedCode from "../../components/textFields/reviewedCode";
import { useDemoApi } from "../../lib/api/demo/useDemoApi";

export default function Demo(): JSX.Element {
const { status } = useSession();
const [loading ] = useState(false);
const [passedText, setSyncedText] = useState<string>('');
const [displayedText, setDisplayedText] = useState<string>('');
const [loading] = useState(false);
const [passedText, setSyncedText] = useState<string>("");
const [displayedText, setDisplayedText] = useState<string>("");
const [isHidden, setIsHidden] = useState<boolean>(true);
const { postDemoReview } = useDemoApi();

const handleText = (text: string) => {
setSyncedText(text);
};

const onClick = () => {
const onClick = async () => {
setIsHidden(false);
setDisplayedText(passedText);
}
const review = await postDemoReview(passedText);

setDisplayedText(JSON.stringify(review));
};

if (status === "loading" || loading) {
return <Loading />;
Expand Down
3 changes: 1 addition & 2 deletions services/web-app/src/app/installation/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from "react";
import ReactMarkdown from "react-markdown";

import { InstallationInstructions } from "../../lib/constants";
import { InstallationInstructions } from "../../lib/installation";

export default function Installation(): JSX.Element {
return (
Expand Down
31 changes: 31 additions & 0 deletions services/web-app/src/lib/api/demo/demo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { DEMO_URL } from "../../constants";

type DemoReviewLambdaResponse = {
statusCode: number;
body: string | undefined;
};

export const postDemoReview = async (
code: string
): Promise<DemoReviewLambdaResponse> => {
try {
const response = await fetch(`${DEMO_URL}/demoReview`, {
method: "POST",
body: JSON.stringify({
code: code,
}),
headers: {
"Content-Type": "application/json",
},
});

return (await response.json()) as DemoReviewLambdaResponse;
} catch (error) {
console.log(error);

return {
statusCode: 500,
body: undefined,
};
}
};
8 changes: 8 additions & 0 deletions services/web-app/src/lib/api/demo/useDemoApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { postDemoReview } from "./demo";

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const useDemoApi = () => {
return {
postDemoReview: async (code: string) => postDemoReview(code),
};
};
102 changes: 4 additions & 98 deletions services/web-app/src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,98 +1,4 @@
export const BASE_URL = "https://9e0fli8qi6.execute-api.eu-west-2.amazonaws.com/prod";
export const InstallationInstructions = `
## We give engineers their weekends back

Code Review GPT uses Large Language Models to review code in your CI/CD pipeline. It helps streamline the code review process by providing feedback on code that may have issues or areas for improvement.

It should pick up on common issues such as:

- Exposed secrets
- Slow or inefficient code
- Unreadable code

It can also be run locally in your command line to review staged files.

Code Review GPT is in alpha and should be used for fun only. It may provide useful feedback but please check any suggestions thoroughly.

## Prerequisites

- Node.js
- Git
- Github or Gitlab CLI (optional for configure tool)

## Easy Setup in CI 🚀

In the root of your git repository run:

### Github Actions

\`\`\`shell
npm install code-review-gpt
npx code-review-gpt configure --setupTarget=github
\`\`\`

### Gitlab CI

If you are running this tool in Gitlab, you will need to do some additional setup. You will need to create a **access token** in Gitlab and store it in your CI/CD variables to allow the bot access to you Gitlab account. Follow the steps below.

#### Get Your Access Token
1. Log in to your GitLab account.
2. Go to your **Repo settings** by clicking on the repository, and selecting **Settings** -> **Access Tokens**.
3. In this section, you can generate a new access token.
4. Name your token something relevant and understandable ie. \`CODE_REVIEW-GPT-TOKEN\`. Set the scope to be \`api\` only.
5. Click the "Create personal access token" button. GitLab will generate the token and display it to you ***once***. Make sure to copy this value, we are going to use it in the next step.

#### Set Access Token as a CI/CD Variable
1. Navigate to the project where you want to add the code review bot.
2. In the left sidebar, click the **Settings** drop down, then click **CI/CD**
3. Scroll down to the **Variables** section and click the **Expand** button.This is where you can manage your CI/CD variables.
4. Create a new variable by clicking the **Add Variable** button in the CI/CD Variable table.
5. Paste your previously copied access token into the **Value** box. Name the variable \`GITLAB_TOKEN\`. Under the **Flags** section, make sure to tick the \`Mask variable\` option.

- [Un-tick the \`Protect variable\` if your branches are not protected, otherwise this variable won't be availiable for the bot to use.]
6. Save you changes. Now you can go ahead and run the following commands in you project directory.


\`\`\`shell
npm install code-review-gpt
npx code-review-gpt configure --setupTarget=gitlab
\`\`\`


See templates for example yaml files. Copy and paste them to perform a manual setup.

## Local Usage 🌈

Code Review GPT works locally to review files staged for commit:

### Scoped Install

Run \`npm i code-review-gpt && npx code-review-gpt review\` in the root directory of a git repository.

### Global Install

Run \`npm i -g code-review-gpt\` to install the tool globally.

You can now run \`code-review-gpt review\` in the root directory of any git-enabled repository on your machine.

### Commands

- \`code-review-gpt review\` - Runs the code review on the staged files.
- \`code-review-gpt configure\` - Runs a setup tool to configure the application.

- \`code-review-gpt test\` - Runs the e2e testing suite used internally in the CI in the tool repo.

### Options

- \`--ci\` - Used with the \`review\` command. Options are --ci=("github" | "gitlab"). Defaults to "github" if no option is specified. Runs the application in CI mode. This will use the BASE_SHA and GITHUB_SHA environment variables to determine which files to review. It will also use the GITHUB_TOKEN environment variable to create a comment on the pull request with the review results.

- \`--reviewType\` - Used with the 'review' command. The options are --reviewType=("changed" | "full" | "costOptimized"). Defaults to "changed" if no option is specified. Specifies whether the review is for the full file or just the changed lines. costOptimized limits the context surrounding the changed lines to 5 lines.

- \`--commentPerFile\` - Used when the \`--ci\` flag is set. Defaults to false. It enables the bot to comment the feedback on a file-by-file basis.

- \`--setupTarget\` - Used with the \`configure\` command. Options are --setupTarget=("github" | "gitlab"). Defaults to "github" if no option is specified. Specifies for which platform ('github' or 'gitlab') the project should be configured for.

- \`--model\` - The model to use for the review. Defaults to \`gpt-4\`. You can use any openai model you have access to.

- \`--debug\` - Runs the application in debug mode. This will enable debug logging.
`;
export const BASE_URL =
"https://9e0fli8qi6.execute-api.eu-west-2.amazonaws.com/prod";
export const DEMO_URL =
" https://n6r2v56qbg.execute-api.eu-west-2.amazonaws.com/prod";
Loading