Explore "https://github.com/knqyf263/pet" covert this into typescript javascript pls Save Share Download ▾ Report Assistant2024-11-18 07:11 UTC Copy response
Certainly! The repository you're referring to, knqyf263/pet , is a command-line snippet manager written in Go. It allows users to manage and use command snippets efficiently.
If you're interested in creating a similar tool using TypeScript and JavaScript, I'd be happy to guide you through the process. Below is a step-by-step outline to help you build a command-line snippet manager in TypeScript.
Overview
Objective : Build a command-line tool to manage code snippets.
Technologies : TypeScript, Node.js, filesystem or database for storage, and CLI libraries.
Step 1: Setup Your Development Environment
Initialize a Node.js Project :
bash Copy code
mkdir ts-snippet-manager
cd ts-snippet-manager
npm init -y
Install TypeScript and Necessary Dependencies :
bash Copy code
npm install typescript ts-node @types/node --save-dev
npm install commander inquirer chalk
commander: For parsing command-line arguments.
inquirer: For interactive command-line prompts.
chalk: For styling terminal output.
Initialize TypeScript Configuration :
bash Copy code
npx tsc --init
Adjust the tsconfig.json as needed for your project.
Step 2: Design the Application Structure
Consider the following structure:
code Copy code
ts-snippet-manager/
├── src/
│ ├── index.ts # Entry point
│ ├── commands/
│ │ ├── add.ts
│ │ ├── list.ts
│ │ ├── edit.ts
│ │ └── delete.ts
│ └── utils/
│ └── storage.ts
├── package.json
└── tsconfig.json
Step 3: Implement Core Features
1. Entry Point (src/index.ts)
Show full message · 300 lines Copy first prompt Copy first response
Details
Provider openai
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language Not recorded
Added to archive Nov 24, 2026
ID 01m86ev4rm45c2axg7v0g2rzq5Source & license Imported from WildChat-4.8M (source ). Imported records earn no Research Points.
Upstream record: 73f2f7b4fb4e46cef3cb4ee7ba794423
allenai/WildChat-4.8M, revision c827c6df8fcf008219ffaffa4d1dd77491099367
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
#!/usr/bin/env node
import { Command } from 'commander';
import addCommand from './commands/add';
import listCommand from './commands/list';
import editCommand from './commands/edit';
import deleteCommand from './commands/delete';
const program = new Command();
program
.name('snip')
.description('A command-line snippet manager')
.version('1.0.0');
program.addCommand(addCommand);
program.addCommand(listCommand);
program.addCommand(editCommand);
program.addCommand(deleteCommand);
program.parse(process.argv);
Make sure to add execution permissions to your index.ts when compiled, so it can be run directly.
2. Add Snippet (src/commands/add.ts) typescript Copy code
import { Command } from 'commander';
import inquirer from 'inquirer';
import { saveSnippet } from '../utils/storage';
const addCommand = new Command('add')
.description('Add a new snippet')
.action(async () => {
const answers = await inquirer.prompt([
{ type: 'input', name: 'title', message: 'Snippet title:' },
{ type: 'editor', name: 'content', message: 'Snippet content:' },
{ type: 'input', name: 'tags', message: 'Tags (comma-separated):' },
]);
saveSnippet({
title: answers.title,
content: answers.content,
tags: answers.tags.split(',').map((tag) => tag.trim()),
});
console.log('Snippet added successfully!');
});
export default addCommand;
3. List Snippets (src/commands/list.ts) typescript Copy code
import { Command } from 'commander';
import { getSnippets } from '../utils/storage';
import chalk from 'chalk';
const listCommand = new Command('list')
.description('List all snippets')
.option('-t, --tag <tag>', 'Filter by tag')
.action((options) => {
const snippets = getSnippets();
const filteredSnippets = options.tag
? snippets.filter((s) => s.tags.includes(options.tag))
: snippets;
filteredSnippets.forEach((snippet, index) => {
console.log(chalk.green(`\n[${index + 1}] ${snippet.title}`));
console.log(chalk.yellow(`Tags: ${snippet.tags.join(', ')}`));
console.log(chalk.white(snippet.content));
});
});
export default listCommand;
4. Storage Utility (src/utils/storage.ts) For simplicity, we'll use a JSON file to store snippets.
typescript Copy code
import fs from 'fs';
import path from 'path';
const DATA_FILE = path.join(__dirname, '../../snippets.json');
interface Snippet {
title: string;
content: string;
tags: string[];
}
export function getSnippets(): Snippet[] {
if (!fs.existsSync(DATA_FILE)) {
return [];
}
const data = fs.readFileSync(DATA_FILE, 'utf-8');
return JSON.parse(data);
}
export function saveSnippet(snippet: Snippet): void {
const snippets = getSnippets();
snippets.push(snippet);
fs.writeFileSync(DATA_FILE, JSON.stringify(snippets, null, 2));
}
5. Implement Other Commands Similarly, implement edit and delete commands to update and remove snippets.
Step 4: Enhance Functionality
Search Snippets Implement a search command to find snippets by keyword.
typescript Copy code
// src/commands/search.ts
import { Command } from 'commander';
import { getSnippets } from '../utils/storage';
import chalk from 'chalk';
const searchCommand = new Command('search')
.description('Search snippets by keyword')
.argument('<keyword>', 'Keyword to search for')
.action((keyword) => {
const snippets = getSnippets();
const matchedSnippets = snippets.filter(
(s) =>
s.title.includes(keyword) ||
s.content.includes(keyword) ||
s.tags.includes(keyword)
);
matchedSnippets.forEach((snippet, index) => {
console.log(chalk.green(`\n[${index + 1}] ${snippet.title}`));
console.log(chalk.yellow(`Tags: ${snippet.tags.join(', ')}`));
console.log(chalk.white(snippet.content));
});
});
export default searchCommand;
Execute Snippets If your snippets are shell commands or scripts, you can allow users to execute them.
typescript Copy code
// src/commands/exec.ts
import { Command } from 'commander';
import { getSnippets } from '../utils/storage';
import { exec } from 'child_process';
const execCommand = new Command('exec')
.description('Execute a snippet by index')
.argument('<index>', 'Index of the snippet to execute')
.action((index) => {
const snippets = getSnippets();
const snippet = snippets[Number(index) - 1];
if (!snippet) {
console.error('Snippet not found.');
return;
}
exec(snippet.content, (error, stdout, stderr) => {
if (error) {
console.error(`Execution error: ${error.message}`);
return;
}
if (stderr) {
console.error(`Error output: ${stderr}`);
return;
}
console.log(`Output:\n${stdout}`);
});
});
export default execCommand;
Note : Be cautious when executing code to prevent security risks.
Step 5: Build and Distribute Your Tool
Compile TypeScript to JavaScript Adjust your package.json scripts:
json Copy code
"scripts": {
"build": "tsc",
"start": "ts-node src/index.ts"
}
bash Copy code
npm run build
Link the Executable To use your tool system-wide during development:
Now you can run the command snip from anywhere.
Distribute the Package You can publish your package to npm or package it as an executable using tools like pkg.
Additional Tips
Improve Data Storage : For better performance and data management, consider using a database like SQLite with packages like typeorm.
Error Handling : Implement comprehensive error handling to improve user experience.
Unit Testing : Use frameworks like Jest to write tests for your code.
Configuration Files : Allow users to set configurations using a config file or environment variables.
Auto-completion : Implement shell auto-completion scripts for your CLI tool.
Logging : Implement logging for debugging purposes using packages like winston.
Conclusion By following these steps, you can create a robust command-line snippet manager using TypeScript and JavaScript. This not only replicates the functionality of the original Go-based pet tool but also allows for customization and expansion based on your needs.
Feel free to ask if you need further details on any section or assistance with specific features!