uast.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. package hercules
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. goioutil "io/ioutil"
  9. "os"
  10. "path"
  11. "runtime"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/gogo/protobuf/proto"
  16. "github.com/jeffail/tunny"
  17. "gopkg.in/bblfsh/client-go.v2"
  18. "gopkg.in/bblfsh/sdk.v1/protocol"
  19. "gopkg.in/bblfsh/sdk.v1/uast"
  20. "gopkg.in/src-d/enry.v1"
  21. "gopkg.in/src-d/go-git.v4"
  22. "gopkg.in/src-d/go-git.v4/plumbing"
  23. "gopkg.in/src-d/go-git.v4/plumbing/object"
  24. "gopkg.in/src-d/go-git.v4/utils/ioutil"
  25. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  26. "gopkg.in/src-d/hercules.v3/pb"
  27. )
  28. // UASTExtractor retrieves UASTs from Babelfish server which correspond to changed files in a commit.
  29. // It is a PipelineItem.
  30. type UASTExtractor struct {
  31. Endpoint string
  32. Context func() (context.Context, context.CancelFunc)
  33. PoolSize int
  34. Languages map[string]bool
  35. FailOnErrors bool
  36. ProcessedFiles map[string]int
  37. clients []*bblfsh.Client
  38. pool *tunny.WorkPool
  39. }
  40. const (
  41. uastExtractionSkipped = -(1 << 31)
  42. // ConfigUASTEndpoint is the name of the configuration option (UASTExtractor.Configure())
  43. // which sets the Babelfish server address.
  44. ConfigUASTEndpoint = "ConfigUASTEndpoint"
  45. // ConfigUASTTimeout is the name of the configuration option (UASTExtractor.Configure())
  46. // which sets the maximum amount of time to wait for a Babelfish server response.
  47. ConfigUASTTimeout = "ConfigUASTTimeout"
  48. // ConfigUASTPoolSize is the name of the configuration option (UASTExtractor.Configure())
  49. // which sets the number of goroutines to run for UAST parse queries.
  50. ConfigUASTPoolSize = "ConfigUASTPoolSize"
  51. // ConfigUASTFailOnErrors is the name of the configuration option (UASTExtractor.Configure())
  52. // which enables early exit in case of any Babelfish UAST parsing errors.
  53. ConfigUASTFailOnErrors = "ConfigUASTFailOnErrors"
  54. // ConfigUASTLanguages is the name of the configuration option (UASTExtractor.Configure())
  55. // which sets the list of languages to parse. Language names are at
  56. // https://doc.bblf.sh/languages.html Names are joined with a comma ",".
  57. ConfigUASTLanguages = "ConfigUASTLanguages"
  58. // FeatureUast is the name of the Pipeline feature which activates all the items related to UAST.
  59. FeatureUast = "uast"
  60. // DependencyUasts is the name of the dependency provided by UASTExtractor.
  61. DependencyUasts = "uasts"
  62. )
  63. type uastTask struct {
  64. Client *bblfsh.Client
  65. Lock *sync.RWMutex
  66. Dest map[plumbing.Hash]*uast.Node
  67. File *object.File
  68. Errors *[]error
  69. Status chan int
  70. }
  71. type worker struct {
  72. Client *bblfsh.Client
  73. Callback func(interface{}) interface{}
  74. }
  75. func (w worker) Ready() bool {
  76. return true
  77. }
  78. func (w worker) Job(data interface{}) interface{} {
  79. task := data.(uastTask)
  80. task.Client = w.Client
  81. return w.Callback(task)
  82. }
  83. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  84. func (exr *UASTExtractor) Name() string {
  85. return "UAST"
  86. }
  87. // Provides returns the list of names of entities which are produced by this PipelineItem.
  88. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  89. // to this list. Also used by hercules.Registry to build the global map of providers.
  90. func (exr *UASTExtractor) Provides() []string {
  91. arr := [...]string{DependencyUasts}
  92. return arr[:]
  93. }
  94. // Requires returns the list of names of entities which are needed by this PipelineItem.
  95. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  96. // entities are Provides() upstream.
  97. func (exr *UASTExtractor) Requires() []string {
  98. arr := [...]string{DependencyTreeChanges, DependencyBlobCache}
  99. return arr[:]
  100. }
  101. // Features which must be enabled for this PipelineItem to be automatically inserted into the DAG.
  102. func (exr *UASTExtractor) Features() []string {
  103. arr := [...]string{FeatureUast}
  104. return arr[:]
  105. }
  106. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  107. func (exr *UASTExtractor) ListConfigurationOptions() []ConfigurationOption {
  108. options := [...]ConfigurationOption{{
  109. Name: ConfigUASTEndpoint,
  110. Description: "How many days there are in a single band.",
  111. Flag: "bblfsh",
  112. Type: StringConfigurationOption,
  113. Default: "0.0.0.0:9432"}, {
  114. Name: ConfigUASTTimeout,
  115. Description: "Babelfish's server timeout in seconds.",
  116. Flag: "bblfsh-timeout",
  117. Type: IntConfigurationOption,
  118. Default: 20}, {
  119. Name: ConfigUASTPoolSize,
  120. Description: "Number of goroutines to extract UASTs.",
  121. Flag: "bblfsh-pool-size",
  122. Type: IntConfigurationOption,
  123. Default: runtime.NumCPU() * 2}, {
  124. Name: ConfigUASTFailOnErrors,
  125. Description: "Panic if there is a UAST extraction error.",
  126. Flag: "bblfsh-fail-on-error",
  127. Type: BoolConfigurationOption,
  128. Default: false}, {
  129. Name: ConfigUASTLanguages,
  130. Description: "Programming languages from which to extract UASTs. Separated by comma \",\".",
  131. Flag: "languages",
  132. Type: StringConfigurationOption,
  133. Default: "Python,Java"},
  134. }
  135. return options[:]
  136. }
  137. // Configure sets the properties previously published by ListConfigurationOptions().
  138. func (exr *UASTExtractor) Configure(facts map[string]interface{}) {
  139. if val, exists := facts[ConfigUASTEndpoint].(string); exists {
  140. exr.Endpoint = val
  141. }
  142. if val, exists := facts[ConfigUASTTimeout].(int); exists {
  143. exr.Context = func() (context.Context, context.CancelFunc) {
  144. return context.WithTimeout(context.Background(),
  145. time.Duration(val)*time.Second)
  146. }
  147. }
  148. if val, exists := facts[ConfigUASTPoolSize].(int); exists {
  149. exr.PoolSize = val
  150. }
  151. if val, exists := facts[ConfigUASTLanguages].(string); exists {
  152. exr.Languages = map[string]bool{}
  153. for _, lang := range strings.Split(val, ",") {
  154. exr.Languages[strings.TrimSpace(lang)] = true
  155. }
  156. }
  157. if val, exists := facts[ConfigUASTFailOnErrors].(bool); exists {
  158. exr.FailOnErrors = val
  159. }
  160. }
  161. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  162. // calls. The repository which is going to be analysed is supplied as an argument.
  163. func (exr *UASTExtractor) Initialize(repository *git.Repository) {
  164. if exr.Context == nil {
  165. exr.Context = func() (context.Context, context.CancelFunc) {
  166. return context.Background(), nil
  167. }
  168. }
  169. poolSize := exr.PoolSize
  170. if poolSize == 0 {
  171. poolSize = runtime.NumCPU()
  172. }
  173. var err error
  174. exr.clients = make([]*bblfsh.Client, poolSize)
  175. for i := 0; i < poolSize; i++ {
  176. client, err := bblfsh.NewClient(exr.Endpoint)
  177. if err != nil {
  178. panic(err)
  179. }
  180. exr.clients[i] = client
  181. }
  182. if exr.pool != nil {
  183. exr.pool.Close()
  184. }
  185. workers := make([]tunny.Worker, poolSize)
  186. for i := 0; i < poolSize; i++ {
  187. workers[i] = worker{Client: exr.clients[i], Callback: exr.extractTask}
  188. }
  189. exr.pool, err = tunny.CreateCustomPool(workers).Open()
  190. if err != nil {
  191. panic(err)
  192. }
  193. exr.ProcessedFiles = map[string]int{}
  194. if exr.Languages == nil {
  195. exr.Languages = map[string]bool{}
  196. }
  197. }
  198. // Consume runs this PipelineItem on the next commit data.
  199. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  200. // Additionally, "commit" is always present there and represents the analysed *object.Commit.
  201. // This function returns the mapping with analysis results. The keys must be the same as
  202. // in Provides(). If there was an error, nil is returned.
  203. func (exr *UASTExtractor) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  204. cache := deps[DependencyBlobCache].(map[plumbing.Hash]*object.Blob)
  205. treeDiffs := deps[DependencyTreeChanges].(object.Changes)
  206. uasts := map[plumbing.Hash]*uast.Node{}
  207. lock := sync.RWMutex{}
  208. errs := make([]error, 0)
  209. status := make(chan int)
  210. pending := 0
  211. submit := func(change *object.Change) {
  212. {
  213. reader, err := cache[change.To.TreeEntry.Hash].Reader()
  214. if err != nil {
  215. errs = append(errs, err)
  216. return
  217. }
  218. defer ioutil.CheckClose(reader, &err)
  219. buf := new(bytes.Buffer)
  220. if _, err := buf.ReadFrom(reader); err != nil {
  221. errs = append(errs, err)
  222. return
  223. }
  224. lang := enry.GetLanguage(change.To.Name, buf.Bytes())
  225. if _, exists := exr.Languages[lang]; !exists {
  226. exr.ProcessedFiles[change.To.Name] = uastExtractionSkipped
  227. return
  228. }
  229. exr.ProcessedFiles[change.To.Name]++
  230. }
  231. pending++
  232. exr.pool.SendWorkAsync(uastTask{
  233. Lock: &lock,
  234. Dest: uasts,
  235. File: &object.File{Name: change.To.Name, Blob: *cache[change.To.TreeEntry.Hash]},
  236. Errors: &errs, Status: status}, nil)
  237. }
  238. for _, change := range treeDiffs {
  239. action, err := change.Action()
  240. if err != nil {
  241. return nil, err
  242. }
  243. switch action {
  244. case merkletrie.Insert:
  245. submit(change)
  246. case merkletrie.Delete:
  247. continue
  248. case merkletrie.Modify:
  249. submit(change)
  250. }
  251. }
  252. for i := 0; i < pending; i++ {
  253. _ = <-status
  254. }
  255. if len(errs) > 0 {
  256. msgs := make([]string, len(errs))
  257. for i, err := range errs {
  258. msgs[i] = err.Error()
  259. }
  260. joined := strings.Join(msgs, "\n")
  261. if exr.FailOnErrors {
  262. return nil, errors.New(joined)
  263. }
  264. fmt.Fprintln(os.Stderr, joined)
  265. }
  266. return map[string]interface{}{DependencyUasts: uasts}, nil
  267. }
  268. func (exr *UASTExtractor) extractUAST(
  269. client *bblfsh.Client, file *object.File) (*uast.Node, error) {
  270. request := client.NewParseRequest()
  271. contents, err := file.Contents()
  272. if err != nil {
  273. return nil, err
  274. }
  275. request.Content(contents)
  276. request.Filename(file.Name)
  277. ctx, cancel := exr.Context()
  278. if cancel != nil {
  279. defer cancel()
  280. }
  281. response, err := request.DoWithContext(ctx)
  282. if err != nil {
  283. if strings.Contains("missing driver", err.Error()) {
  284. return nil, nil
  285. }
  286. return nil, err
  287. }
  288. if response.Status != protocol.Ok {
  289. return nil, errors.New(strings.Join(response.Errors, "\n"))
  290. }
  291. if err != nil {
  292. return nil, err
  293. }
  294. return response.UAST, nil
  295. }
  296. func (exr *UASTExtractor) extractTask(data interface{}) interface{} {
  297. task := data.(uastTask)
  298. defer func() { task.Status <- 0 }()
  299. node, err := exr.extractUAST(task.Client, task.File)
  300. task.Lock.Lock()
  301. defer task.Lock.Unlock()
  302. if err != nil {
  303. *task.Errors = append(*task.Errors, errors.New(task.File.Name+": "+err.Error()))
  304. return nil
  305. }
  306. if node != nil {
  307. task.Dest[task.File.Hash] = node
  308. }
  309. return nil
  310. }
  311. // UASTChange is the type of the items in the list of changes which is provided by UASTChanges.
  312. type UASTChange struct {
  313. Before *uast.Node
  314. After *uast.Node
  315. Change *object.Change
  316. }
  317. const (
  318. // DependencyUastChanges is the name of the dependency provided by UASTChanges.
  319. DependencyUastChanges = "changed_uasts"
  320. )
  321. // UASTChanges is a structured analog of TreeDiff: it provides UASTs for every logical change
  322. // in a commit. It is a PipelineItem.
  323. type UASTChanges struct {
  324. cache map[plumbing.Hash]*uast.Node
  325. }
  326. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  327. func (uc *UASTChanges) Name() string {
  328. return "UASTChanges"
  329. }
  330. // Provides returns the list of names of entities which are produced by this PipelineItem.
  331. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  332. // to this list. Also used by hercules.Registry to build the global map of providers.
  333. func (uc *UASTChanges) Provides() []string {
  334. arr := [...]string{DependencyUastChanges}
  335. return arr[:]
  336. }
  337. // Requires returns the list of names of entities which are needed by this PipelineItem.
  338. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  339. // entities are Provides() upstream.
  340. func (uc *UASTChanges) Requires() []string {
  341. arr := [...]string{DependencyUasts, DependencyTreeChanges}
  342. return arr[:]
  343. }
  344. // Features which must be enabled for this PipelineItem to be automatically inserted into the DAG.
  345. func (uc *UASTChanges) Features() []string {
  346. arr := [...]string{FeatureUast}
  347. return arr[:]
  348. }
  349. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  350. func (uc *UASTChanges) ListConfigurationOptions() []ConfigurationOption {
  351. return []ConfigurationOption{}
  352. }
  353. // Configure sets the properties previously published by ListConfigurationOptions().
  354. func (uc *UASTChanges) Configure(facts map[string]interface{}) {}
  355. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  356. // calls. The repository which is going to be analysed is supplied as an argument.
  357. func (uc *UASTChanges) Initialize(repository *git.Repository) {
  358. uc.cache = map[plumbing.Hash]*uast.Node{}
  359. }
  360. // Consume runs this PipelineItem on the next commit data.
  361. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  362. // Additionally, "commit" is always present there and represents the analysed *object.Commit.
  363. // This function returns the mapping with analysis results. The keys must be the same as
  364. // in Provides(). If there was an error, nil is returned.
  365. func (uc *UASTChanges) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  366. uasts := deps[DependencyUasts].(map[plumbing.Hash]*uast.Node)
  367. treeDiffs := deps[DependencyTreeChanges].(object.Changes)
  368. commit := make([]UASTChange, 0, len(treeDiffs))
  369. for _, change := range treeDiffs {
  370. action, err := change.Action()
  371. if err != nil {
  372. return nil, err
  373. }
  374. switch action {
  375. case merkletrie.Insert:
  376. hashTo := change.To.TreeEntry.Hash
  377. uastTo := uasts[hashTo]
  378. commit = append(commit, UASTChange{Before: nil, After: uastTo, Change: change})
  379. uc.cache[hashTo] = uastTo
  380. case merkletrie.Delete:
  381. hashFrom := change.From.TreeEntry.Hash
  382. commit = append(commit, UASTChange{Before: uc.cache[hashFrom], After: nil, Change: change})
  383. delete(uc.cache, hashFrom)
  384. case merkletrie.Modify:
  385. hashFrom := change.From.TreeEntry.Hash
  386. hashTo := change.To.TreeEntry.Hash
  387. uastTo := uasts[hashTo]
  388. commit = append(commit, UASTChange{Before: uc.cache[hashFrom], After: uastTo, Change: change})
  389. delete(uc.cache, hashFrom)
  390. uc.cache[hashTo] = uastTo
  391. }
  392. }
  393. return map[string]interface{}{DependencyUastChanges: commit}, nil
  394. }
  395. // UASTChangesSaver dumps changed files and corresponding UASTs for every commit.
  396. // it is a LeafPipelineItem.
  397. type UASTChangesSaver struct {
  398. // OutputPath points to the target directory with UASTs
  399. OutputPath string
  400. repository *git.Repository
  401. result [][]UASTChange
  402. }
  403. const (
  404. // ConfigUASTChangesSaverOutputPath is the name of the configuration option
  405. // (UASTChangesSaver.Configure()) which sets the target directory where to save the files.
  406. ConfigUASTChangesSaverOutputPath = "UASTChangesSaver.OutputPath"
  407. )
  408. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  409. func (saver *UASTChangesSaver) Name() string {
  410. return "UASTChangesSaver"
  411. }
  412. // Provides returns the list of names of entities which are produced by this PipelineItem.
  413. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  414. // to this list. Also used by hercules.Registry to build the global map of providers.
  415. func (saver *UASTChangesSaver) Provides() []string {
  416. return []string{}
  417. }
  418. // Requires returns the list of names of entities which are needed by this PipelineItem.
  419. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  420. // entities are Provides() upstream.
  421. func (saver *UASTChangesSaver) Requires() []string {
  422. arr := [...]string{DependencyUastChanges}
  423. return arr[:]
  424. }
  425. // Features which must be enabled for this PipelineItem to be automatically inserted into the DAG.
  426. func (saver *UASTChangesSaver) Features() []string {
  427. arr := [...]string{FeatureUast}
  428. return arr[:]
  429. }
  430. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  431. func (saver *UASTChangesSaver) ListConfigurationOptions() []ConfigurationOption {
  432. options := [...]ConfigurationOption{{
  433. Name: ConfigUASTChangesSaverOutputPath,
  434. Description: "The target directory where to store the changed UAST files.",
  435. Flag: "changed-uast-dir",
  436. Type: StringConfigurationOption,
  437. Default: "."},
  438. }
  439. return options[:]
  440. }
  441. // Flag for the command line switch which enables this analysis.
  442. func (saver *UASTChangesSaver) Flag() string {
  443. return "dump-uast-changes"
  444. }
  445. // Configure sets the properties previously published by ListConfigurationOptions().
  446. func (saver *UASTChangesSaver) Configure(facts map[string]interface{}) {
  447. if val, exists := facts[ConfigUASTChangesSaverOutputPath]; exists {
  448. saver.OutputPath = val.(string)
  449. }
  450. }
  451. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  452. // calls. The repository which is going to be analysed is supplied as an argument.
  453. func (saver *UASTChangesSaver) Initialize(repository *git.Repository) {
  454. saver.repository = repository
  455. saver.result = [][]UASTChange{}
  456. }
  457. // Consume runs this PipelineItem on the next commit data.
  458. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  459. // Additionally, "commit" is always present there and represents the analysed *object.Commit.
  460. // This function returns the mapping with analysis results. The keys must be the same as
  461. // in Provides(). If there was an error, nil is returned.
  462. func (saver *UASTChangesSaver) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  463. changes := deps[DependencyUastChanges].([]UASTChange)
  464. saver.result = append(saver.result, changes)
  465. return nil, nil
  466. }
  467. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  468. func (saver *UASTChangesSaver) Finalize() interface{} {
  469. return saver.result
  470. }
  471. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  472. // The text format is YAML and the bytes format is Protocol Buffers.
  473. func (saver *UASTChangesSaver) Serialize(result interface{}, binary bool, writer io.Writer) error {
  474. saverResult := result.([][]UASTChange)
  475. fileNames := saver.dumpFiles(saverResult)
  476. if binary {
  477. return saver.serializeBinary(fileNames, writer)
  478. }
  479. saver.serializeText(fileNames, writer)
  480. return nil
  481. }
  482. func (saver *UASTChangesSaver) dumpFiles(result [][]UASTChange) []*pb.UASTChange {
  483. fileNames := []*pb.UASTChange{}
  484. for i, changes := range result {
  485. for j, change := range changes {
  486. if change.Before == nil || change.After == nil {
  487. continue
  488. }
  489. record := &pb.UASTChange{FileName: change.Change.To.Name}
  490. bs, _ := change.Before.Marshal()
  491. record.UastBefore = path.Join(saver.OutputPath, fmt.Sprintf(
  492. "%d_%d_before_%s.pb", i, j, change.Change.From.TreeEntry.Hash.String()))
  493. goioutil.WriteFile(record.UastBefore, bs, 0666)
  494. blob, _ := saver.repository.BlobObject(change.Change.From.TreeEntry.Hash)
  495. s, _ := (&object.File{Blob: *blob}).Contents()
  496. record.SrcBefore = path.Join(saver.OutputPath, fmt.Sprintf(
  497. "%d_%d_before_%s.src", i, j, change.Change.From.TreeEntry.Hash.String()))
  498. goioutil.WriteFile(record.SrcBefore, []byte(s), 0666)
  499. bs, _ = change.After.Marshal()
  500. record.UastAfter = path.Join(saver.OutputPath, fmt.Sprintf(
  501. "%d_%d_after_%s.pb", i, j, change.Change.To.TreeEntry.Hash.String()))
  502. goioutil.WriteFile(record.UastAfter, bs, 0666)
  503. blob, _ = saver.repository.BlobObject(change.Change.To.TreeEntry.Hash)
  504. s, _ = (&object.File{Blob: *blob}).Contents()
  505. record.SrcAfter = path.Join(saver.OutputPath, fmt.Sprintf(
  506. "%d_%d_after_%s.src", i, j, change.Change.To.TreeEntry.Hash.String()))
  507. goioutil.WriteFile(record.SrcAfter, []byte(s), 0666)
  508. fileNames = append(fileNames, record)
  509. }
  510. }
  511. return fileNames
  512. }
  513. func (saver *UASTChangesSaver) serializeText(result []*pb.UASTChange, writer io.Writer) {
  514. for _, sc := range result {
  515. kv := [...]string{
  516. "file: " + sc.FileName,
  517. "src0: " + sc.SrcBefore, "src1: " + sc.SrcAfter,
  518. "uast0: " + sc.UastBefore, "uast1: " + sc.UastAfter,
  519. }
  520. fmt.Fprintf(writer, " - {%s}\n", strings.Join(kv[:], ", "))
  521. }
  522. }
  523. func (saver *UASTChangesSaver) serializeBinary(result []*pb.UASTChange, writer io.Writer) error {
  524. message := pb.UASTChangesSaverResults{Changes: result}
  525. serialized, err := proto.Marshal(&message)
  526. if err != nil {
  527. return err
  528. }
  529. writer.Write(serialized)
  530. return nil
  531. }
  532. func init() {
  533. Registry.Register(&UASTExtractor{})
  534. Registry.Register(&UASTChanges{})
  535. Registry.Register(&UASTChangesSaver{})
  536. }