Преглед изворни кода

Refactor logging system to centralize initialization and remove printLogs parameter

🤖 Generated with [OpenCode](https://opencode.ai)

Co-Authored-By: OpenCode <[email protected]>
Dax Raad пре 8 месеци
родитељ
комит
d8510ab452

+ 2 - 8
packages/opencode/src/app/app.ts

@@ -32,11 +32,7 @@ export namespace App {
 
   const APP_JSON = "app.json"
 
-  async function create(input: {
-    cwd: string
-    version: string
-    printLogs?: boolean
-  }) {
+  async function create(input: { cwd: string; version: string }) {
     const git = await Filesystem.findUp(".git", input.cwd).then((x) =>
       x ? path.dirname(x) : undefined,
     )
@@ -62,8 +58,6 @@ export namespace App {
       }
     >()
 
-    if (!input.printLogs) await Log.file(path.join(data, "log"))
-
     const info: Info = {
       user: os.userInfo().username,
       time: {
@@ -110,7 +104,7 @@ export namespace App {
   }
 
   export async function provide<T extends (app: Info) => any>(
-    input: { cwd: string; version: string; printLogs?: boolean },
+    input: { cwd: string; version: string },
     cb: T,
   ) {
     const app = await create(input)

+ 0 - 1
packages/opencode/src/cli/cmd/run.ts

@@ -34,7 +34,6 @@ export const RunCommand = {
       {
         cwd: process.cwd(),
         version: "0.0.0",
-        printLogs: args.printLogs,
       },
       async () => {
         await Share.init()

+ 4 - 7
packages/opencode/src/cli/cmd/scrap.ts

@@ -9,12 +9,9 @@ export const ScrapCommand = cmd({
     yargs.positional("file", { type: "string", demandOption: true }),
   describe: "test command",
   async handler(args) {
-    await App.provide(
-      { cwd: process.cwd(), version: VERSION, printLogs: true },
-      async () => {
-        await LSP.touchFile(args.file, true)
-        await LSP.diagnostics()
-      },
-    )
+    await App.provide({ cwd: process.cwd(), version: VERSION }, async () => {
+      await LSP.touchFile(args.file, true)
+      await LSP.diagnostics()
+    })
   },
 })

+ 36 - 36
packages/opencode/src/index.ts

@@ -15,6 +15,9 @@ import { LoginAnthropicCommand } from "./cli/cmd/login-anthropic"
 import { GenerateCommand } from "./cli/cmd/generate"
 import { VERSION } from "./cli/version"
 import { ScrapCommand } from "./cli/cmd/scrap"
+import { Log } from "./util/log"
+
+await Log.init({ print: false })
 
 yargs(hideBin(process.argv))
   .scriptName("opencode")
@@ -27,44 +30,41 @@ yargs(hideBin(process.argv))
         type: "boolean",
       }),
     handler: async (args) => {
-      await App.provide(
-        { cwd: process.cwd(), version: VERSION, printLogs: args.printLogs },
-        async () => {
-          await Share.init()
-          const server = Server.listen()
+      await App.provide({ cwd: process.cwd(), version: VERSION }, async () => {
+        await Share.init()
+        const server = Server.listen()
 
-          let cmd = ["go", "run", "./main.go"]
-          let cwd = new URL("../../tui/cmd/opencode", import.meta.url).pathname
-          if (Bun.embeddedFiles.length > 0) {
-            const blob = Bun.embeddedFiles[0] as File
-            const binary = path.join(Global.Path.cache, "tui", blob.name)
-            const file = Bun.file(binary)
-            if (!(await file.exists())) {
-              console.log("installing tui binary...")
-              await Bun.write(file, blob, { mode: 0o755 })
-              await fs.chmod(binary, 0o755)
-            }
-            cwd = process.cwd()
-            cmd = [binary]
+        let cmd = ["go", "run", "./main.go"]
+        let cwd = new URL("../../tui/cmd/opencode", import.meta.url).pathname
+        if (Bun.embeddedFiles.length > 0) {
+          const blob = Bun.embeddedFiles[0] as File
+          const binary = path.join(Global.Path.cache, "tui", blob.name)
+          const file = Bun.file(binary)
+          if (!(await file.exists())) {
+            console.log("installing tui binary...")
+            await Bun.write(file, blob, { mode: 0o755 })
+            await fs.chmod(binary, 0o755)
           }
-          const proc = Bun.spawn({
-            cmd,
-            cwd,
-            stdout: "inherit",
-            stderr: "inherit",
-            stdin: "inherit",
-            env: {
-              ...process.env,
-              OPENCODE_SERVER: server.url.toString(),
-            },
-            onExit: () => {
-              server.stop()
-            },
-          })
-          await proc.exited
-          await server.stop()
-        },
-      )
+          cwd = process.cwd()
+          cmd = [binary]
+        }
+        const proc = Bun.spawn({
+          cmd,
+          cwd,
+          stdout: "inherit",
+          stderr: "inherit",
+          stdin: "inherit",
+          env: {
+            ...process.env,
+            OPENCODE_SERVER: server.url.toString(),
+          },
+          onExit: () => {
+            server.stop()
+          },
+        })
+        await proc.exited
+        await server.stop()
+      })
     },
   })
   .command(RunCommand)

+ 34 - 27
packages/opencode/src/util/log.ts

@@ -1,35 +1,42 @@
 import path from "path"
 import fs from "fs/promises"
+import { Global } from "../global"
 export namespace Log {
-  const write = {
-    out: (msg: string) => {
-      process.stdout.write(msg)
-    },
-    err: (msg: string) => {
-      process.stderr.write(msg)
-    },
+  export interface Options {
+    print: boolean
   }
 
-  export async function file(directory: string) {
-    await fs.mkdir(directory, { recursive: true })
-    const outPath = path.join(directory, "opencode.out.log")
-    const errPath = path.join(directory, "opencode.err.log")
-    await fs.truncate(outPath).catch(() => {})
-    await fs.truncate(errPath).catch(() => {})
-    const out = Bun.file(outPath)
-    const err = Bun.file(errPath)
-    const outWriter = out.writer()
-    const errWriter = err.writer()
-    write["out"] = (msg) => {
-      outWriter.write(msg)
-      outWriter.flush()
-    }
-    write["err"] = (msg) => {
-      errWriter.write(msg)
-      errWriter.flush()
+  export async function init(options: Options) {
+    const dir = path.join(Global.Path.data, "log")
+    await fs.mkdir(dir, { recursive: true })
+    cleanup(dir)
+    if (options.print) return
+    const logpath = path.join(dir, new Date().toISOString() + ".log")
+    const logfile = Bun.file(logpath)
+    await fs.truncate(logpath).catch(() => {})
+    const writer = logfile.writer()
+    process.stderr.write = (msg) => {
+      writer.write(msg)
+      writer.flush()
+      return true
     }
   }
 
+  async function cleanup(dir: string) {
+    const entries = await fs.readdir(dir, { withFileTypes: true })
+    const files = entries
+      .filter((entry) => entry.isFile() && entry.name.endsWith(".log"))
+      .map((entry) => path.join(dir, entry.name))
+
+    if (files.length <= 10) return
+
+    const filesToDelete = files.slice(0, -10)
+
+    await Promise.all(
+      filesToDelete.map((file) => fs.unlink(file).catch(() => {})),
+    )
+  }
+
   export function create(tags?: Record<string, any>) {
     tags = tags || {}
 
@@ -48,13 +55,13 @@ export namespace Log {
     }
     const result = {
       info(message?: any, extra?: Record<string, any>) {
-        write.out(build(message, extra))
+        process.stderr.write(build(message, extra))
       },
       error(message?: any, extra?: Record<string, any>) {
-        write.out(build(message, extra))
+        process.stderr.write(build(message, extra))
       },
       warn(message?: any, extra?: Record<string, any>) {
-        write.out(build(message, extra))
+        process.stderr.write(build(message, extra))
       },
       tag(key: string, value: string) {
         if (tags) tags[key] = value