bolt-pull
Version:
A CLI tool to fetch latest code from Bolt.new project
103 lines (87 loc) • 2.8 kB
JavaScript
const { program } = require("commander")
const inquirer = require("inquirer")
const fetch = require("node-fetch")
const fs = require("fs")
const path = require("path")
const colorette = require("colorette")
const { join } = path
const { existsSync, mkdirSync, writeFileSync } = fs
const API_URL = "https://bolt.new/api/import/stackblitz"
const createDir = (dirPath) => {
if (!existsSync(dirPath)) {
mkdirSync(dirPath, { recursive: true })
console.log(`Created folder: ${dirPath}`)
}
}
const createFile = (filePath, content = "") => {
writeFileSync(filePath, content)
console.log(`Created file: ${filePath}`)
}
const fetchStackBlitzProject = async (slug) => {
try {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0",
},
body: JSON.stringify({ slug }),
})
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`)
return await response.json()
} catch (error) {
console.error("Error fetching StackBlitz data:", error.message)
process.exit(1)
}
}
const createProject = async (slug, dir) => {
console.log("Fetching project data...")
const response = await fetchStackBlitzProject(slug)
console.log("Creating project...")
Object.values(response.appFiles).forEach((file) => {
if (!file.fullPath) {
console.warn(`Skipping file/folder: ${file.name} (missing fullPath)`)
return
}
const fullPath = join(dir || process.cwd(), file.fullPath)
if (file.type === "folder") {
createDir(fullPath)
} else if (file.type === "file") {
createFile(fullPath, file.contents || "")
}
})
console.log("Project successfully created!")
}
program
.command("bolt-pull")
.description("Pulls the latest changes from the remote repository")
.option("-s, --slug <slug>", "Provide project slug to pull the changes")
.option("-d, --dir <dir>", "Provide the directory to pull the changes")
.action(async (options) => {
if (!options.slug) {
console.error("Project slug is required!")
process.exit(1)
}
console.log("Pulling the latest changes")
inquirer
.prompt([
{
type: "confirm",
name: "confirm",
message:
"Pulling the latest changes will overwrite the local changes. Are you sure you want to continue?",
default: false,
},
])
.then((answers) => {
if (answers.confirm) {
createProject(options.slug, options.dir)
console.log(colorette.green("\n Project pulled successfully. \n"))
}
})
.catch((err) => {
console.log(colorette.red(`\n Error: ${err} \n`))
})
})
program.parse()