uast.go 20 KB

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