uast.go 20 KB

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