Skip to content

Commit

Permalink
Normalize whitespace and improve code consistency across multiple files
Browse files Browse the repository at this point in the history
  • Loading branch information
pelikhan committed Sep 25, 2024
1 parent f55fd75 commit a09cb72
Show file tree
Hide file tree
Showing 54 changed files with 438 additions and 217 deletions.
16 changes: 14 additions & 2 deletions docs/genaisrc/genaiscript.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 14 additions & 2 deletions genaisrc/genaiscript.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 14 additions & 2 deletions packages/auto/genaiscript.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions packages/cli/src/azuretoken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ export interface AuthenticationToken {

/**
* Checks if the Azure token is expired.
*
*
* @param token - The authentication token to check.
* @returns True if the token is expired, false otherwise.
*
*
* This function avoids data races by considering the token expired slightly before
* its actual expiration time.
*/
Expand All @@ -27,10 +27,10 @@ export function isAzureTokenExpired(token: AuthenticationToken) {

/**
* Creates a new Azure authentication token.
*
*
* @param signal - An AbortSignal to allow aborting the token creation process.
* @returns A promise that resolves to an AuthenticationToken.
*
*
* Utilizes DefaultAzureCredential from the Azure Identity SDK to obtain the token.
* Logs the expiration time of the token for debugging or informational purposes.
*/
Expand All @@ -39,7 +39,7 @@ export async function createAzureToken(
): Promise<AuthenticationToken> {
// Dynamically import DefaultAzureCredential from the Azure SDK
const { DefaultAzureCredential } = await import("@azure/identity")

// Obtain the Azure token using the DefaultAzureCredential
const azureToken = await new DefaultAzureCredential().getToken(
AZURE_OPENAI_TOKEN_SCOPES.slice(),
Expand All @@ -58,6 +58,6 @@ export async function createAzureToken(
logVerbose(
`azure token expires at ${new Date(res.expiresOnTimestamp).toLocaleString()}`
)

return res
}
10 changes: 5 additions & 5 deletions packages/cli/src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@ import { emptyDir } from "fs-extra"
* This function removes all contents within the cache directory. If the 'name'
* parameter is 'tests', it specifically targets and clears a subdirectory named 'tests'
* within the cache directory.
*
* @param name - The name of the subdirectory to clear.
*
* @param name - The name of the subdirectory to clear.
* If 'tests', it targets a specific subdirectory within the cache.
*/
export async function cacheClear(name: string) {
// Get the base cache directory path using the dotGenaiscriptPath utility function.
let dir = dotGenaiscriptPath("cache")

// If the name is 'tests', adjust the directory path to include the 'tests' subdirectory.
if (["tests"].includes(name)) dir = join(dir, name)

// Log the directory being cleared to the console for debugging purposes.
console.log(`removing ${dir}`)

// Clear the contents of the directory asynchronously.
await emptyDir(dir)
}
4 changes: 2 additions & 2 deletions packages/cli/src/codequery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import { logVerbose } from "../../core/src/util"

/**
* Executes a code query using Tree-sitter on specified files and outputs the results in YAML format.
*
*
* This function utilizes Tree-sitter to perform queries on code files that match a given glob pattern.
* It respects .gitignore rules when searching for files and outputs the results in a structured YAML format.
*
*
* @param files - A glob pattern to match files for querying.
* @param query - The Tree-sitter query to be executed on each file.
*/
Expand Down
6 changes: 6 additions & 0 deletions packages/cli/src/google_generative_ai.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
// This file declares a TypeScript module for type definitions related to the Google Generative AI library.
// It helps with type-checking and auto-completion for code that interacts with this library.

declare module "@google/generative-ai"
// Declares the module "@google/generative-ai", allowing TypeScript to recognize types and interfaces
// associated with the Google Generative AI library. This declaration is crucial for seamless integration
// and development when using the library in TypeScript projects.
6 changes: 3 additions & 3 deletions packages/cli/src/grep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ import { grepSearch } from "../../core/src/grep"

/**
* Asynchronously performs a grep search pattern on given files and outputs the results.
*
*
* This function takes a search pattern and an array of file paths, and uses the `grepSearch`
* function to find matches. The results are then output to the console.
*
*
* @param pattern - The search pattern to match within files.
* @param files - An array of file paths to search within.
*/
export async function grep(pattern: string, files: string[]) {
// Perform the search using the grepSearch function and await the result
const res = await grepSearch(pattern, files)

// Output the filenames from the search results, each on a new line
console.log(res.files.map((f) => f.filename).join("\n"))
}
2 changes: 1 addition & 1 deletion packages/cli/src/help.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// This file provides a function to generate structured help documentation
// This file provides a function to generate structured help documentation
// for all CLI commands, formatted as Markdown content.

import { Command, program } from "commander"
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/annotations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ export function convertDiagnosticToGitHubActionCommand(d: Diagnostic) {
export function convertDiagnosticToAzureDevOpsCommand(d: Diagnostic) {
// Handle 'info' severity separately with a debug message.
if (d.severity === "info") return `##[debug]${d.message} at ${d.filename}`
// Construct Azure DevOps command string with necessary details.
else
// Construct Azure DevOps command string with necessary details.
return `##vso[task.logissue type=${d.severity};sourcepath=${d.filename};linenumber=${d.range[0][0]}]${d.message}`
}

Expand Down
9 changes: 2 additions & 7 deletions packages/core/src/chattypes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* This module defines TypeScript types and interfaces for chat completions using the OpenAI API.
* These types represent structured data for various chat-related functionalities.
*
*
* Tags: TypeScript, OpenAI, Chat, Types, Interfaces
*/

Expand Down Expand Up @@ -98,12 +98,7 @@ export interface ChatCompletionResponse {
variables?: Record<string, string> // Optional variables associated with the response
toolCalls?: ChatCompletionToolCall[] // List of tool calls made during the response
finishReason?: // Reason why the chat completion finished
| "stop"
| "length"
| "tool_calls"
| "content_filter"
| "cancel"
| "fail"
"stop" | "length" | "tool_calls" | "content_filter" | "cancel" | "fail"
}

// Alias for OpenAI's API error type
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,4 +242,4 @@ export const OPENAI_RETRY_DEFAULT_DEFAULT = 1000
export const TEMPLATE_ARG_FILE_MAX_TOKENS = 4000
export const TEMPLATE_ARG_DATA_SLICE_SAMPLE = 2000

export const CHAT_REQUEST_PER_MODEL_CONCURRENT_LIMIT = 5
export const CHAT_REQUEST_PER_MODEL_CONCURRENT_LIMIT = 5
33 changes: 17 additions & 16 deletions packages/core/src/copy.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
// This file defines functions related to copying and managing prompt scripts,
// including constructing file paths and handling copy operations,
// including constructing file paths and handling copy operations,
// with optional forking functionality.

import { PromptScript } from "./ast" // Import PromptScript type
import { GENAI_MJS_EXT, GENAI_SRC } from "./constants" // Import constants for file extensions and source directory
import { host } from "./host" // Import host module for file operations
import { fileExists, writeText } from "./fs" // Import file system utilities
import { PromptScript } from "./ast" // Import PromptScript type
import { GENAI_MJS_EXT, GENAI_SRC } from "./constants" // Import constants for file extensions and source directory
import { host } from "./host" // Import host module for file operations
import { fileExists, writeText } from "./fs" // Import file system utilities

/**
* Constructs the path to a prompt file.
* If `id` is null, returns the base prompt directory path.
* Otherwise, appends the `id` with a specific file extension to the path.
*
*
* @param id - Identifier for the prompt script
* @returns The file path as a string
*/
function promptPath(id: string) {
const prompts = host.resolvePath(host.projectFolder(), GENAI_SRC) // Resolve base prompt directory
if (id === null) return prompts // Return base path if id is not provided
return host.resolvePath(prompts, id + GENAI_MJS_EXT) // Construct full path if id is provided
const prompts = host.resolvePath(host.projectFolder(), GENAI_SRC) // Resolve base prompt directory
if (id === null) return prompts // Return base path if id is not provided
return host.resolvePath(prompts, id + GENAI_MJS_EXT) // Construct full path if id is provided
}

/**
* Copies a prompt script to a new location.
* Can optionally fork the script if needed, ensuring that the new filename is unique.
*
*
* @param t - The prompt script object
* @param options - Configuration options for the copy
* @param options.fork - Indicates if the script should be forked
Expand All @@ -40,19 +40,20 @@ export async function copyPrompt(
await host.createDirectory(promptPath(null))

// Determine the name for the new prompt file
const n = options?.name || t.id // Use provided name or default to script id
const n = options?.name || t.id // Use provided name or default to script id
let fn = promptPath(n)

// Handle forking logic by appending a suffix if needed
if (options.fork) {
let suff = 2
for (;;) {
fn = promptPath(n + "_" + suff) // Construct new name with suffix
if (await fileExists(fn)) { // Check if file already exists
fn = promptPath(n + "_" + suff) // Construct new name with suffix
if (await fileExists(fn)) {
// Check if file already exists
suff++
continue // Increment suffix and retry if file exists
continue // Increment suffix and retry if file exists
}
break // Exit loop if file does not exist
break // Exit loop if file does not exist
}
}

Expand All @@ -62,5 +63,5 @@ export async function copyPrompt(
// Write the prompt script to the determined path
await writeText(fn, t.jsSource)

return fn // Return the path of the copied script
return fn // Return the path of the copied script
}
6 changes: 3 additions & 3 deletions packages/core/src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ import { toHex } from "./util"

/**
* Generates a random hexadecimal string of a specified size.
*
*
* @param size - The number of bytes to generate, which will be converted to a hexadecimal string.
* @returns A string representing the randomly generated bytes in hexadecimal format.
*/
export function randomHex(size: number) {
// Create a new Uint8Array with the specified size to hold random bytes
const bytes = new Uint8Array(size)

// Fill the array with cryptographically secure random values using the Web Crypto API
crypto.getRandomValues(bytes)

// Convert the random byte array to a hexadecimal string using the toHex function and return it
return toHex(bytes)
}
36 changes: 19 additions & 17 deletions packages/core/src/dotenv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { logError } from "./util"
/**
* Safely parses a dotenv-style string into a key-value object.
* If parsing fails, logs the error and returns an empty object.
*
*
* @param text - The dotenv file content as a string
* @returns A record with key-value pairs from the dotenv file
*/
Expand All @@ -33,25 +33,27 @@ export const dotEnvParse = parse
/**
* Converts a key-value record into a dotenv-style string.
* If values contain newlines or quotes, they are enclosed in double quotes and escaped.
*
*
* @param record - An object representing key-value pairs
* @returns A dotenv-formatted string
*/
export function dotEnvStringify(record: Record<string, string>): string {
return Object.entries(record || {})
.map(([key, value]) => {
// Ensure null or undefined values are treated as empty strings
if (value === undefined || value === null) value = ""
return (
Object.entries(record || {})
.map(([key, value]) => {
// Ensure null or undefined values are treated as empty strings
if (value === undefined || value === null) value = ""

// Enclose in quotes if the value contains newlines or quotes, and escape quotes
if (value.includes("\n") || value.includes('"')) {
value = value.replace(/"/g, '\\"') // Escape existing quotes
return `${key}="${value}"`
}

// Default key-value format without quotes
return `${key}=${value}`
})
// Join all key-value pairs with newline characters for dotenv format
.join("\n")
// Enclose in quotes if the value contains newlines or quotes, and escape quotes
if (value.includes("\n") || value.includes('"')) {
value = value.replace(/"/g, '\\"') // Escape existing quotes
return `${key}="${value}"`
}

// Default key-value format without quotes
return `${key}=${value}`
})
// Join all key-value pairs with newline characters for dotenv format
.join("\n")
)
}
Loading

0 comments on commit a09cb72

Please sign in to comment.