diff.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package hostbridge
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. proto "github.com/cline/grpc-go/host"
  13. )
  14. // diffSession represents an in-memory diff editing session
  15. type diffSession struct {
  16. originalPath string // File path from OpenDiff request
  17. originalContent []byte // Original file content (for comparison)
  18. currentContent []byte // Current modified content
  19. lines []string // Current content split into lines
  20. encoding string // File encoding (default: utf8)
  21. }
  22. // DiffService implements the proto.DiffServiceServer interface
  23. type DiffService struct {
  24. proto.UnimplementedDiffServiceServer
  25. verbose bool
  26. sessions *sync.Map // thread-safe: diffId -> *diffSession
  27. counter *int64 // atomic counter for unique IDs
  28. }
  29. // NewDiffService creates a new DiffService
  30. func NewDiffService(verbose bool) *DiffService {
  31. counter := int64(0)
  32. return &DiffService{
  33. verbose: verbose,
  34. sessions: &sync.Map{},
  35. counter: &counter,
  36. }
  37. }
  38. // generateDiffID creates a unique diff ID
  39. func (s *DiffService) generateDiffID() string {
  40. id := atomic.AddInt64(s.counter, 1)
  41. return fmt.Sprintf("diff_%d_%d", os.Getpid(), id)
  42. }
  43. // splitLines splits content into lines, preserving line ending information
  44. func splitLines(content string) []string {
  45. if content == "" {
  46. return []string{}
  47. }
  48. lines := []string{}
  49. current := ""
  50. for _, char := range content {
  51. if char == '\n' {
  52. lines = append(lines, current)
  53. current = ""
  54. } else if char != '\r' { // Skip \r characters, handle \r\n as \n
  55. current += string(char)
  56. }
  57. }
  58. // Add the last line if it doesn't end with newline
  59. if current != "" {
  60. lines = append(lines, current)
  61. }
  62. return lines
  63. }
  64. // joinLines joins lines back into content with newlines
  65. func joinLines(lines []string) string {
  66. if len(lines) == 0 {
  67. return ""
  68. }
  69. return strings.Join(lines, "\n")
  70. }
  71. // OpenDiff opens a diff view for the specified file
  72. func (s *DiffService) OpenDiff(ctx context.Context, req *proto.OpenDiffRequest) (*proto.OpenDiffResponse, error) {
  73. if s.verbose {
  74. log.Printf("OpenDiff called for path: %s", req.GetPath())
  75. }
  76. diffID := s.generateDiffID()
  77. var originalContent []byte
  78. // Check if file exists and read original content
  79. if req.GetPath() != "" {
  80. if _, err := os.Stat(req.GetPath()); err == nil {
  81. // File exists, read its content
  82. var readErr error
  83. originalContent, readErr = ioutil.ReadFile(req.GetPath())
  84. if readErr != nil {
  85. return nil, fmt.Errorf("failed to read original file: %w", readErr)
  86. }
  87. } else {
  88. // File doesn't exist, use empty content
  89. originalContent = []byte{}
  90. }
  91. }
  92. // Use provided content as the initial current content
  93. currentContent := []byte(req.GetContent())
  94. // Create the diff session
  95. session := &diffSession{
  96. originalPath: req.GetPath(),
  97. originalContent: originalContent,
  98. currentContent: currentContent,
  99. lines: splitLines(req.GetContent()),
  100. encoding: "utf8", // Default encoding
  101. }
  102. // Store the session
  103. s.sessions.Store(diffID, session)
  104. if s.verbose {
  105. log.Printf("Created diff session: %s (original: %d bytes, current: %d bytes)",
  106. diffID, len(originalContent), len(currentContent))
  107. }
  108. return &proto.OpenDiffResponse{
  109. DiffId: &diffID,
  110. }, nil
  111. }
  112. // GetDocumentText returns the current content of the diff document
  113. func (s *DiffService) GetDocumentText(ctx context.Context, req *proto.GetDocumentTextRequest) (*proto.GetDocumentTextResponse, error) {
  114. if s.verbose {
  115. log.Printf("GetDocumentText called for diff ID: %s", req.GetDiffId())
  116. }
  117. sessionInterface, exists := s.sessions.Load(req.GetDiffId())
  118. if !exists {
  119. return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
  120. }
  121. session := sessionInterface.(*diffSession)
  122. content := string(session.currentContent)
  123. return &proto.GetDocumentTextResponse{
  124. Content: &content,
  125. }, nil
  126. }
  127. // ReplaceText replaces text in the diff document using line-based operations
  128. func (s *DiffService) ReplaceText(ctx context.Context, req *proto.ReplaceTextRequest) (*proto.ReplaceTextResponse, error) {
  129. if s.verbose {
  130. log.Printf("ReplaceText called for diff ID: %s, lines %d-%d",
  131. req.GetDiffId(), req.GetStartLine(), req.GetEndLine())
  132. }
  133. sessionInterface, exists := s.sessions.Load(req.GetDiffId())
  134. if !exists {
  135. return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
  136. }
  137. session := sessionInterface.(*diffSession)
  138. startLine := int(req.GetStartLine())
  139. endLine := int(req.GetEndLine())
  140. newContent := req.GetContent()
  141. // Validate line ranges
  142. if startLine < 0 {
  143. startLine = 0
  144. }
  145. if endLine < startLine {
  146. endLine = startLine
  147. }
  148. // Split new content into lines
  149. newLines := splitLines(newContent)
  150. // Ensure we have enough lines in the current content
  151. for len(session.lines) < endLine {
  152. session.lines = append(session.lines, "")
  153. }
  154. // Replace the specified line range
  155. if endLine > len(session.lines) {
  156. // Extending beyond current content - append new lines
  157. session.lines = append(session.lines[:startLine], newLines...)
  158. } else {
  159. // Replace within existing content
  160. result := make([]string, 0, len(session.lines)-endLine+startLine+len(newLines))
  161. result = append(result, session.lines[:startLine]...)
  162. result = append(result, newLines...)
  163. result = append(result, session.lines[endLine:]...)
  164. session.lines = result
  165. }
  166. // Update current content
  167. session.currentContent = []byte(joinLines(session.lines))
  168. // Store the updated session
  169. s.sessions.Store(req.GetDiffId(), session)
  170. if s.verbose {
  171. log.Printf("Updated diff session %s: %d lines, %d bytes",
  172. req.GetDiffId(), len(session.lines), len(session.currentContent))
  173. }
  174. return &proto.ReplaceTextResponse{}, nil
  175. }
  176. // ScrollDiff scrolls the diff view to a specific line (no-op for CLI)
  177. func (s *DiffService) ScrollDiff(ctx context.Context, req *proto.ScrollDiffRequest) (*proto.ScrollDiffResponse, error) {
  178. if s.verbose {
  179. log.Printf("ScrollDiff called for diff ID: %s, line: %d", req.GetDiffId(), req.GetLine())
  180. }
  181. // Verify session exists
  182. if _, exists := s.sessions.Load(req.GetDiffId()); !exists {
  183. return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
  184. }
  185. // In a CLI implementation, scrolling is a no-op
  186. // In a GUI implementation, this would scroll the view to the specified line
  187. return &proto.ScrollDiffResponse{}, nil
  188. }
  189. // TruncateDocument truncates the diff document at the specified line
  190. func (s *DiffService) TruncateDocument(ctx context.Context, req *proto.TruncateDocumentRequest) (*proto.TruncateDocumentResponse, error) {
  191. if s.verbose {
  192. log.Printf("TruncateDocument called for diff ID: %s, end line: %d", req.GetDiffId(), req.GetEndLine())
  193. }
  194. sessionInterface, exists := s.sessions.Load(req.GetDiffId())
  195. if !exists {
  196. return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
  197. }
  198. session := sessionInterface.(*diffSession)
  199. endLine := int(req.GetEndLine())
  200. // Truncate lines at the specified position
  201. if endLine >= 0 && endLine < len(session.lines) {
  202. session.lines = session.lines[:endLine]
  203. session.currentContent = []byte(joinLines(session.lines))
  204. // Store the updated session
  205. s.sessions.Store(req.GetDiffId(), session)
  206. if s.verbose {
  207. log.Printf("Truncated diff session %s to %d lines", req.GetDiffId(), len(session.lines))
  208. }
  209. }
  210. return &proto.TruncateDocumentResponse{}, nil
  211. }
  212. // SaveDocument saves the diff document to the original file
  213. func (s *DiffService) SaveDocument(ctx context.Context, req *proto.SaveDocumentRequest) (*proto.SaveDocumentResponse, error) {
  214. if s.verbose {
  215. log.Printf("SaveDocument called for diff ID: %s", req.GetDiffId())
  216. }
  217. sessionInterface, exists := s.sessions.Load(req.GetDiffId())
  218. if !exists {
  219. return nil, fmt.Errorf("diff session not found: %s", req.GetDiffId())
  220. }
  221. session := sessionInterface.(*diffSession)
  222. if session.originalPath == "" {
  223. return nil, fmt.Errorf("no file path specified for diff session: %s", req.GetDiffId())
  224. }
  225. // Create parent directories if they don't exist
  226. dir := filepath.Dir(session.originalPath)
  227. if err := os.MkdirAll(dir, 0755); err != nil {
  228. return nil, fmt.Errorf("failed to create directories: %w", err)
  229. }
  230. // Write the current content to the original file
  231. if err := ioutil.WriteFile(session.originalPath, session.currentContent, 0644); err != nil {
  232. return nil, fmt.Errorf("failed to save file: %w", err)
  233. }
  234. if s.verbose {
  235. log.Printf("Saved diff session %s to file: %s (%d bytes)",
  236. req.GetDiffId(), session.originalPath, len(session.currentContent))
  237. }
  238. return &proto.SaveDocumentResponse{}, nil
  239. }
  240. // CloseAllDiffs closes all diff views and cleans up all sessions
  241. func (s *DiffService) CloseAllDiffs(ctx context.Context, req *proto.CloseAllDiffsRequest) (*proto.CloseAllDiffsResponse, error) {
  242. if s.verbose {
  243. log.Printf("CloseAllDiffs called")
  244. }
  245. var count int64
  246. s.sessions.Range(func(key, value any) bool {
  247. // Optional: attempt to close if the value supports it
  248. if c, ok := value.(interface{ Close() error }); ok {
  249. _ = c.Close() // best-effort; ignore error
  250. }
  251. s.sessions.Delete(key)
  252. atomic.AddInt64(&count, 1)
  253. return true
  254. })
  255. if s.verbose {
  256. log.Printf("Closed %d diff sessions", count)
  257. }
  258. return &proto.CloseAllDiffsResponse{}, nil
  259. }
  260. // OpenMultiFileDiff displays a diff view comparing before/after states for multiple files
  261. func (s *DiffService) OpenMultiFileDiff(ctx context.Context, req *proto.OpenMultiFileDiffRequest) (*proto.OpenMultiFileDiffResponse, error) {
  262. if s.verbose {
  263. log.Printf("OpenMultiFileDiff called with title: %s, %d files", req.GetTitle(), len(req.GetDiffs()))
  264. }
  265. // In a CLI implementation, we could display the diffs to console
  266. // For now, we'll just log the information
  267. title := req.GetTitle()
  268. if title == "" {
  269. title = "Multi-file diff"
  270. }
  271. if s.verbose {
  272. log.Printf("=== %s ===", title)
  273. for i, diff := range req.GetDiffs() {
  274. log.Printf("File %d: %s", i+1, diff.GetFilePath())
  275. log.Printf(" Left content: %d bytes", len(diff.GetLeftContent()))
  276. log.Printf(" Right content: %d bytes", len(diff.GetRightContent()))
  277. }
  278. }
  279. // In a more sophisticated CLI implementation, we could:
  280. // 1. Use a diff library to generate unified diffs
  281. // 2. Display them with colors
  282. // 3. Allow navigation between files
  283. // For now, this is a no-op that just acknowledges the request
  284. return &proto.OpenMultiFileDiffResponse{}, nil
  285. }