diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..2ce54b1 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +All notable changes to this project will be documented in this file. + + diff --git a/cliff.toml b/cliff.toml new file mode 100644 index 0000000..7beeaca --- /dev/null +++ b/cliff.toml @@ -0,0 +1,83 @@ +# git-cliff ~ default configuration file +# https://git-cliff.org/docs/configuration +# +# Lines starting with "#" are comments. +# Configuration options are organized into tables and keys. +# See documentation for more information on available options. + +[changelog] +# changelog header +header = """ +# Changelog\n +All notable changes to this project will be documented in this file.\n +""" +# template for the changelog body +# https://keats.github.io/tera/docs/#introduction +body = """ +{% if version %}\ + ## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }} +{% else %}\ + ## [unreleased] +{% endif %}\ +{% for group, commits in commits | group_by(attribute="group") %} + ### {{ group | upper_first }} + {% for commit in commits %} + - {% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }}\ + {% endfor %} +{% endfor %}\n +""" +# remove the leading and trailing whitespace from the template +trim = true +# changelog footer +footer = """ + +""" +# postprocessors +postprocessors = [ + # { pattern = '', replace = "https://github.com/orhun/git-cliff" }, # replace repository URL +] +[git] +# parse the commits based on https://www.conventionalcommits.org +conventional_commits = true +# filter out the commits that are not conventional +filter_unconventional = true +# process each line of a commit as an individual commit +split_commits = false +# regex for preprocessing the commit messages +commit_preprocessors = [ + # { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, # replace issue numbers +] +# regex for parsing and grouping commits +commit_parsers = [ + { message = "^feat", group = "Features" }, + { message = "^fix", group = "Bug Fixes" }, + { message = "^doc", group = "Documentation" }, + { message = "^perf", group = "Performance" }, + { message = "^refactor", group = "Refactor" }, + { message = "^style", group = "Styling" }, + { message = "^test", group = "Testing" }, + { message = "^chore\\(release\\): prepare for", skip = true }, + { message = "^chore\\(deps\\)", skip = true }, + { message = "^chore\\(pr\\)", skip = true }, + { message = "^chore\\(pull\\)", skip = true }, + { message = "^chore|ci", group = "Miscellaneous Tasks" }, + { body = ".*security", group = "Security" }, + { message = "^revert", group = "Revert" }, +] +# protect breaking changes from being skipped due to matching a skipping commit_parser +protect_breaking_commits = false +# filter out the commits that are not matched by commit parsers +filter_commits = false +# regex for matching git tags +tag_pattern = "v[0-9].*" + +# regex for skipping tags +skip_tags = "v0.1.0-beta.1" +# regex for ignoring tags +ignore_tags = "" +# sort the tags topologically +topo_order = false +# sort the commits inside sections by oldest/newest order +sort_commits = "oldest" +# limit the number of commits included in the changelog. +# limit_commits = 42 diff --git a/package.json b/package.json index eba9472..b5e101d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ebenjs/gpt-shell", - "version": "1.0.0", + "version": "1.1.1", "description": "Chat-GPT in the console", "main": "index.js", "type": "module", diff --git a/src/main.js b/src/main.js index 1211b0d..59c2fc9 100644 --- a/src/main.js +++ b/src/main.js @@ -4,17 +4,26 @@ import { sendOpenApiRequest } from "./request-helper.js"; import { logger } from "./utilities/logger.js"; export const ask = (prompt) => { - sendOpenApiRequest(prompt).then((data) => { - logger.logResponse(data.choices[0].message.content); - }); + sendOpenApiRequest(prompt) + .then((data) => { + logger.logResponse(data.choices[0].message.content); + }) + .catch((error) => { + logger.logError(JSON.parse(error.message)); + }); }; export const configure = (args) => { + let existingConfig = null; + if (fs.existsSync("./.gpt-shell-config.json")) { + existingConfig = JSON.parse(fs.readFileSync("./.gpt-shell-config.json")); + } + const { apikey, model, url } = args; const config = { - apikey: apikey || process.env.OPENAI_API_KEY, - model: model || process.env.OPENAI_DEFAULT_MODEL, - url: url || process.env.OPENAI_API_URL, + apikey: apikey || existingConfig?.apikey || process.env.OPENAI_API_KEY, + model: model || existingConfig?.model || process.env.OPENAI_DEFAULT_MODEL, + url: url || existingConfig?.url || process.env.OPENAI_API_URL, }; fs.writeFileSync("./.gpt-shell-config.json", JSON.stringify(config, null, 2)); diff --git a/src/request-helper.js b/src/request-helper.js index 8d06953..cc5e42d 100644 --- a/src/request-helper.js +++ b/src/request-helper.js @@ -6,20 +6,26 @@ export const sendOpenApiRequest = async (requestPrompt) => { logger.logPrompt(requestPrompt + "\n"); const animation = loadingAnimation(); - console.log(getConfig()); + const config = getConfig(); + + if (config.status === "error") { + clearInterval(animation); + process.stdout.write("\r"); + throw new Error(JSON.stringify(config.errors)); + } const requestOptions = { method: "POST", headers: { "Content-Type": "application/json", - Authorization: "Bearer " + getConfig().apikey, + Authorization: "Bearer " + getConfig().config.apikey, }, body: JSON.stringify({ - model: getConfig().model, + model: getConfig().config.model, messages: [{ role: "user", content: requestPrompt }], }), }; - const response = await fetch(getConfig().url, requestOptions); + const response = await fetch(getConfig().config.url, requestOptions); const data = await response.json(); clearInterval(animation); diff --git a/src/utilities/error-handling.js b/src/utilities/error-handling.js new file mode 100644 index 0000000..73d247d --- /dev/null +++ b/src/utilities/error-handling.js @@ -0,0 +1,21 @@ +import { logger } from "./logger.js"; + +let aggregatedErrors = []; + +export const addError = (error) => { + aggregatedErrors.push(error); +}; + +export const getErrors = () => aggregatedErrors; + +export const clearErrors = () => (aggregatedErrors = []); + +export const logErrors = () => { + aggregatedErrors.forEach((error) => { + logger.logError(error); + }); +}; + +export const throwError = (message) => { + throw new Error(message); +}; diff --git a/src/utilities/get-config.js b/src/utilities/get-config.js index 946902f..4ba228a 100644 --- a/src/utilities/get-config.js +++ b/src/utilities/get-config.js @@ -1,9 +1,30 @@ import fs from "fs"; +import { getErrors, addError } from "./error-handling.js"; + +const checkForRequiredEnvironmentVariables = (config) => { + if (!config.apikey) { + addError("OPENAI_API_KEY is not defined"); + } + + if (!config.model) { + addError("OPENAI_MODEL is not defined"); + } + + if (!config.url) { + addError("OPENAI_API_URL is not defined"); + } + + return !getErrors().length > 0; +}; export const getConfig = () => { if (fs.existsSync("./.gpt-shell-config.json")) { const config = JSON.parse(fs.readFileSync("./.gpt-shell-config.json")); - return config; + if (!checkForRequiredEnvironmentVariables(config)) { + return { status: "error", errors: getErrors() }; + } + + return { status: "success", config: config }; } const config = { @@ -12,5 +33,9 @@ export const getConfig = () => { url: process.env.OPENAI_API_URL, }; - return config; + if (!checkForRequiredEnvironmentVariables(config)) { + return { status: "error", errors: getErrors() }; + } + + return { status: "success", config: config }; }; diff --git a/src/utilities/logger.js b/src/utilities/logger.js index 7c657ef..529f449 100644 --- a/src/utilities/logger.js +++ b/src/utilities/logger.js @@ -9,6 +9,16 @@ const customPromptLoggerFormat = winston.format.printf(({ message }) => { return `${chalk.blueBright("[gpt-shell-prompt]")} : ${message}`; }); +const customErrorLoggerFormat = winston.format.printf(({ message }) => { + return chalk.redBright("[error] : " + message); +}); + +const customPrefixedErrorLoggerFormat = (prefix) => { + return winston.format.printf(({ message }) => { + return chalk.redBright(prefix + message); + }); +}; + const _logger = winston.createLogger({ level: "info", transports: [ @@ -35,8 +45,18 @@ const logResponse = (response) => { _logger.info(response); }; +const logError = (errors) => { + _logger.format = customErrorLoggerFormat; + _logger.error("Some configuration errors were found"); + errors.forEach((error, index) => { + _logger.format = customPrefixedErrorLoggerFormat(`[${index}] `); + _logger.error(error); + }); +}; + export const logger = { default: _logger, logPrompt, logResponse, + logError, };