pipeline.go 21 KB

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