test.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const parser = async () => {
  2. try {
  3. const { default: Parser } = await import("tree-sitter")
  4. const Bash = await import("tree-sitter-bash")
  5. const p = new Parser()
  6. p.setLanguage(Bash.language as any)
  7. return p
  8. } catch (e) {
  9. const { Parser, Language } = await import("web-tree-sitter")
  10. const { default: treeWasm } = await import("web-tree-sitter/web-tree-sitter.wasm" as string, {
  11. with: { type: "wasm" },
  12. })
  13. await Parser.init({
  14. locateFile() {
  15. return treeWasm
  16. },
  17. })
  18. const { default: bashWasm } = await import("tree-sitter-bash/tree-sitter-bash.wasm" as string, {
  19. with: { type: "wasm" },
  20. })
  21. const bashLanguage = await Language.load(bashWasm)
  22. const p = new Parser()
  23. p.setLanguage(bashLanguage)
  24. return p
  25. }
  26. }
  27. const sourceCode = `cd --foo foo/bar && echo "hello" && cd ../baz`
  28. const tree = await parser().then((p) => p.parse(sourceCode))
  29. // Function to extract commands and arguments
  30. function extractCommands(node: any): Array<{ command: string; args: string[] }> {
  31. const commands: Array<{ command: string; args: string[] }> = []
  32. function traverse(node: any) {
  33. if (node.type === "command") {
  34. const commandNode = node.child(0)
  35. if (commandNode) {
  36. const command = commandNode.text
  37. const args: string[] = []
  38. // Extract arguments
  39. for (let i = 1; i < node.childCount; i++) {
  40. const child = node.child(i)
  41. if (child && child.type === "word") {
  42. args.push(child.text)
  43. }
  44. }
  45. commands.push({ command, args })
  46. }
  47. }
  48. // Traverse children
  49. for (let i = 0; i < node.childCount; i++) {
  50. traverse(node.child(i))
  51. }
  52. }
  53. traverse(node)
  54. return commands
  55. }
  56. // Extract and display commands
  57. console.log("Source code: " + sourceCode)
  58. if (!tree) {
  59. throw new Error("Failed to parse command")
  60. }
  61. const commands = extractCommands(tree.rootNode)
  62. console.log("Extracted commands:")
  63. commands.forEach((cmd, index) => {
  64. console.log(`${index + 1}. Command: ${cmd.command}`)
  65. console.log(` Args: [${cmd.args.join(", ")}]`)
  66. })