Skip to content

Commit

Permalink
feat: replace .env with .codeshift.config.toml
Browse files Browse the repository at this point in the history
fix: always call process.exit with 1
  • Loading branch information
uday-rana committed Nov 21, 2024
1 parent 0bd41da commit 519515c
Show file tree
Hide file tree
Showing 21 changed files with 191 additions and 278 deletions.
7 changes: 7 additions & 0 deletions .codeshift.config.toml.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[settings]
baseUrl="xxxxxxxxxxxxxxxxxx"
apiKey="sk-xxxxxxxxxxx"
outputFile="xxxxxxxxxxx"
model="xxxxxxxxxxxx"
tokenUsage=false
stream=false
3 changes: 0 additions & 3 deletions .codeshift.toml.example

This file was deleted.

2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,5 @@ dist
# Finder (MacOS) folder config
.DS_Store

# Codeshift config file
.codeshift.config.toml
58 changes: 24 additions & 34 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,31 +28,35 @@ Codeshift is a command-line tool to translate and transform source code files be

- Run `npm install -g @uday-rana/codeshift`.

- Create a file called `.env` by copying the `.env.example` file

- Add your API key, preferred base URL, and preferred model. It should look similar to the example below:

- For OpenAI, use the base URL `https://api.openai.com/v1`
- For OpenRouter, use the base URL `https://openrouter.ai/api/v1`
- For Groq, use the base URL `https://api.groq.com/openai/v1`.
- For a list of models for each provider, see:

- Run `npx codeshift`. This will generate a `.codeshift.config.toml` file in the current directory.

- In `.codeshift.config.toml`, set the base URL for your preferred provider and add your API key. It should look something like this:

```toml
# .codeshift.config.toml

[settings]
baseUrl="https://openrouter.ai/api/v1"
apiKey="sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
outputFile="xxxxxxxxxxx"
model=""
tokenUsage=true
stream=true
```

- The following base URLs are supported. Others may be used but are not supported and may cause errors:
- OpenAI: `https://api.openai.com/v1`
- OpenRouter: `https://openrouter.ai/api/v1`
- Groq: `https://api.groq.com/openai/v1`.
- For a list of models for supported providers, see:
- [OpenAI models](https://platform.openai.com/docs/models)
- [OpenRouter models](https://openrouter.ai/models)
- [Groq models](https://console.groq.com/docs/models)

```bash
# .env

API_KEY=YOUR_API_KEY_HERE
BASE_URL=https://api.groq.com/openai/v1
MODEL=llama3-8b-8192
```

## Usage

```bash
codeshift [options] <output-language> <input-files...>
npx codeshift [options] <output-language> <input-files...>
```

### Arguments
Expand All @@ -64,33 +68,19 @@ codeshift [options] <output-language> <input-files...>

- `-o, --output`: Specify filename to write output to
- `-t, --token-usage`: Display the number of tokens used by the AI for processing
- `-s, --stream`: Stream the response from the LLM.
- `-h, --help`: Display the help message explaining usage, options, and arguments
- `-v, --version`: Display the program name and version number

### Example

```bash
# Converts a JavaScript file (index.js) to Go, saving the output in index.go
codeshift -o index.go go examples/index.js
npx codeshift -o index.go go examples/index.js
```

![codeshift file output demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tqlkq2d1495e6qps5wz3.gif)

## Configuration File

Options can be set in a TOML file located in your home directory: `~/.codeshift.toml`. Supported options are:

- `--output="filename"`
- `--token-usage=true|false`

### Example

```toml
[settings]
output="output.go"
tokenUsage=true
```

## Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md)
Expand Down
52 changes: 0 additions & 52 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,75 +7,55 @@
const config = {
// All imported modules in your tests should be mocked automatically
// automock: false,

// Stop running tests after `n` failures
// bail: 0,

// The directory where Jest should store its cached dependency information
// cacheDirectory: "/tmp/jest_rs",

// Automatically clear mock calls, instances, contexts and results before every test
// clearMocks: false,

// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,

// The directory where Jest should output its coverage files
// coverageDirectory: undefined,

// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],

// Indicates which provider should be used to instrument code for coverage
// coverageProvider: "babel",

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,

// A path to a custom dependency extractor
// dependencyExtractor: undefined,

// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,

// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },

// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],

// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,

// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,

// A set of global variables that need to be available in all test environments
// globals: {},

// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",

// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],

// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
Expand All @@ -87,110 +67,78 @@ const config = {
// "json",
// "node"
// ],

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],

// Activates notifications for test results
// notify: false,

// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",

// A preset that is used as a base for Jest's configuration
// preset: undefined,

// Run tests from one or more projects
// projects: undefined,

// Use this configuration option to add custom reporters to Jest
// reporters: undefined,

// Automatically reset mock state before every test
// resetMocks: false,

// Reset the module registry before running each individual test
// resetModules: false,

// A path to a custom resolver
// resolver: undefined,

// Automatically restore mock state and implementation before every test
// restoreMocks: false,

// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,

// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],

// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",

// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],

// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},

// Adds a location field to test results
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],

// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],

// This option allows the use of a custom results processor
// testResultsProcessor: undefined,

// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",

// A map from regular expressions to paths to transformers
// transform: undefined,

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,

// Indicates whether each individual test should be reported during the run
verbose: true,

// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],

// Whether to use watchman for file crawling
// watchman: true,
};
Expand Down
12 changes: 6 additions & 6 deletions package-lock.json

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

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
"lint": "oxlint && eslint",
"prettier": "prettier --write .",
"prepare": "husky",
"test": "jest --",
"test:watch": "jest --watch --",
"test:coverage": "jest --coverage"
"test": "jest --runInBand --",
"test:watch": "jest --watch --runInBand --",
"test:coverage": "jest --coverage --runInBand"
},
"dependencies": {
"commander": "^12.1.0",
Expand Down
6 changes: 3 additions & 3 deletions src/buildPrompt.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const fs = require("node:fs/promises");
const fsPromises = require("node:fs/promises");

/**
* Constructs a prompt by reading the content of input files and formatting it for code conversion.
Expand All @@ -22,7 +22,7 @@ Do not use backticks (\`) to enclose the code in your response.\n\n`;
try {
// Loop through input files and add them to prompt
for (const inputFilePath of inputFiles) {
const inputFileContent = await fs.readFile(inputFilePath, {
const inputFileContent = await fsPromises.readFile(inputFilePath, {
encoding: "utf8",
});

Expand All @@ -35,7 +35,7 @@ Do not use backticks (\`) to enclose the code in your response.\n\n`;
return prompt;
} catch (error) {
console.error(`error reading input files: ${error}`);
process.exit(21);
process.exit(1);
}
}

Expand Down
35 changes: 35 additions & 0 deletions src/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const fs = require("node:fs");
const path = require("node:path");
const toml = require("smol-toml");

const configFilePath = path.join(process.cwd(), ".codeshift.config.toml");

const defaultConfig = `[settings]
baseUrl="xxxxxxxxxxxxxxxxxx"
apiKey="sk-xxxxxxxxxxx"
outputFile="xxxxxxxxxxx"
model="xxxxxxxxxxxx"
tokenUsage=false
stream=true
`;

let parsedConfig;

try {
const fileContent = fs.readFileSync(configFilePath, "utf-8");
parsedConfig = toml.parse(fileContent);
} catch (err) {
// If config file is missing, create it
if (err.code == "ENOENT") {
fs.writeFileSync(configFilePath, defaultConfig);
console.error(
"Existing config not found. Created .codeshift.config.toml. Please set config options.",
);
process.exit(1);
} else {
console.error(`error reading or parsing the config file: ${err.message}`);
process.exit(1); // Exit with an error message if the file exists but is invalid
}
}

module.exports = parsedConfig.settings;
Loading

0 comments on commit 519515c

Please sign in to comment.