pipeline.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. package core
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "sort"
  11. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. "gopkg.in/src-d/go-git.v4"
  15. "gopkg.in/src-d/go-git.v4/plumbing"
  16. "gopkg.in/src-d/go-git.v4/plumbing/object"
  17. "gopkg.in/src-d/hercules.v4/internal/pb"
  18. "gopkg.in/src-d/hercules.v4/internal/toposort"
  19. "gopkg.in/src-d/go-git.v4/plumbing/storer"
  20. )
  21. // ConfigurationOptionType represents the possible types of a ConfigurationOption's value.
  22. type ConfigurationOptionType int
  23. const (
  24. // BoolConfigurationOption reflects the boolean value type.
  25. BoolConfigurationOption ConfigurationOptionType = iota
  26. // IntConfigurationOption reflects the integer value type.
  27. IntConfigurationOption
  28. // StringConfigurationOption reflects the string value type.
  29. StringConfigurationOption
  30. // FloatConfigurationOption reflects a floating point value type.
  31. FloatConfigurationOption
  32. // StringsConfigurationOption reflects the array of strings value type.
  33. StringsConfigurationOption
  34. )
  35. // String() returns an empty string for the boolean type, "int" for integers and "string" for
  36. // strings. It is used in the command line interface to show the argument's type.
  37. func (opt ConfigurationOptionType) String() string {
  38. switch opt {
  39. case BoolConfigurationOption:
  40. return ""
  41. case IntConfigurationOption:
  42. return "int"
  43. case StringConfigurationOption:
  44. return "string"
  45. case FloatConfigurationOption:
  46. return "float"
  47. case StringsConfigurationOption:
  48. return "string"
  49. }
  50. log.Panicf("Invalid ConfigurationOptionType value %d", opt)
  51. return ""
  52. }
  53. // ConfigurationOption allows for the unified, retrospective way to setup PipelineItem-s.
  54. type ConfigurationOption struct {
  55. // Name identifies the configuration option in facts.
  56. Name string
  57. // Description represents the help text about the configuration option.
  58. Description string
  59. // Flag corresponds to the CLI token with "--" prepended.
  60. Flag string
  61. // Type specifies the kind of the configuration option's value.
  62. Type ConfigurationOptionType
  63. // Default is the initial value of the configuration option.
  64. Default interface{}
  65. }
  66. // FormatDefault converts the default value of ConfigurationOption to string.
  67. // Used in the command line interface to show the argument's default value.
  68. func (opt ConfigurationOption) FormatDefault() string {
  69. if opt.Type == StringsConfigurationOption {
  70. return fmt.Sprintf("\"%s\"", strings.Join(opt.Default.([]string), ","))
  71. }
  72. if opt.Type != StringConfigurationOption {
  73. return fmt.Sprint(opt.Default)
  74. }
  75. return fmt.Sprintf("\"%s\"", opt.Default)
  76. }
  77. // PipelineItem is the interface for all the units in the Git commits analysis pipeline.
  78. type PipelineItem interface {
  79. // Name returns the name of the analysis.
  80. Name() string
  81. // Provides returns the list of keys of reusable calculated entities.
  82. // Other items may depend on them.
  83. Provides() []string
  84. // Requires returns the list of keys of needed entities which must be supplied in Consume().
  85. Requires() []string
  86. // ListConfigurationOptions returns the list of available options which can be consumed by Configure().
  87. ListConfigurationOptions() []ConfigurationOption
  88. // Configure performs the initial setup of the object by applying parameters from facts.
  89. // It allows to create PipelineItems in a universal way.
  90. Configure(facts map[string]interface{})
  91. // Initialize prepares and resets the item. Consume() requires Initialize()
  92. // to be called at least once beforehand.
  93. Initialize(*git.Repository)
  94. // Consume processes the next commit.
  95. // deps contains the required entities which match Depends(). Besides, it always includes
  96. // DependencyCommit and DependencyIndex.
  97. // Returns the calculated entities which match Provides().
  98. Consume(deps map[string]interface{}) (map[string]interface{}, error)
  99. // Fork clones the item the requested number of times. The data links between the clones
  100. // are up to the implementation. Needed to handle Git branches. See also Merge().
  101. // Returns a slice with `n` fresh clones. In other words, it does not include the original item.
  102. Fork(n int) []PipelineItem
  103. // Merge combines several branches together. Each is supposed to have been created with Fork().
  104. // The result is stored in the called item, thus this function returns nothing.
  105. // Merge() must update all the branches, not only self. When several branches merge, some of
  106. // them may continue to live, hence this requirement.
  107. Merge(branches []PipelineItem)
  108. }
  109. // FeaturedPipelineItem enables switching the automatic insertion of pipeline items on or off.
  110. type FeaturedPipelineItem interface {
  111. PipelineItem
  112. // Features returns the list of names which enable this item to be automatically inserted
  113. // in Pipeline.DeployItem().
  114. Features() []string
  115. }
  116. // LeafPipelineItem corresponds to the top level pipeline items which produce the end results.
  117. type LeafPipelineItem interface {
  118. PipelineItem
  119. // Flag returns the cmdline name of the item.
  120. Flag() string
  121. // Finalize returns the result of the analysis.
  122. Finalize() interface{}
  123. // Serialize encodes the object returned by Finalize() to YAML or Protocol Buffers.
  124. Serialize(result interface{}, binary bool, writer io.Writer) error
  125. }
  126. // ResultMergeablePipelineItem specifies the methods to combine several analysis results together.
  127. type ResultMergeablePipelineItem interface {
  128. LeafPipelineItem
  129. // Deserialize loads the result from Protocol Buffers blob.
  130. Deserialize(pbmessage []byte) (interface{}, error)
  131. // MergeResults joins two results together. Common-s are specified as the global state.
  132. MergeResults(r1, r2 interface{}, c1, c2 *CommonAnalysisResult) interface{}
  133. }
  134. // CommonAnalysisResult holds the information which is always extracted at Pipeline.Run().
  135. type CommonAnalysisResult struct {
  136. // BeginTime is the time of the first commit in the analysed sequence.
  137. BeginTime int64
  138. // EndTime is the time of the last commit in the analysed sequence.
  139. EndTime int64
  140. // CommitsNumber is the number of commits in the analysed sequence.
  141. CommitsNumber int
  142. // RunTime is the duration of Pipeline.Run().
  143. RunTime time.Duration
  144. // RunTimePerItem is the time elapsed by each PipelineItem.
  145. RunTimePerItem map[string]float64
  146. }
  147. // BeginTimeAsTime converts the UNIX timestamp of the beginning to Go time.
  148. func (car *CommonAnalysisResult) BeginTimeAsTime() time.Time {
  149. return time.Unix(car.BeginTime, 0)
  150. }
  151. // EndTimeAsTime converts the UNIX timestamp of the ending to Go time.
  152. func (car *CommonAnalysisResult) EndTimeAsTime() time.Time {
  153. return time.Unix(car.EndTime, 0)
  154. }
  155. // Merge combines the CommonAnalysisResult with an other one.
  156. // We choose the earlier BeginTime, the later EndTime, sum the number of commits and the
  157. // elapsed run times.
  158. func (car *CommonAnalysisResult) Merge(other *CommonAnalysisResult) {
  159. if car.EndTime == 0 || other.BeginTime == 0 {
  160. panic("Merging with an uninitialized CommonAnalysisResult")
  161. }
  162. if other.BeginTime < car.BeginTime {
  163. car.BeginTime = other.BeginTime
  164. }
  165. if other.EndTime > car.EndTime {
  166. car.EndTime = other.EndTime
  167. }
  168. car.CommitsNumber += other.CommitsNumber
  169. car.RunTime += other.RunTime
  170. for key, val := range other.RunTimePerItem {
  171. car.RunTimePerItem[key] += val
  172. }
  173. }
  174. // FillMetadata copies the data to a Protobuf message.
  175. func (car *CommonAnalysisResult) FillMetadata(meta *pb.Metadata) *pb.Metadata {
  176. meta.BeginUnixTime = car.BeginTime
  177. meta.EndUnixTime = car.EndTime
  178. meta.Commits = int32(car.CommitsNumber)
  179. meta.RunTime = car.RunTime.Nanoseconds() / 1e6
  180. meta.RunTimePerItem = car.RunTimePerItem
  181. return meta
  182. }
  183. // Metadata is defined in internal/pb/pb.pb.go - header of the binary file.
  184. type Metadata = pb.Metadata
  185. // MetadataToCommonAnalysisResult copies the data from a Protobuf message.
  186. func MetadataToCommonAnalysisResult(meta *Metadata) *CommonAnalysisResult {
  187. return &CommonAnalysisResult{
  188. BeginTime: meta.BeginUnixTime,
  189. EndTime: meta.EndUnixTime,
  190. CommitsNumber: int(meta.Commits),
  191. RunTime: time.Duration(meta.RunTime * 1e6),
  192. RunTimePerItem: meta.RunTimePerItem,
  193. }
  194. }
  195. // Pipeline is the core Hercules entity which carries several PipelineItems and executes them.
  196. // See the extended example of how a Pipeline works in doc.go
  197. type Pipeline struct {
  198. // OnProgress is the callback which is invoked in Analyse() to output it's
  199. // progress. The first argument is the number of complete steps and the
  200. // second is the total number of steps.
  201. OnProgress func(int, int)
  202. // Repository points to the analysed Git repository struct from go-git.
  203. repository *git.Repository
  204. // Items are the registered building blocks in the pipeline. The order defines the
  205. // execution sequence.
  206. items []PipelineItem
  207. // The collection of parameters to create items.
  208. facts map[string]interface{}
  209. // Feature flags which enable the corresponding items.
  210. features map[string]bool
  211. }
  212. const (
  213. // ConfigPipelineDumpPath is the name of the Pipeline configuration option (Pipeline.Initialize())
  214. // which enables saving the items DAG to the specified file.
  215. ConfigPipelineDumpPath = "Pipeline.DumpPath"
  216. // ConfigPipelineDryRun is the name of the Pipeline configuration option (Pipeline.Initialize())
  217. // which disables Configure() and Initialize() invocation on each PipelineItem during the
  218. // Pipeline initialization.
  219. // Subsequent Run() calls are going to fail. Useful with ConfigPipelineDumpPath=true.
  220. ConfigPipelineDryRun = "Pipeline.DryRun"
  221. // ConfigPipelineCommits is the name of the Pipeline configuration option (Pipeline.Initialize())
  222. // which allows to specify the custom commit sequence. By default, Pipeline.Commits() is used.
  223. ConfigPipelineCommits = "commits"
  224. // DependencyCommit is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  225. // which always exists. It corresponds to the currently analyzed commit.
  226. DependencyCommit = "commit"
  227. // DependencyIndex is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  228. // which always exists. It corresponds to the currently analyzed commit's index.
  229. DependencyIndex = "index"
  230. // DependencyIsMerge is the name of one of the three items in `deps` supplied to PipelineItem.Consume()
  231. // which always exists. It indicates whether the analyzed commit is a merge commit.
  232. // Checking the number of parents is not correct - we remove the back edges during the DAG simplification.
  233. DependencyIsMerge = "is_merge"
  234. )
  235. // NewPipeline initializes a new instance of Pipeline struct.
  236. func NewPipeline(repository *git.Repository) *Pipeline {
  237. return &Pipeline{
  238. repository: repository,
  239. items: []PipelineItem{},
  240. facts: map[string]interface{}{},
  241. features: map[string]bool{},
  242. }
  243. }
  244. // GetFact returns the value of the fact with the specified name.
  245. func (pipeline *Pipeline) GetFact(name string) interface{} {
  246. return pipeline.facts[name]
  247. }
  248. // SetFact sets the value of the fact with the specified name.
  249. func (pipeline *Pipeline) SetFact(name string, value interface{}) {
  250. pipeline.facts[name] = value
  251. }
  252. // GetFeature returns the state of the feature with the specified name (enabled/disabled) and
  253. // whether it exists. See also: FeaturedPipelineItem.
  254. func (pipeline *Pipeline) GetFeature(name string) (bool, bool) {
  255. val, exists := pipeline.features[name]
  256. return val, exists
  257. }
  258. // SetFeature sets the value of the feature with the specified name.
  259. // See also: FeaturedPipelineItem.
  260. func (pipeline *Pipeline) SetFeature(name string) {
  261. pipeline.features[name] = true
  262. }
  263. // SetFeaturesFromFlags enables the features which were specified through the command line flags
  264. // which belong to the given PipelineItemRegistry instance.
  265. // See also: AddItem().
  266. func (pipeline *Pipeline) SetFeaturesFromFlags(registry ...*PipelineItemRegistry) {
  267. var ffr *PipelineItemRegistry
  268. if len(registry) == 0 {
  269. ffr = Registry
  270. } else if len(registry) == 1 {
  271. ffr = registry[0]
  272. } else {
  273. panic("Zero or one registry is allowed to be passed.")
  274. }
  275. for _, feature := range ffr.featureFlags.Flags {
  276. pipeline.SetFeature(feature)
  277. }
  278. }
  279. // DeployItem inserts a PipelineItem into the pipeline. It also recursively creates all of it's
  280. // dependencies (PipelineItem.Requires()). Returns the same item as specified in the arguments.
  281. func (pipeline *Pipeline) DeployItem(item PipelineItem) PipelineItem {
  282. fpi, ok := item.(FeaturedPipelineItem)
  283. if ok {
  284. for _, f := range fpi.Features() {
  285. pipeline.SetFeature(f)
  286. }
  287. }
  288. queue := []PipelineItem{}
  289. queue = append(queue, item)
  290. added := map[string]PipelineItem{}
  291. for _, item := range pipeline.items {
  292. added[item.Name()] = item
  293. }
  294. added[item.Name()] = item
  295. pipeline.AddItem(item)
  296. for len(queue) > 0 {
  297. head := queue[0]
  298. queue = queue[1:]
  299. for _, dep := range head.Requires() {
  300. for _, sibling := range Registry.Summon(dep) {
  301. if _, exists := added[sibling.Name()]; !exists {
  302. disabled := false
  303. // If this item supports features, check them against the activated in pipeline.features
  304. if fpi, matches := sibling.(FeaturedPipelineItem); matches {
  305. for _, feature := range fpi.Features() {
  306. if !pipeline.features[feature] {
  307. disabled = true
  308. break
  309. }
  310. }
  311. }
  312. if disabled {
  313. continue
  314. }
  315. added[sibling.Name()] = sibling
  316. queue = append(queue, sibling)
  317. pipeline.AddItem(sibling)
  318. }
  319. }
  320. }
  321. }
  322. return item
  323. }
  324. // AddItem inserts a PipelineItem into the pipeline. It does not check any dependencies.
  325. // See also: DeployItem().
  326. func (pipeline *Pipeline) AddItem(item PipelineItem) PipelineItem {
  327. pipeline.items = append(pipeline.items, item)
  328. return item
  329. }
  330. // RemoveItem deletes a PipelineItem from the pipeline. It leaves all the rest of the items intact.
  331. func (pipeline *Pipeline) RemoveItem(item PipelineItem) {
  332. for i, reg := range pipeline.items {
  333. if reg == item {
  334. pipeline.items = append(pipeline.items[:i], pipeline.items[i+1:]...)
  335. return
  336. }
  337. }
  338. }
  339. // Len returns the number of items in the pipeline.
  340. func (pipeline *Pipeline) Len() int {
  341. return len(pipeline.items)
  342. }
  343. // Commits returns the list of commits from the history similar to `git log` over the HEAD.
  344. // `firstParent` specifies whether to leave only the first parent after each merge
  345. // (`git log --first-parent`) - effectively decreasing the accuracy but increasing performance.
  346. func (pipeline *Pipeline) Commits(firstParent bool) ([]*object.Commit, error) {
  347. var result []*object.Commit
  348. repository := pipeline.repository
  349. head, err := repository.Head()
  350. if err != nil {
  351. if err == plumbing.ErrReferenceNotFound {
  352. refs, errr := repository.References()
  353. if errr != nil {
  354. return nil, errors.Wrap(errr, "unable to list the references")
  355. }
  356. refs.ForEach(func(ref *plumbing.Reference) error {
  357. if strings.HasPrefix(ref.Name().String(), "refs/heads/HEAD/") {
  358. head = ref
  359. return storer.ErrStop
  360. }
  361. return nil
  362. })
  363. }
  364. if head == nil && err != nil {
  365. return nil, errors.Wrap(err, "unable to collect the commit history")
  366. }
  367. }
  368. if firstParent {
  369. commit, err := repository.CommitObject(head.Hash())
  370. if err != nil {
  371. panic(err)
  372. }
  373. // the first parent matches the head
  374. for ; err != io.EOF; commit, err = commit.Parents().Next() {
  375. if err != nil {
  376. panic(err)
  377. }
  378. result = append(result, commit)
  379. }
  380. // reverse the order
  381. for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
  382. result[i], result[j] = result[j], result[i]
  383. }
  384. return result, nil
  385. }
  386. cit, err := repository.Log(&git.LogOptions{From: head.Hash()})
  387. if err != nil {
  388. return nil, errors.Wrap(err, "unable to collect the commit history")
  389. }
  390. defer cit.Close()
  391. cit.ForEach(func(commit *object.Commit) error {
  392. result = append(result, commit)
  393. return nil
  394. })
  395. return result, nil
  396. }
  397. type sortablePipelineItems []PipelineItem
  398. func (items sortablePipelineItems) Len() int {
  399. return len(items)
  400. }
  401. func (items sortablePipelineItems) Less(i, j int) bool {
  402. return items[i].Name() < items[j].Name()
  403. }
  404. func (items sortablePipelineItems) Swap(i, j int) {
  405. items[i], items[j] = items[j], items[i]
  406. }
  407. func (pipeline *Pipeline) resolve(dumpPath string) {
  408. graph := toposort.NewGraph()
  409. sort.Sort(sortablePipelineItems(pipeline.items))
  410. name2item := map[string]PipelineItem{}
  411. ambiguousMap := map[string][]string{}
  412. nameUsages := map[string]int{}
  413. for _, item := range pipeline.items {
  414. nameUsages[item.Name()]++
  415. }
  416. counters := map[string]int{}
  417. for _, item := range pipeline.items {
  418. name := item.Name()
  419. if nameUsages[name] > 1 {
  420. index := counters[item.Name()] + 1
  421. counters[item.Name()] = index
  422. name = fmt.Sprintf("%s_%d", item.Name(), index)
  423. }
  424. graph.AddNode(name)
  425. name2item[name] = item
  426. for _, key := range item.Provides() {
  427. key = "[" + key + "]"
  428. graph.AddNode(key)
  429. if graph.AddEdge(name, key) > 1 {
  430. if ambiguousMap[key] != nil {
  431. fmt.Fprintln(os.Stderr, "Pipeline:")
  432. for _, item2 := range pipeline.items {
  433. if item2 == item {
  434. fmt.Fprint(os.Stderr, "> ")
  435. }
  436. fmt.Fprint(os.Stderr, item2.Name(), " [")
  437. for i, key2 := range item2.Provides() {
  438. fmt.Fprint(os.Stderr, key2)
  439. if i < len(item.Provides())-1 {
  440. fmt.Fprint(os.Stderr, ", ")
  441. }
  442. }
  443. fmt.Fprintln(os.Stderr, "]")
  444. }
  445. panic("Failed to resolve pipeline dependencies: ambiguous graph.")
  446. }
  447. ambiguousMap[key] = graph.FindParents(key)
  448. }
  449. }
  450. }
  451. counters = map[string]int{}
  452. for _, item := range pipeline.items {
  453. name := item.Name()
  454. if nameUsages[name] > 1 {
  455. index := counters[item.Name()] + 1
  456. counters[item.Name()] = index
  457. name = fmt.Sprintf("%s_%d", item.Name(), index)
  458. }
  459. for _, key := range item.Requires() {
  460. key = "[" + key + "]"
  461. if graph.AddEdge(key, name) == 0 {
  462. log.Panicf("Unsatisfied dependency: %s -> %s", key, item.Name())
  463. }
  464. }
  465. }
  466. // Try to break the cycles in some known scenarios.
  467. if len(ambiguousMap) > 0 {
  468. var ambiguous []string
  469. for key := range ambiguousMap {
  470. ambiguous = append(ambiguous, key)
  471. }
  472. sort.Strings(ambiguous)
  473. bfsorder := graph.BreadthSort()
  474. bfsindex := map[string]int{}
  475. for i, s := range bfsorder {
  476. bfsindex[s] = i
  477. }
  478. for len(ambiguous) > 0 {
  479. key := ambiguous[0]
  480. ambiguous = ambiguous[1:]
  481. pair := ambiguousMap[key]
  482. inheritor := pair[1]
  483. if bfsindex[pair[1]] < bfsindex[pair[0]] {
  484. inheritor = pair[0]
  485. }
  486. removed := graph.RemoveEdge(key, inheritor)
  487. cycle := map[string]bool{}
  488. for _, node := range graph.FindCycle(key) {
  489. cycle[node] = true
  490. }
  491. if len(cycle) == 0 {
  492. cycle[inheritor] = true
  493. }
  494. if removed {
  495. graph.AddEdge(key, inheritor)
  496. }
  497. graph.RemoveEdge(inheritor, key)
  498. graph.ReindexNode(inheritor)
  499. // for all nodes key links to except those in cycle, put the link from inheritor
  500. for _, node := range graph.FindChildren(key) {
  501. if _, exists := cycle[node]; !exists {
  502. graph.AddEdge(inheritor, node)
  503. graph.RemoveEdge(key, node)
  504. }
  505. }
  506. graph.ReindexNode(key)
  507. }
  508. }
  509. var graphCopy *toposort.Graph
  510. if dumpPath != "" {
  511. graphCopy = graph.Copy()
  512. }
  513. strplan, ok := graph.Toposort()
  514. if !ok {
  515. panic("Failed to resolve pipeline dependencies: unable to topologically sort the items.")
  516. }
  517. pipeline.items = make([]PipelineItem, 0, len(pipeline.items))
  518. for _, key := range strplan {
  519. if item, ok := name2item[key]; ok {
  520. pipeline.items = append(pipeline.items, item)
  521. }
  522. }
  523. if dumpPath != "" {
  524. // If there is a floating difference, uncomment this:
  525. // fmt.Fprint(os.Stderr, graphCopy.DebugDump())
  526. ioutil.WriteFile(dumpPath, []byte(graphCopy.Serialize(strplan)), 0666)
  527. absPath, _ := filepath.Abs(dumpPath)
  528. log.Printf("Wrote the DAG to %s\n", absPath)
  529. }
  530. }
  531. // Initialize prepares the pipeline for the execution (Run()). This function
  532. // resolves the execution DAG, Configure()-s and Initialize()-s the items in it in the
  533. // topological dependency order. `facts` are passed inside Configure(). They are mutable.
  534. func (pipeline *Pipeline) Initialize(facts map[string]interface{}) {
  535. if facts == nil {
  536. facts = map[string]interface{}{}
  537. }
  538. if _, exists := facts[ConfigPipelineCommits]; !exists {
  539. var err error
  540. facts[ConfigPipelineCommits], err = pipeline.Commits(false)
  541. if err != nil {
  542. log.Panicf("failed to list the commits: %v", err)
  543. }
  544. }
  545. dumpPath, _ := facts[ConfigPipelineDumpPath].(string)
  546. pipeline.resolve(dumpPath)
  547. if dryRun, _ := facts[ConfigPipelineDryRun].(bool); dryRun {
  548. return
  549. }
  550. for _, item := range pipeline.items {
  551. item.Configure(facts)
  552. }
  553. for _, item := range pipeline.items {
  554. item.Initialize(pipeline.repository)
  555. }
  556. }
  557. // Run method executes the pipeline.
  558. //
  559. // `commits` is a slice with the git commits to analyse. Multiple branches are supported.
  560. //
  561. // Returns the mapping from each LeafPipelineItem to the corresponding analysis result.
  562. // There is always a "nil" record with CommonAnalysisResult.
  563. func (pipeline *Pipeline) Run(commits []*object.Commit) (map[LeafPipelineItem]interface{}, error) {
  564. startRunTime := time.Now()
  565. onProgress := pipeline.OnProgress
  566. if onProgress == nil {
  567. onProgress = func(int, int) {}
  568. }
  569. plan := prepareRunPlan(commits)
  570. progressSteps := len(plan) + 2
  571. branches := map[int][]PipelineItem{}
  572. // we will need rootClone if there is more than one root branch
  573. rootClone := cloneItems(pipeline.items, 1)[0]
  574. var newestTime int64
  575. runTimePerItem := map[string]float64{}
  576. commitIndex := 0
  577. for index, step := range plan {
  578. onProgress(index + 1, progressSteps)
  579. firstItem := step.Items[0]
  580. switch step.Action {
  581. case runActionCommit:
  582. state := map[string]interface{}{
  583. DependencyCommit: step.Commit,
  584. DependencyIndex: commitIndex,
  585. DependencyIsMerge:
  586. (index > 0 &&
  587. plan[index-1].Action == runActionCommit &&
  588. plan[index-1].Commit.Hash == step.Commit.Hash) ||
  589. (index < (len(plan)-1) &&
  590. plan[index+1].Action == runActionCommit &&
  591. plan[index+1].Commit.Hash == step.Commit.Hash),
  592. }
  593. for _, item := range branches[firstItem] {
  594. startTime := time.Now()
  595. update, err := item.Consume(state)
  596. runTimePerItem[item.Name()] += time.Now().Sub(startTime).Seconds()
  597. if err != nil {
  598. log.Printf("%s failed on commit #%d (%d) %s\n",
  599. item.Name(), commitIndex + 1, index + 1, step.Commit.Hash.String())
  600. return nil, err
  601. }
  602. for _, key := range item.Provides() {
  603. val, ok := update[key]
  604. if !ok {
  605. log.Panicf("%s: Consume() did not return %s", item.Name(), key)
  606. }
  607. state[key] = val
  608. }
  609. }
  610. commitTime := step.Commit.Committer.When.Unix()
  611. if commitTime > newestTime {
  612. newestTime = commitTime
  613. }
  614. commitIndex++
  615. case runActionFork:
  616. for i, clone := range cloneItems(branches[firstItem], len(step.Items)-1) {
  617. branches[step.Items[i+1]] = clone
  618. }
  619. case runActionMerge:
  620. merged := make([][]PipelineItem, len(step.Items))
  621. for i, b := range step.Items {
  622. merged[i] = branches[b]
  623. }
  624. mergeItems(merged)
  625. case runActionEmerge:
  626. if firstItem == rootBranchIndex {
  627. branches[firstItem] = pipeline.items
  628. } else {
  629. branches[firstItem] = cloneItems(rootClone, 1)[0]
  630. }
  631. case runActionDelete:
  632. delete(branches, firstItem)
  633. }
  634. }
  635. onProgress(len(plan) + 1, progressSteps)
  636. result := map[LeafPipelineItem]interface{}{}
  637. for index, item := range getMasterBranch(branches) {
  638. if casted, ok := item.(LeafPipelineItem); ok {
  639. result[pipeline.items[index].(LeafPipelineItem)] = casted.Finalize()
  640. }
  641. }
  642. onProgress(progressSteps, progressSteps)
  643. result[nil] = &CommonAnalysisResult{
  644. BeginTime: plan[0].Commit.Committer.When.Unix(),
  645. EndTime: newestTime,
  646. CommitsNumber: len(commits),
  647. RunTime: time.Since(startRunTime),
  648. RunTimePerItem: runTimePerItem,
  649. }
  650. return result, nil
  651. }
  652. // LoadCommitsFromFile reads the file by the specified FS path and generates the sequence of commits
  653. // by interpreting each line as a Git commit hash.
  654. func LoadCommitsFromFile(path string, repository *git.Repository) ([]*object.Commit, error) {
  655. var file io.ReadCloser
  656. if path != "-" {
  657. var err error
  658. file, err = os.Open(path)
  659. if err != nil {
  660. return nil, err
  661. }
  662. defer file.Close()
  663. } else {
  664. file = os.Stdin
  665. }
  666. scanner := bufio.NewScanner(file)
  667. var commits []*object.Commit
  668. for scanner.Scan() {
  669. hash := plumbing.NewHash(scanner.Text())
  670. if len(hash) != 20 {
  671. return nil, errors.New("invalid commit hash " + scanner.Text())
  672. }
  673. commit, err := repository.CommitObject(hash)
  674. if err != nil {
  675. return nil, err
  676. }
  677. commits = append(commits, commit)
  678. }
  679. return commits, nil
  680. }