forked from cloudwego/abcoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2352 lines (2073 loc) · 71.6 KB
/
main.go
File metadata and controls
2352 lines (2073 loc) · 71.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Copyright 2024 ByteDance Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/cloudwego/abcoder/internal/pipeline"
"github.com/cloudwego/abcoder/lang"
"github.com/cloudwego/abcoder/lang/collect"
"github.com/cloudwego/abcoder/lang/log"
"github.com/cloudwego/abcoder/lang/translate"
"github.com/cloudwego/abcoder/lang/uniast"
"github.com/cloudwego/abcoder/lang/utils"
"github.com/cloudwego/abcoder/llm"
"github.com/cloudwego/abcoder/llm/agent"
"github.com/cloudwego/abcoder/llm/mcp"
"github.com/cloudwego/abcoder/llm/tool"
"github.com/cloudwego/abcoder/version"
"github.com/cloudwego/eino/schema"
)
const Usage = `abcoder <Action> [Language] <Path> [Flags]
Action:
parse parse the specific repo and write its UniAST (to stdout by default)
write write the specific UniAST back to codes
translate translate code from one language to another (e.g., java to go)
mcp run as a MCP server for all repo ASTs (*.json) in the specific directory
agent run as an Agent for all repo ASTs (*.json) in the specific directory. WIP: only support code-analyzing at present.
skills manage skills (list, install, etc.)
version print the version of abcoder
Language:
go for golang codes
rust for rust codes
cxx for c codes (cpp support is on the way)
python for python codes
ts for typescript codes
js for javascript codes
java for java codes
`
func main() {
flags := flag.NewFlagSet("abcoder", flag.ExitOnError)
flagHelp := flags.Bool("h", false, "Show help message.")
flagVerbose := flags.Bool("verbose", false, "Verbose mode.")
flagOutput := flags.String("o", "", "Output path.")
flagLsp := flags.String("lsp", "", "Specify the language server path.")
javaHome := flags.String("java-home", "", "java home")
var opts lang.ParseOptions
flags.BoolVar(&opts.LoadExternalSymbol, "load-external-symbol", false, "load external symbols into results")
flags.BoolVar(&opts.NoNeedComment, "no-need-comment", false, "not need comment (only works for Go now)")
flags.BoolVar(&opts.NotNeedTest, "no-need-test", false, "not need parse test files (only works for Go now)")
flags.BoolVar(&opts.LoadByPackages, "load-by-packages", false, "load by packages (only works for Go now)")
flags.Var((*StringArray)(&opts.Excludes), "exclude", "exclude files or directories, support multiple values")
flags.StringVar(&opts.RepoID, "repo-id", "", "specify the repo id")
flags.StringVar(&opts.TSConfig, "tsconfig", "", "tsconfig path (only works for TS now)")
flags.Var((*StringArray)(&opts.TSSrcDir), "ts-src-dir", "src-dir path (only works for TS now)")
var wopts lang.WriteOptions
flags.StringVar(&wopts.Compiler, "compiler", "", "destination compiler path.")
var aopts agent.AgentOptions
flags.IntVar(&aopts.MaxSteps, "agent-max-steps", 50, "specify the max steps that the agent can run for each time")
flags.IntVar(&aopts.MaxHistories, "agent-max-histories", 10, "specify the max histories that the agent can use")
var skillName string
flags.StringVar(&skillName, "skill", "", "specify skill name to use (empty for auto-match)")
// Translation post-processing options
var webFramework string
flags.StringVar(&webFramework, "framework", "", "web framework for translation: gin, echo, actix, fastapi, flask, none (default: auto)")
var noEntryPoint bool
flags.BoolVar(&noEntryPoint, "no-entry", false, "skip entry point generation")
var noConfig bool
flags.BoolVar(&noConfig, "no-config", false, "skip project config generation (go.mod, Cargo.toml, etc.)")
flags.Usage = func() {
fmt.Fprint(os.Stderr, Usage)
fmt.Fprintf(os.Stderr, "Flags:\n")
flags.PrintDefaults()
}
if len(os.Args) < 2 {
flags.Usage()
os.Exit(1)
}
action := strings.ToLower(os.Args[1])
switch action {
case "version":
fmt.Fprintf(os.Stdout, "%s\n", version.Version)
case "parse":
language, uri := parseArgsAndFlags(flags, true, flagHelp, flagVerbose)
if flagVerbose != nil && *flagVerbose {
log.SetLogLevel(log.DebugLevel)
opts.Verbose = true
}
opts.Language = language
if language == uniast.TypeScript {
if err := parseTSProject(context.Background(), uri, opts, flagOutput); err != nil {
log.Error("Failed to parse: %v\n", err)
os.Exit(1)
}
return
}
if flagLsp != nil {
opts.LSP = *flagLsp
}
lspOptions := make(map[string]string)
if javaHome != nil {
lspOptions["java.home"] = *javaHome
}
opts.LspOptions = lspOptions
out, err := lang.Parse(context.Background(), uri, opts)
if err != nil {
log.Error("Failed to parse: %v\n", err)
os.Exit(1)
}
if flagOutput != nil && *flagOutput != "" {
if err := utils.MustWriteFile(*flagOutput, out); err != nil {
log.Error("Failed to write output: %v\n", err)
}
} else {
fmt.Fprintf(os.Stdout, "%s\n", out)
}
case "write":
_, uri := parseArgsAndFlags(flags, false, flagHelp, flagVerbose)
if uri == "" {
log.Error("Argument Path is required\n")
os.Exit(1)
}
repo, err := uniast.LoadRepo(uri)
if err != nil {
log.Error("Failed to load repo: %v\n", err)
os.Exit(1)
}
if flagOutput != nil && *flagOutput != "" {
wopts.OutputDir = *flagOutput
} else {
wopts.OutputDir = filepath.Base(repo.Path)
}
if err := lang.Write(context.Background(), repo, wopts); err != nil {
log.Error("Failed to write: %v\n", err)
os.Exit(1)
}
case "mcp":
_, uri := parseArgsAndFlags(flags, false, flagHelp, flagVerbose)
if uri == "" {
log.Error("Argument Path is required\n")
os.Exit(1)
}
svr := mcp.NewServer(mcp.ServerOptions{
ServerName: "abcoder",
ServerVersion: version.Version,
Verbose: *flagVerbose,
ASTReadToolsOptions: tool.ASTReadToolsOptions{
RepoASTsDir: uri,
},
})
if err := svr.ServeStdio(); err != nil {
log.Error("Failed to run MCP server: %v\n", err)
os.Exit(1)
}
case "translate":
srcLang, dstLang, uri := parseTranslateArgs(flags, flagHelp, flagVerbose)
if uri == "" {
log.Error("Argument Path is required\n")
os.Exit(1)
}
// Validate source and destination languages
supportedSrcLangs := []uniast.Language{uniast.Java, uniast.Golang, uniast.Python, uniast.Rust, uniast.Cxx, uniast.TypeScript}
supportedDstLangs := []uniast.Language{uniast.Golang, uniast.Python, uniast.Rust, uniast.Java, uniast.Cxx}
srcSupported := false
for _, l := range supportedSrcLangs {
if srcLang == l {
srcSupported = true
break
}
}
if !srcSupported {
log.Error("Unsupported source language: %s. Supported: java, go, python, rust, cxx, ts\n", srcLang)
os.Exit(1)
}
dstSupported := false
for _, l := range supportedDstLangs {
if dstLang == l {
dstSupported = true
break
}
}
if !dstSupported {
log.Error("Unsupported destination language: %s. Supported: java, go, python, rust, cxx\n", dstLang)
os.Exit(1)
}
if srcLang == dstLang {
log.Error("Source and destination languages must be different\n")
os.Exit(1)
}
log.Info("Translating %s → %s\n", srcLang, dstLang)
if flagVerbose != nil && *flagVerbose {
log.SetLogLevel(log.DebugLevel)
}
// Pipeline state for this run (which step failed, attempt N, status)
pipelineState := &pipeline.PipelineState{
RunID: fmt.Sprintf("%d", time.Now().UnixNano()),
SourceLang: srcLang,
TargetLang: dstLang,
SourceCodePath: uri,
OutputPath: "",
History: nil,
}
reportPipelineFailureAndExit := func() {
if n := len(pipelineState.History); n > 0 {
last := pipelineState.History[n-1]
log.Info("Pipeline: last step=%s, attempt=%d, status=%s\n", last.StepName, last.Attempt, last.Status)
}
os.Exit(1)
}
// Parse source project to UniAST
tempASTDir := filepath.Join(os.TempDir(), "abcoder-translate-asts")
os.MkdirAll(tempASTDir, 0755)
tempASTFile := filepath.Join(tempASTDir, fmt.Sprintf("%s-repo.json", srcLang))
parseOpts := lang.ParseOptions{
CollectOption: collect.CollectOption{
Language: srcLang,
},
}
if flagLsp != nil {
parseOpts.LSP = *flagLsp
}
lspOptions := make(map[string]string)
if javaHome != nil {
lspOptions["java.home"] = *javaHome
}
parseOpts.LspOptions = lspOptions
parseOpts.TSConfig = opts.TSConfig
parseOpts.TSSrcDir = opts.TSSrcDir
var srcRepo *uniast.Repository
usedExistingUniAST := false
var existingUniASTPath string
if stat, err := os.Stat(uri); err == nil {
var candidatePath string
if stat.IsDir() {
candidatePath = filepath.Join(uri, "uniast.json")
} else if !stat.IsDir() && strings.HasSuffix(strings.ToLower(uri), ".json") {
candidatePath = uri
}
if candidatePath != "" {
if s, err := os.Stat(candidatePath); err == nil && s != nil && !s.IsDir() {
loaded, err := uniast.LoadRepo(candidatePath)
if err == nil {
srcRepo = loaded
usedExistingUniAST = true
existingUniASTPath = candidatePath
log.Info("Using existing UniAST: %s, skip parsing\n", candidatePath)
} else {
// User explicitly passed a .json path; failed load is fatal (don't fall back to parsing a file as directory)
if candidatePath == uri {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "parse", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("Failed to load UniAST from %s: %v\n", candidatePath, err)
reportPipelineFailureAndExit()
}
log.Info("Failed to load existing UniAST, will parse: %v\n", err)
}
}
}
}
if !usedExistingUniAST {
if srcLang == uniast.TypeScript {
if err := parseTSProject(context.Background(), uri, parseOpts, &tempASTFile); err != nil {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "parse", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("Failed to parse TypeScript project: %v\n", err)
reportPipelineFailureAndExit()
}
var err error
srcRepo, err = uniast.LoadRepo(tempASTFile)
if err != nil {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "parse", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("Failed to load TypeScript repository: %v\n", err)
reportPipelineFailureAndExit()
}
} else {
astJSON, err := lang.Parse(context.Background(), uri, parseOpts)
if err != nil {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "parse", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("Failed to parse %s project: %v\n", srcLang, err)
reportPipelineFailureAndExit()
}
if err := utils.MustWriteFile(tempASTFile, astJSON); err != nil {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "parse", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("Failed to write AST file: %v\n", err)
reportPipelineFailureAndExit()
}
srcRepo, err = uniast.LoadRepo(tempASTFile)
if err != nil {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "parse", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("Failed to load %s repository: %v\n", srcLang, err)
reportPipelineFailureAndExit()
}
}
}
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "parse", Attempt: 1, Status: pipeline.StepOK, Time: time.Now(),
})
if usedExistingUniAST {
log.Info("%s UniAST: %s\n", srcLang, existingUniASTPath)
} else {
log.Info("%s UniAST generated and saved to: %s\n", srcLang, tempASTFile)
}
// Determine output directory
outputDir := ""
if flagOutput != nil && *flagOutput != "" {
outputDir = *flagOutput
} else {
outputDir = filepath.Base(uri) + "-" + string(dstLang)
}
pipelineState.OutputPath = outputDir
// Create output directory
if err := os.MkdirAll(outputDir, 0755); err != nil {
log.Error("Failed to create output directory: %v\n", err)
os.Exit(1)
}
// Setup LLM configuration
modelConfig := llm.ModelConfig{
APIType: llm.NewModelType(os.Getenv("API_TYPE")),
APIKey: os.Getenv("API_KEY"),
ModelName: os.Getenv("MODEL_NAME"),
BaseURL: os.Getenv("BASE_URL"),
}
if modelConfig.APIType == llm.ModelTypeUnknown {
log.Error("env API_TYPE is required for translation")
os.Exit(1)
}
if modelConfig.APIKey == "" {
log.Error("env API_KEY is required for translation")
os.Exit(1)
}
if modelConfig.ModelName == "" {
log.Error("env MODEL_NAME is required for translation")
os.Exit(1)
}
// Create LLM translator callback
llmTranslator := createLLMTranslator(modelConfig)
// Determine web framework if auto
framework := webFramework
if framework == "" {
// Auto-detect based on target language
switch dstLang {
case uniast.Golang:
framework = "gin"
case uniast.Rust:
framework = "actix"
case uniast.Python:
framework = "fastapi"
default:
framework = "none"
}
}
// Prepare translation options using new API
concurrency := 16
if s := os.Getenv("TRANSLATE_CONCURRENCY"); s != "" {
if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= 128 {
concurrency = n
}
}
packageConcurrency := 1
if s := os.Getenv("TRANSLATE_PACKAGE_CONCURRENCY"); s != "" {
if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= 16 {
packageConcurrency = n
}
}
if packageConcurrency == 1 && translate.CountTranslatableNodes(srcRepo) > 500 {
packageConcurrency = 4
}
translateResult := &translate.TranslateResult{}
translateOpts := translate.TranslateOptions{
SourceLanguage: srcLang,
TargetLanguage: dstLang,
TargetModuleName: "", // Auto-derive from source
OutputDir: outputDir,
LLMTranslator: llmTranslator,
Parallel: true,
Concurrency: concurrency,
PackageConcurrency: packageConcurrency,
MaxDependenciesInPrompt: 25,
MaxSourceChars: 12000,
WebFramework: framework,
GenerateEntryPoint: !noEntryPoint,
GenerateConfig: !noConfig,
Result: translateResult,
ProgressCallback: func(done, total int, currentKind, currentNodeID string) {
if total > 0 {
pct := 100 * float64(done) / float64(total)
log.Info("Progress: %d/%d (%.1f%%) current: %s %s\n", done, total, pct, currentKind, currentNodeID)
}
},
}
// Transform source UniAST to target UniAST with LLM content translation
log.Info("Translating %s to %s using LLM (Parser → Transform → Writer flow)...\n", srcLang, dstLang)
// Use TranslateAST to get the target repo (so we can save it)
targetRepo, err := translate.TranslateAST(context.Background(), srcRepo, translateOpts)
if err != nil {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "transform", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("Failed to translate: %v\n", err)
reportPipelineFailureAndExit()
}
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "transform", Attempt: 1, Status: pipeline.StepOK, Time: time.Now(),
})
// Save target UniAST to JSON file
targetASTFile := filepath.Join(tempASTDir, fmt.Sprintf("%s-repo.json", dstLang))
targetASTJSON, err := json.MarshalIndent(targetRepo, "", " ")
if err != nil {
log.Error("Failed to marshal target AST: %v\n", err)
os.Exit(1)
}
if err := utils.MustWriteFile(targetASTFile, targetASTJSON); err != nil {
log.Error("Failed to write target AST file: %v\n", err)
os.Exit(1)
}
log.Info("Target UniAST saved to: %s\n", targetASTFile)
// Validate target UniAST before writing (reject invalid LLM output)
if err := uniast.ValidateRepository(targetRepo); err != nil {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "validate", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("UniAST validation failed (rejecting output): %v\n", err)
reportPipelineFailureAndExit()
}
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "validate", Attempt: 1, Status: pipeline.StepOK, Time: time.Now(),
})
// Snapshot target UniAST so rollback (e.g. on later failure) can restore; on Fatal validation we never reach here.
pipelineState.TargetUniAST = pipeline.NewSnapshot("target-uniast", targetRepo, targetASTJSON)
// Write target code using lang.Write
err = lang.Write(context.Background(), targetRepo, lang.WriteOptions{
OutputDir: outputDir,
})
if err != nil {
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "write", Attempt: 1, Status: pipeline.StepFailed, Error: err.Error(), Time: time.Now(),
})
log.Error("Failed to write target code: %v\n", err)
reportPipelineFailureAndExit()
}
pipelineState.History = append(pipelineState.History, pipeline.StepRecord{
StepName: "write", Attempt: 1, Status: pipeline.StepOK, Time: time.Now(),
})
// Report pipeline outcome (last step, attempt, status)
if n := len(pipelineState.History); n > 0 {
last := pipelineState.History[n-1]
log.Info("Pipeline: last step=%s, attempt=%d, status=%s\n", last.StepName, last.Attempt, last.Status)
}
if flagVerbose != nil && *flagVerbose {
for _, rec := range pipelineState.History {
if rec.Error != "" {
log.Debug(" step=%s attempt=%d status=%s error=%s\n", rec.StepName, rec.Attempt, rec.Status, rec.Error)
} else {
log.Debug(" step=%s attempt=%d status=%s\n", rec.StepName, rec.Attempt, rec.Status)
}
}
}
// Persist pipeline report (StepHistory) for observability
if reportPath := filepath.Join(outputDir, "abcoder-pipeline-report.json"); outputDir != "" {
report := struct {
RunID string `json:"run_id"`
History []pipeline.StepRecord `json:"history"`
}{RunID: pipelineState.RunID, History: pipelineState.History}
if reportJSON, err := json.MarshalIndent(report, "", " "); err == nil {
_ = os.WriteFile(reportPath, reportJSON, 0644)
}
}
// Lightweight checkpoint for future resume: translated_ids + source identifier
if outputDir != "" && translateResult.TranslatedIDs != nil {
ids := make([]string, 0, len(translateResult.TranslatedIDs))
for id := range translateResult.TranslatedIDs {
ids = append(ids, id)
}
sort.Strings(ids)
checkpoint := struct {
SourcePath string `json:"source_path"`
TranslatedIDs []string `json:"translated_ids"`
}{SourcePath: uri, TranslatedIDs: ids}
if checkpointJSON, err := json.MarshalIndent(checkpoint, "", " "); err == nil {
_ = os.WriteFile(filepath.Join(outputDir, "abcoder-translate-checkpoint.json"), checkpointJSON, 0644)
}
}
// Run target language specific post-processing
switch dstLang {
case uniast.Golang:
// Fix invalid imports in generated Go files
// First try to read module name from go.mod
moduleName := readGoModuleName(outputDir)
if moduleName == "" {
moduleName = translateOpts.TargetModuleName
}
if moduleName == "" {
moduleName = "github.com/example/" + filepath.Base(outputDir)
}
if err := fixGoImportsInFiles(outputDir, moduleName); err != nil {
log.Info("Failed to fix imports: %v\n", err)
}
// Run goimports to fix any remaining import issues and format code
if err := runGoimports(outputDir); err != nil {
log.Info("Failed to run goimports: %v\n", err)
}
// Run go mod tidy
if err := runGoModTidy(outputDir); err != nil {
log.Info("Failed to run go mod tidy: %v\n", err)
}
// Try to build
if err := runGoBuild(outputDir); err != nil {
log.Info("Go build failed: %v\n", err)
}
case uniast.Rust:
// Run cargo check
if err := runCargoCheck(outputDir); err != nil {
log.Info("Cargo check failed: %v\n", err)
}
case uniast.Python:
// Python doesn't need compilation, but we can check syntax
log.Info("Python code generated. Run 'python -m py_compile <file>' to check syntax.\n")
case uniast.Java:
// Java compilation would need maven or gradle
log.Info("Java code generated. Run 'mvn compile' or 'gradle build' to compile.\n")
case uniast.Cxx:
// C++ compilation would need cmake or make
log.Info("C++ code generated. Run 'cmake . && make' or 'g++ -o main *.cpp' to compile.\n")
}
log.Info("Translation completed successfully!\n")
log.Info("Source UniAST: %s\n", tempASTFile)
log.Info("Target UniAST: %s\n", targetASTFile)
log.Info("%s code written to: %s\n", dstLang, outputDir)
case "agent":
_, uri := parseArgsAndFlags(flags, false, flagHelp, flagVerbose)
if uri == "" {
log.Error("Argument Path is required\n")
os.Exit(1)
}
aopts.ASTsDir = uri
aopts.Model.APIType = llm.NewModelType(os.Getenv("API_TYPE"))
if aopts.Model.APIType == llm.ModelTypeUnknown {
log.Error("env API_TYPE is required")
os.Exit(1)
}
aopts.Model.APIKey = os.Getenv("API_KEY")
if aopts.Model.APIKey == "" {
log.Error("env API_KEY is required")
os.Exit(1)
}
aopts.Model.ModelName = os.Getenv("MODEL_NAME")
if aopts.Model.ModelName == "" {
log.Error("env MODEL_NAME is required")
os.Exit(1)
}
aopts.Model.BaseURL = os.Getenv("BASE_URL")
// 如果指定了 skill,使用 skill-based agent
if skillName != "" {
runSkillAgent(context.Background(), uri, skillName, aopts)
} else {
// 使用 coordinator 自动匹配 skill
runCoordinatorAgent(context.Background(), uri, aopts)
}
case "skills":
handleSkillsCommand(flags, flagHelp, flagVerbose)
}
}
func parseArgsAndFlags(flags *flag.FlagSet, needLang bool, flagHelp *bool, flagVerbose *bool) (language uniast.Language, uri string) {
if len(os.Args) < 3 {
flags.Usage()
os.Exit(1)
}
if needLang {
language = uniast.NewLanguage(os.Args[2])
if language == uniast.Unknown {
fmt.Fprintf(os.Stderr, "unsupported language: %s\n", os.Args[2])
os.Exit(1)
}
if len(os.Args) < 4 {
fmt.Fprintf(os.Stderr, "argument Path is required\n")
os.Exit(1)
}
uri = os.Args[3]
if len(os.Args) > 4 {
flags.Parse(os.Args[4:])
}
} else {
uri = os.Args[2]
if len(os.Args) > 3 {
flags.Parse(os.Args[3:])
}
}
if flagHelp != nil && *flagHelp {
flags.Usage()
os.Exit(0)
}
if flagVerbose != nil && *flagVerbose {
log.SetLogLevel(log.DebugLevel)
}
return language, uri
}
func parseTranslateArgs(flags *flag.FlagSet, flagHelp *bool, flagVerbose *bool) (srcLang uniast.Language, dstLang uniast.Language, uri string) {
if len(os.Args) < 5 {
fmt.Fprintf(os.Stderr, "Usage: abcoder translate <src-lang> <dst-lang> <path>\n")
fmt.Fprintf(os.Stderr, "Example: abcoder translate java go ./my-java-project\n")
os.Exit(1)
}
srcLang = uniast.NewLanguage(os.Args[2])
if srcLang == uniast.Unknown {
fmt.Fprintf(os.Stderr, "unsupported source language: %s\n", os.Args[2])
os.Exit(1)
}
dstLang = uniast.NewLanguage(os.Args[3])
if dstLang == uniast.Unknown {
fmt.Fprintf(os.Stderr, "unsupported destination language: %s\n", os.Args[3])
os.Exit(1)
}
uri = os.Args[4]
if len(os.Args) > 5 {
flags.Parse(os.Args[5:])
}
if flagHelp != nil && *flagHelp {
flags.Usage()
os.Exit(0)
}
if flagVerbose != nil && *flagVerbose {
log.SetLogLevel(log.DebugLevel)
}
return srcLang, dstLang, uri
}
type StringArray []string
func (s *StringArray) Set(value string) error {
*s = append(*s, value)
return nil
}
func (s *StringArray) String() string {
return strings.Join(*s, ",")
}
func parseTSProject(ctx context.Context, repoPath string, opts lang.ParseOptions, outputFlag *string) error {
if outputFlag == nil {
return fmt.Errorf("output path is required")
}
parserPath, err := exec.LookPath("abcoder-ts-parser")
if err != nil {
log.Info("abcoder-ts-parser not found, installing...")
cmd := exec.Command("npm", "install", "-g", "abcoder-ts-parser")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to install abcoder-ts-parser: %v", err)
}
parserPath, err = exec.LookPath("abcoder-ts-parser")
if err != nil {
return fmt.Errorf("failed to find abcoder-ts-parser after installation: %v", err)
}
}
args := []string{"parse", repoPath}
if len(opts.TSSrcDir) > 0 {
args = append(args, "--src", strings.Join(opts.TSSrcDir, ","))
}
if opts.TSConfig != "" {
args = append(args, "--tsconfig", opts.TSConfig)
}
if *outputFlag != "" {
args = append(args, "--output", *outputFlag)
}
args = append(args, "--monorepo-mode", "combined")
cmd := exec.CommandContext(ctx, parserPath, args...)
cmd.Env = append(os.Environ(), "NODE_OPTIONS=--max-old-space-size=65536")
cmd.Env = append(cmd.Env, "ABCODER_TOOL_VERSION="+version.Version)
cmd.Env = append(cmd.Env, "ABCODER_AST_VERSION="+uniast.Version)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Info("Running abcoder-ts-parser with args: %v", args)
return cmd.Run()
}
// extractGoCode extracts Go code from LLM response, removing markdown code blocks if present
func extractGoCode(response string) string {
response = strings.TrimSpace(response)
// Remove markdown code blocks
if strings.HasPrefix(response, "```go") {
response = strings.TrimPrefix(response, "```go")
response = strings.TrimSuffix(response, "```")
} else if strings.HasPrefix(response, "```") {
response = strings.TrimPrefix(response, "```")
idx := strings.Index(response, "\n")
if idx >= 0 {
response = response[idx+1:]
}
response = strings.TrimSuffix(response, "```")
}
return strings.TrimSpace(response)
}
// extractGoUniASTJSON extracts Go UniAST JSON from LLM response
func extractGoUniASTJSON(response string) string {
response = strings.TrimSpace(response)
// Try to find JSON in the response
// Look for JSON object start
startIdx := strings.Index(response, "{")
if startIdx == -1 {
return ""
}
// Find matching closing brace
braceCount := 0
endIdx := startIdx
for i := startIdx; i < len(response); i++ {
if response[i] == '{' {
braceCount++
} else if response[i] == '}' {
braceCount--
if braceCount == 0 {
endIdx = i + 1
break
}
}
}
if endIdx > startIdx {
jsonStr := response[startIdx:endIdx]
// Validate it's valid JSON by trying to parse it
var test interface{}
if err := json.Unmarshal([]byte(jsonStr), &test); err == nil {
return jsonStr
}
}
// Fallback: try to extract from markdown code blocks
if strings.Contains(response, "```json") {
start := strings.Index(response, "```json")
if start != -1 {
start += 7 // len("```json")
end := strings.Index(response[start:], "```")
if end != -1 {
return strings.TrimSpace(response[start : start+end])
}
}
}
// Last resort: return the whole response if it looks like JSON
if strings.HasPrefix(response, "{") && strings.HasSuffix(response, "}") {
return response
}
return ""
}
// determineGoFilePath determines the output Go file path based on package path and original file path
func determineGoFilePath(outputDir, goPkgPath, originalPath string) string {
// Get base filename and change extension to .go
baseName := filepath.Base(originalPath)
baseName = strings.TrimSuffix(baseName, filepath.Ext(baseName)) + ".go"
// If package path is different, create package directory structure
if goPkgPath != "" && goPkgPath != "." {
// Convert package path to directory structure
// For simple packages like "simple", just use the package name as directory
// For full paths like "github.com/example/project", extract the relative part
pkgDir := goPkgPath
// If it's a full module path, extract the relative part
if strings.HasPrefix(pkgDir, "github.com/") {
parts := strings.Split(pkgDir, "/")
if len(parts) > 2 {
// Use parts after github.com/org/repo
pkgDir = strings.Join(parts[2:], "/")
} else {
// Just use the last part
pkgDir = parts[len(parts)-1]
}
} else if strings.Contains(pkgDir, "/") {
// Already a path, use as is
} else {
// Simple package name, use as directory
}
// Create directory structure
if pkgDir != "" && pkgDir != "." {
return filepath.Join(outputDir, pkgDir, baseName)
}
}
return filepath.Join(outputDir, baseName)
}
// packageMiniAST represents a minimal UniAST structure for a single package
type packageMiniAST struct {
Package *uniast.Package `json:"package,omitempty"`
Functions map[string]*uniast.Function `json:"functions,omitempty"`
Types map[string]*uniast.Type `json:"types,omitempty"`
Vars map[string]*uniast.Var `json:"vars,omitempty"`
Files map[string]*uniast.File `json:"files,omitempty"`
Graph map[string]*uniast.Node `json:"graph,omitempty"`
}
// buildPackageUniAST builds a mini UniAST containing only one package
func buildPackageUniAST(repo *uniast.Repository, modName, pkgPath string, pkg *uniast.Package, mod *uniast.Module) *packageMiniAST {
mini := &packageMiniAST{
Package: pkg,
Functions: make(map[string]*uniast.Function),
Types: make(map[string]*uniast.Type),
Vars: make(map[string]*uniast.Var),
Files: make(map[string]*uniast.File),
Graph: make(map[string]*uniast.Node),
}
// Copy functions
for name, fn := range pkg.Functions {
mini.Functions[name] = fn
}
// Copy types
for name, tp := range pkg.Types {
mini.Types[name] = tp
}
// Copy vars
for name, v := range pkg.Vars {
mini.Vars[name] = v
}
// Copy relevant files
for path, file := range mod.Files {
if file.Package == pkgPath {
mini.Files[path] = file
}
}
// Copy relevant graph nodes
for id, node := range repo.Graph {
identity := uniast.NewIdentityFromString(id)
if identity.ModPath == modName && identity.PkgPath == pkgPath {
mini.Graph[id] = node
}
}
return mini
}
// mergePackageIntoRepo merges a translated package mini AST into the Go repository
func mergePackageIntoRepo(goRepo *uniast.Repository, goMod *uniast.Module, goPkgPath string, mini *packageMiniAST) {
// Create or get the package
goPkg, exists := goMod.Packages[goPkgPath]
if !exists {
goPkg = uniast.NewPackage(goPkgPath)
goMod.Packages[goPkgPath] = goPkg
}
// Merge functions
if mini.Functions != nil {
for name, fn := range mini.Functions {
if fn != nil {
// Update identity to use Go module
fn.ModPath = goMod.Name
fn.PkgPath = goPkgPath
goPkg.Functions[name] = fn
}
}
}
if mini.Package != nil && mini.Package.Functions != nil {
for name, fn := range mini.Package.Functions {
if fn != nil {
fn.ModPath = goMod.Name
fn.PkgPath = goPkgPath
goPkg.Functions[name] = fn
}
}
}
// Merge types
if mini.Types != nil {
for name, tp := range mini.Types {
if tp != nil {
tp.ModPath = goMod.Name