uninstall.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import type { Argv } from "yargs"
  2. import { UI } from "../ui"
  3. import * as prompts from "@clack/prompts"
  4. import { Installation } from "../../installation"
  5. import { Global } from "../../global"
  6. import { $ } from "bun"
  7. import fs from "fs/promises"
  8. import path from "path"
  9. import os from "os"
  10. interface UninstallArgs {
  11. keepConfig: boolean
  12. keepData: boolean
  13. dryRun: boolean
  14. force: boolean
  15. }
  16. interface RemovalTargets {
  17. directories: Array<{ path: string; label: string; keep: boolean }>
  18. shellConfig: string | null
  19. binary: string | null
  20. }
  21. export const UninstallCommand = {
  22. command: "uninstall",
  23. describe: "uninstall opencode and remove all related files",
  24. builder: (yargs: Argv) =>
  25. yargs
  26. .option("keep-config", {
  27. alias: "c",
  28. type: "boolean",
  29. describe: "keep configuration files",
  30. default: false,
  31. })
  32. .option("keep-data", {
  33. alias: "d",
  34. type: "boolean",
  35. describe: "keep session data and snapshots",
  36. default: false,
  37. })
  38. .option("dry-run", {
  39. type: "boolean",
  40. describe: "show what would be removed without removing",
  41. default: false,
  42. })
  43. .option("force", {
  44. alias: "f",
  45. type: "boolean",
  46. describe: "skip confirmation prompts",
  47. default: false,
  48. }),
  49. handler: async (args: UninstallArgs) => {
  50. UI.empty()
  51. UI.println(UI.logo(" "))
  52. UI.empty()
  53. prompts.intro("Uninstall OpenCode")
  54. const method = await Installation.method()
  55. prompts.log.info(`Installation method: ${method}`)
  56. const targets = await collectRemovalTargets(args, method)
  57. await showRemovalSummary(targets, method)
  58. if (!args.force && !args.dryRun) {
  59. const confirm = await prompts.confirm({
  60. message: "Are you sure you want to uninstall?",
  61. initialValue: false,
  62. })
  63. if (!confirm || prompts.isCancel(confirm)) {
  64. prompts.outro("Cancelled")
  65. return
  66. }
  67. }
  68. if (args.dryRun) {
  69. prompts.log.warn("Dry run - no changes made")
  70. prompts.outro("Done")
  71. return
  72. }
  73. await executeUninstall(method, targets)
  74. prompts.outro("Done")
  75. },
  76. }
  77. async function collectRemovalTargets(args: UninstallArgs, method: Installation.Method): Promise<RemovalTargets> {
  78. const directories: RemovalTargets["directories"] = [
  79. { path: Global.Path.data, label: "Data", keep: args.keepData },
  80. { path: Global.Path.cache, label: "Cache", keep: false },
  81. { path: Global.Path.config, label: "Config", keep: args.keepConfig },
  82. { path: Global.Path.state, label: "State", keep: false },
  83. ]
  84. const shellConfig = method === "curl" ? await getShellConfigFile() : null
  85. const binary = method === "curl" ? process.execPath : null
  86. return { directories, shellConfig, binary }
  87. }
  88. async function showRemovalSummary(targets: RemovalTargets, method: Installation.Method) {
  89. prompts.log.message("The following will be removed:")
  90. for (const dir of targets.directories) {
  91. const exists = await fs
  92. .access(dir.path)
  93. .then(() => true)
  94. .catch(() => false)
  95. if (!exists) continue
  96. const size = await getDirectorySize(dir.path)
  97. const sizeStr = formatSize(size)
  98. const status = dir.keep ? UI.Style.TEXT_DIM + "(keeping)" : ""
  99. const prefix = dir.keep ? "○" : "✓"
  100. prompts.log.info(` ${prefix} ${dir.label}: ${shortenPath(dir.path)} ${UI.Style.TEXT_DIM}(${sizeStr})${status}`)
  101. }
  102. if (targets.binary) {
  103. prompts.log.info(` ✓ Binary: ${shortenPath(targets.binary)}`)
  104. }
  105. if (targets.shellConfig) {
  106. prompts.log.info(` ✓ Shell PATH in ${shortenPath(targets.shellConfig)}`)
  107. }
  108. if (method !== "curl" && method !== "unknown") {
  109. const cmds: Record<string, string> = {
  110. npm: "npm uninstall -g opencode-ai",
  111. pnpm: "pnpm uninstall -g opencode-ai",
  112. bun: "bun remove -g opencode-ai",
  113. yarn: "yarn global remove opencode-ai",
  114. brew: "brew uninstall opencode",
  115. }
  116. prompts.log.info(` ✓ Package: ${cmds[method] || method}`)
  117. }
  118. }
  119. async function executeUninstall(method: Installation.Method, targets: RemovalTargets) {
  120. const spinner = prompts.spinner()
  121. const errors: string[] = []
  122. for (const dir of targets.directories) {
  123. if (dir.keep) {
  124. prompts.log.step(`Skipping ${dir.label} (--keep-${dir.label.toLowerCase()})`)
  125. continue
  126. }
  127. const exists = await fs
  128. .access(dir.path)
  129. .then(() => true)
  130. .catch(() => false)
  131. if (!exists) continue
  132. spinner.start(`Removing ${dir.label}...`)
  133. const err = await fs.rm(dir.path, { recursive: true, force: true }).catch((e) => e)
  134. if (err) {
  135. spinner.stop(`Failed to remove ${dir.label}`, 1)
  136. errors.push(`${dir.label}: ${err.message}`)
  137. continue
  138. }
  139. spinner.stop(`Removed ${dir.label}`)
  140. }
  141. if (targets.shellConfig) {
  142. spinner.start("Cleaning shell config...")
  143. const err = await cleanShellConfig(targets.shellConfig).catch((e) => e)
  144. if (err) {
  145. spinner.stop("Failed to clean shell config", 1)
  146. errors.push(`Shell config: ${err.message}`)
  147. } else {
  148. spinner.stop("Cleaned shell config")
  149. }
  150. }
  151. if (method !== "curl" && method !== "unknown") {
  152. const cmds: Record<string, string[]> = {
  153. npm: ["npm", "uninstall", "-g", "opencode-ai"],
  154. pnpm: ["pnpm", "uninstall", "-g", "opencode-ai"],
  155. bun: ["bun", "remove", "-g", "opencode-ai"],
  156. yarn: ["yarn", "global", "remove", "opencode-ai"],
  157. brew: ["brew", "uninstall", "opencode"],
  158. }
  159. const cmd = cmds[method]
  160. if (cmd) {
  161. spinner.start(`Running ${cmd.join(" ")}...`)
  162. const result = await $`${cmd}`.quiet().nothrow()
  163. if (result.exitCode !== 0) {
  164. spinner.stop(`Package manager uninstall failed`, 1)
  165. prompts.log.warn(`You may need to run manually: ${cmd.join(" ")}`)
  166. errors.push(`Package manager: exit code ${result.exitCode}`)
  167. } else {
  168. spinner.stop("Package removed")
  169. }
  170. }
  171. }
  172. if (method === "curl" && targets.binary) {
  173. UI.empty()
  174. prompts.log.message("To finish removing the binary, run:")
  175. prompts.log.info(` rm "${targets.binary}"`)
  176. const binDir = path.dirname(targets.binary)
  177. if (binDir.includes(".opencode")) {
  178. prompts.log.info(` rmdir "${binDir}" 2>/dev/null`)
  179. }
  180. }
  181. if (errors.length > 0) {
  182. UI.empty()
  183. prompts.log.warn("Some operations failed:")
  184. for (const err of errors) {
  185. prompts.log.error(` ${err}`)
  186. }
  187. }
  188. UI.empty()
  189. prompts.log.success("Thank you for using OpenCode!")
  190. }
  191. async function getShellConfigFile(): Promise<string | null> {
  192. const shell = path.basename(process.env.SHELL || "bash")
  193. const home = os.homedir()
  194. const xdgConfig = process.env.XDG_CONFIG_HOME || path.join(home, ".config")
  195. const configFiles: Record<string, string[]> = {
  196. fish: [path.join(xdgConfig, "fish", "config.fish")],
  197. zsh: [
  198. path.join(home, ".zshrc"),
  199. path.join(home, ".zshenv"),
  200. path.join(xdgConfig, "zsh", ".zshrc"),
  201. path.join(xdgConfig, "zsh", ".zshenv"),
  202. ],
  203. bash: [
  204. path.join(home, ".bashrc"),
  205. path.join(home, ".bash_profile"),
  206. path.join(home, ".profile"),
  207. path.join(xdgConfig, "bash", ".bashrc"),
  208. path.join(xdgConfig, "bash", ".bash_profile"),
  209. ],
  210. ash: [path.join(home, ".ashrc"), path.join(home, ".profile")],
  211. sh: [path.join(home, ".profile")],
  212. }
  213. const candidates = configFiles[shell] || configFiles.bash
  214. for (const file of candidates) {
  215. const exists = await fs
  216. .access(file)
  217. .then(() => true)
  218. .catch(() => false)
  219. if (!exists) continue
  220. const content = await Bun.file(file)
  221. .text()
  222. .catch(() => "")
  223. if (content.includes("# opencode") || content.includes(".opencode/bin")) {
  224. return file
  225. }
  226. }
  227. return null
  228. }
  229. async function cleanShellConfig(file: string) {
  230. const content = await Bun.file(file).text()
  231. const lines = content.split("\n")
  232. const filtered: string[] = []
  233. let skip = false
  234. for (const line of lines) {
  235. const trimmed = line.trim()
  236. if (trimmed === "# opencode") {
  237. skip = true
  238. continue
  239. }
  240. if (skip) {
  241. skip = false
  242. if (trimmed.includes(".opencode/bin") || trimmed.includes("fish_add_path")) {
  243. continue
  244. }
  245. }
  246. if (
  247. (trimmed.startsWith("export PATH=") && trimmed.includes(".opencode/bin")) ||
  248. (trimmed.startsWith("fish_add_path") && trimmed.includes(".opencode"))
  249. ) {
  250. continue
  251. }
  252. filtered.push(line)
  253. }
  254. while (filtered.length > 0 && filtered[filtered.length - 1].trim() === "") {
  255. filtered.pop()
  256. }
  257. const output = filtered.join("\n") + "\n"
  258. await Bun.write(file, output)
  259. }
  260. async function getDirectorySize(dir: string): Promise<number> {
  261. let total = 0
  262. const walk = async (current: string) => {
  263. const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => [])
  264. for (const entry of entries) {
  265. const full = path.join(current, entry.name)
  266. if (entry.isDirectory()) {
  267. await walk(full)
  268. continue
  269. }
  270. if (entry.isFile()) {
  271. const stat = await fs.stat(full).catch(() => null)
  272. if (stat) total += stat.size
  273. }
  274. }
  275. }
  276. await walk(dir)
  277. return total
  278. }
  279. function formatSize(bytes: number): string {
  280. if (bytes < 1024) return `${bytes} B`
  281. if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  282. if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  283. return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`
  284. }
  285. function shortenPath(p: string): string {
  286. const home = os.homedir()
  287. if (p.startsWith(home)) {
  288. return p.replace(home, "~")
  289. }
  290. return p
  291. }