pipeline.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. // "commit" and "index".
  95. // Returns the calculated entities which match Provides().
  96. Consume(deps map[string]interface{}) (map[string]interface{}, error)
  97. }
  98. // FeaturedPipelineItem enables switching the automatic insertion of pipeline items on or off.
  99. type FeaturedPipelineItem interface {
  100. PipelineItem
  101. // Features returns the list of names which enable this item to be automatically inserted
  102. // in Pipeline.DeployItem().
  103. Features() []string
  104. }
  105. // LeafPipelineItem corresponds to the top level pipeline items which produce the end results.
  106. type LeafPipelineItem interface {
  107. PipelineItem
  108. // Flag returns the cmdline name of the item.
  109. Flag() string
  110. // Finalize returns the result of the analysis.
  111. Finalize() interface{}
  112. // Serialize encodes the object returned by Finalize() to YAML or Protocol Buffers.
  113. Serialize(result interface{}, binary bool, writer io.Writer) error
  114. }
  115. // MergeablePipelineItem specifies the methods to combine several analysis results together.
  116. type MergeablePipelineItem interface {
  117. LeafPipelineItem
  118. // Deserialize loads the result from Protocol Buffers blob.
  119. Deserialize(pbmessage []byte) (interface{}, error)
  120. // MergeResults joins two results together. Common-s are specified as the global state.
  121. MergeResults(r1, r2 interface{}, c1, c2 *CommonAnalysisResult) interface{}
  122. }
  123. // CommonAnalysisResult holds the information which is always extracted at Pipeline.Run().
  124. type CommonAnalysisResult struct {
  125. // Time of the first commit in the analysed sequence.
  126. BeginTime int64
  127. // Time of the last commit in the analysed sequence.
  128. EndTime int64
  129. // The number of commits in the analysed sequence.
  130. CommitsNumber int
  131. // The duration of Pipeline.Run().
  132. RunTime time.Duration
  133. }
  134. // BeginTimeAsTime converts the UNIX timestamp of the beginning to Go time.
  135. func (car *CommonAnalysisResult) BeginTimeAsTime() time.Time {
  136. return time.Unix(car.BeginTime, 0)
  137. }
  138. // EndTimeAsTime converts the UNIX timestamp of the ending to Go time.
  139. func (car *CommonAnalysisResult) EndTimeAsTime() time.Time {
  140. return time.Unix(car.EndTime, 0)
  141. }
  142. // Merge combines the CommonAnalysisResult with an other one.
  143. // We choose the earlier BeginTime, the later EndTime, sum the number of commits and the
  144. // elapsed run times.
  145. func (car *CommonAnalysisResult) Merge(other *CommonAnalysisResult) {
  146. if car.EndTime == 0 || other.BeginTime == 0 {
  147. panic("Merging with an uninitialized CommonAnalysisResult")
  148. }
  149. if other.BeginTime < car.BeginTime {
  150. car.BeginTime = other.BeginTime
  151. }
  152. if other.EndTime > car.EndTime {
  153. car.EndTime = other.EndTime
  154. }
  155. car.CommitsNumber += other.CommitsNumber
  156. car.RunTime += other.RunTime
  157. }
  158. // FillMetadata copies the data to a Protobuf message.
  159. func (car *CommonAnalysisResult) FillMetadata(meta *pb.Metadata) *pb.Metadata {
  160. meta.BeginUnixTime = car.BeginTime
  161. meta.EndUnixTime = car.EndTime
  162. meta.Commits = int32(car.CommitsNumber)
  163. meta.RunTime = car.RunTime.Nanoseconds() / 1e6
  164. return meta
  165. }
  166. // Metadata is defined in internal/pb/pb.pb.go - header of the binary file.
  167. type Metadata = pb.Metadata
  168. // MetadataToCommonAnalysisResult copies the data from a Protobuf message.
  169. func MetadataToCommonAnalysisResult(meta *Metadata) *CommonAnalysisResult {
  170. return &CommonAnalysisResult{
  171. BeginTime: meta.BeginUnixTime,
  172. EndTime: meta.EndUnixTime,
  173. CommitsNumber: int(meta.Commits),
  174. RunTime: time.Duration(meta.RunTime * 1e6),
  175. }
  176. }
  177. // Pipeline is the core Hercules entity which carries several PipelineItems and executes them.
  178. // See the extended example of how a Pipeline works in doc.go
  179. type Pipeline struct {
  180. // OnProgress is the callback which is invoked in Analyse() to output it's
  181. // progress. The first argument is the number of processed commits and the
  182. // second is the total number of commits.
  183. OnProgress func(int, int)
  184. // Repository points to the analysed Git repository struct from go-git.
  185. repository *git.Repository
  186. // Items are the registered building blocks in the pipeline. The order defines the
  187. // execution sequence.
  188. items []PipelineItem
  189. // The collection of parameters to create items.
  190. facts map[string]interface{}
  191. // Feature flags which enable the corresponding items.
  192. features map[string]bool
  193. }
  194. const (
  195. // ConfigPipelineDumpPath is the name of the Pipeline configuration option (Pipeline.Initialize())
  196. // which enables saving the items DAG to the specified file.
  197. ConfigPipelineDumpPath = "Pipeline.DumpPath"
  198. // ConfigPipelineDryRun is the name of the Pipeline configuration option (Pipeline.Initialize())
  199. // which disables Configure() and Initialize() invocation on each PipelineItem during the
  200. // Pipeline initialization.
  201. // Subsequent Run() calls are going to fail. Useful with ConfigPipelineDumpPath=true.
  202. ConfigPipelineDryRun = "Pipeline.DryRun"
  203. // ConfigPipelineCommits is the name of the Pipeline configuration option (Pipeline.Initialize())
  204. // which allows to specify the custom commit sequence. By default, Pipeline.Commits() is used.
  205. ConfigPipelineCommits = "commits"
  206. )
  207. // NewPipeline initializes a new instance of Pipeline struct.
  208. func NewPipeline(repository *git.Repository) *Pipeline {
  209. return &Pipeline{
  210. repository: repository,
  211. items: []PipelineItem{},
  212. facts: map[string]interface{}{},
  213. features: map[string]bool{},
  214. }
  215. }
  216. // GetFact returns the value of the fact with the specified name.
  217. func (pipeline *Pipeline) GetFact(name string) interface{} {
  218. return pipeline.facts[name]
  219. }
  220. // SetFact sets the value of the fact with the specified name.
  221. func (pipeline *Pipeline) SetFact(name string, value interface{}) {
  222. pipeline.facts[name] = value
  223. }
  224. // GetFeature returns the state of the feature with the specified name (enabled/disabled) and
  225. // whether it exists. See also: FeaturedPipelineItem.
  226. func (pipeline *Pipeline) GetFeature(name string) (bool, bool) {
  227. val, exists := pipeline.features[name]
  228. return val, exists
  229. }
  230. // SetFeature sets the value of the feature with the specified name.
  231. // See also: FeaturedPipelineItem.
  232. func (pipeline *Pipeline) SetFeature(name string) {
  233. pipeline.features[name] = true
  234. }
  235. // SetFeaturesFromFlags enables the features which were specified through the command line flags
  236. // which belong to the given PipelineItemRegistry instance.
  237. // See also: AddItem().
  238. func (pipeline *Pipeline) SetFeaturesFromFlags(registry ...*PipelineItemRegistry) {
  239. var ffr *PipelineItemRegistry
  240. if len(registry) == 0 {
  241. ffr = Registry
  242. } else if len(registry) == 1 {
  243. ffr = registry[0]
  244. } else {
  245. panic("Zero or one registry is allowed to be passed.")
  246. }
  247. for _, feature := range ffr.featureFlags.Flags {
  248. pipeline.SetFeature(feature)
  249. }
  250. }
  251. // DeployItem inserts a PipelineItem into the pipeline. It also recursively creates all of it's
  252. // dependencies (PipelineItem.Requires()). Returns the same item as specified in the arguments.
  253. func (pipeline *Pipeline) DeployItem(item PipelineItem) PipelineItem {
  254. fpi, ok := item.(FeaturedPipelineItem)
  255. if ok {
  256. for _, f := range fpi.Features() {
  257. pipeline.SetFeature(f)
  258. }
  259. }
  260. queue := []PipelineItem{}
  261. queue = append(queue, item)
  262. added := map[string]PipelineItem{}
  263. for _, item := range pipeline.items {
  264. added[item.Name()] = item
  265. }
  266. added[item.Name()] = item
  267. pipeline.AddItem(item)
  268. for len(queue) > 0 {
  269. head := queue[0]
  270. queue = queue[1:]
  271. for _, dep := range head.Requires() {
  272. for _, sibling := range Registry.Summon(dep) {
  273. if _, exists := added[sibling.Name()]; !exists {
  274. disabled := false
  275. // If this item supports features, check them against the activated in pipeline.features
  276. if fpi, matches := sibling.(FeaturedPipelineItem); matches {
  277. for _, feature := range fpi.Features() {
  278. if !pipeline.features[feature] {
  279. disabled = true
  280. break
  281. }
  282. }
  283. }
  284. if disabled {
  285. continue
  286. }
  287. added[sibling.Name()] = sibling
  288. queue = append(queue, sibling)
  289. pipeline.AddItem(sibling)
  290. }
  291. }
  292. }
  293. }
  294. return item
  295. }
  296. // AddItem inserts a PipelineItem into the pipeline. It does not check any dependencies.
  297. // See also: DeployItem().
  298. func (pipeline *Pipeline) AddItem(item PipelineItem) PipelineItem {
  299. pipeline.items = append(pipeline.items, item)
  300. return item
  301. }
  302. // RemoveItem deletes a PipelineItem from the pipeline. It leaves all the rest of the items intact.
  303. func (pipeline *Pipeline) RemoveItem(item PipelineItem) {
  304. for i, reg := range pipeline.items {
  305. if reg == item {
  306. pipeline.items = append(pipeline.items[:i], pipeline.items[i+1:]...)
  307. return
  308. }
  309. }
  310. }
  311. // Len returns the number of items in the pipeline.
  312. func (pipeline *Pipeline) Len() int {
  313. return len(pipeline.items)
  314. }
  315. // Commits returns the critical path in the repository's history. It starts
  316. // from HEAD and traces commits backwards till the root. When it encounters
  317. // a merge (more than one parent), it always chooses the first parent.
  318. func (pipeline *Pipeline) Commits() []*object.Commit {
  319. result := []*object.Commit{}
  320. repository := pipeline.repository
  321. head, err := repository.Head()
  322. if err != nil {
  323. panic(err)
  324. }
  325. commit, err := repository.CommitObject(head.Hash())
  326. if err != nil {
  327. panic(err)
  328. }
  329. // the first parent matches the head
  330. for ; err != io.EOF; commit, err = commit.Parents().Next() {
  331. if err != nil {
  332. panic(err)
  333. }
  334. result = append(result, commit)
  335. }
  336. // reverse the order
  337. for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
  338. result[i], result[j] = result[j], result[i]
  339. }
  340. return result
  341. }
  342. type sortablePipelineItems []PipelineItem
  343. func (items sortablePipelineItems) Len() int {
  344. return len(items)
  345. }
  346. func (items sortablePipelineItems) Less(i, j int) bool {
  347. return items[i].Name() < items[j].Name()
  348. }
  349. func (items sortablePipelineItems) Swap(i, j int) {
  350. items[i], items[j] = items[j], items[i]
  351. }
  352. func (pipeline *Pipeline) resolve(dumpPath string) {
  353. graph := toposort.NewGraph()
  354. sort.Sort(sortablePipelineItems(pipeline.items))
  355. name2item := map[string]PipelineItem{}
  356. ambiguousMap := map[string][]string{}
  357. nameUsages := map[string]int{}
  358. for _, item := range pipeline.items {
  359. nameUsages[item.Name()]++
  360. }
  361. counters := map[string]int{}
  362. for _, item := range pipeline.items {
  363. name := item.Name()
  364. if nameUsages[name] > 1 {
  365. index := counters[item.Name()] + 1
  366. counters[item.Name()] = index
  367. name = fmt.Sprintf("%s_%d", item.Name(), index)
  368. }
  369. graph.AddNode(name)
  370. name2item[name] = item
  371. for _, key := range item.Provides() {
  372. key = "[" + key + "]"
  373. graph.AddNode(key)
  374. if graph.AddEdge(name, key) > 1 {
  375. if ambiguousMap[key] != nil {
  376. fmt.Fprintln(os.Stderr, "Pipeline:")
  377. for _, item2 := range pipeline.items {
  378. if item2 == item {
  379. fmt.Fprint(os.Stderr, "> ")
  380. }
  381. fmt.Fprint(os.Stderr, item2.Name(), " [")
  382. for i, key2 := range item2.Provides() {
  383. fmt.Fprint(os.Stderr, key2)
  384. if i < len(item.Provides())-1 {
  385. fmt.Fprint(os.Stderr, ", ")
  386. }
  387. }
  388. fmt.Fprintln(os.Stderr, "]")
  389. }
  390. panic("Failed to resolve pipeline dependencies: ambiguous graph.")
  391. }
  392. ambiguousMap[key] = graph.FindParents(key)
  393. }
  394. }
  395. }
  396. counters = map[string]int{}
  397. for _, item := range pipeline.items {
  398. name := item.Name()
  399. if nameUsages[name] > 1 {
  400. index := counters[item.Name()] + 1
  401. counters[item.Name()] = index
  402. name = fmt.Sprintf("%s_%d", item.Name(), index)
  403. }
  404. for _, key := range item.Requires() {
  405. key = "[" + key + "]"
  406. if graph.AddEdge(key, name) == 0 {
  407. panic(fmt.Sprintf("Unsatisfied dependency: %s -> %s", key, item.Name()))
  408. }
  409. }
  410. }
  411. // Try to break the cycles in some known scenarios.
  412. if len(ambiguousMap) > 0 {
  413. ambiguous := []string{}
  414. for key := range ambiguousMap {
  415. ambiguous = append(ambiguous, key)
  416. }
  417. sort.Strings(ambiguous)
  418. bfsorder := graph.BreadthSort()
  419. bfsindex := map[string]int{}
  420. for i, s := range bfsorder {
  421. bfsindex[s] = i
  422. }
  423. for len(ambiguous) > 0 {
  424. key := ambiguous[0]
  425. ambiguous = ambiguous[1:]
  426. pair := ambiguousMap[key]
  427. inheritor := pair[1]
  428. if bfsindex[pair[1]] < bfsindex[pair[0]] {
  429. inheritor = pair[0]
  430. }
  431. removed := graph.RemoveEdge(key, inheritor)
  432. cycle := map[string]bool{}
  433. for _, node := range graph.FindCycle(key) {
  434. cycle[node] = true
  435. }
  436. if len(cycle) == 0 {
  437. cycle[inheritor] = true
  438. }
  439. if removed {
  440. graph.AddEdge(key, inheritor)
  441. }
  442. graph.RemoveEdge(inheritor, key)
  443. graph.ReindexNode(inheritor)
  444. // for all nodes key links to except those in cycle, put the link from inheritor
  445. for _, node := range graph.FindChildren(key) {
  446. if _, exists := cycle[node]; !exists {
  447. graph.AddEdge(inheritor, node)
  448. graph.RemoveEdge(key, node)
  449. }
  450. }
  451. graph.ReindexNode(key)
  452. }
  453. }
  454. var graphCopy *toposort.Graph
  455. if dumpPath != "" {
  456. graphCopy = graph.Copy()
  457. }
  458. strplan, ok := graph.Toposort()
  459. if !ok {
  460. panic("Failed to resolve pipeline dependencies: unable to topologically sort the items.")
  461. }
  462. pipeline.items = make([]PipelineItem, 0, len(pipeline.items))
  463. for _, key := range strplan {
  464. if item, ok := name2item[key]; ok {
  465. pipeline.items = append(pipeline.items, item)
  466. }
  467. }
  468. if dumpPath != "" {
  469. // If there is a floating difference, uncomment this:
  470. // fmt.Fprint(os.Stderr, graphCopy.DebugDump())
  471. ioutil.WriteFile(dumpPath, []byte(graphCopy.Serialize(strplan)), 0666)
  472. absPath, _ := filepath.Abs(dumpPath)
  473. log.Printf("Wrote the DAG to %s\n", absPath)
  474. }
  475. }
  476. // Initialize prepares the pipeline for the execution (Run()). This function
  477. // resolves the execution DAG, Configure()-s and Initialize()-s the items in it in the
  478. // topological dependency order. `facts` are passed inside Configure(). They are mutable.
  479. func (pipeline *Pipeline) Initialize(facts map[string]interface{}) {
  480. if facts == nil {
  481. facts = map[string]interface{}{}
  482. }
  483. if _, exists := facts[ConfigPipelineCommits]; !exists {
  484. facts[ConfigPipelineCommits] = pipeline.Commits()
  485. }
  486. dumpPath, _ := facts[ConfigPipelineDumpPath].(string)
  487. pipeline.resolve(dumpPath)
  488. if dryRun, _ := facts[ConfigPipelineDryRun].(bool); dryRun {
  489. return
  490. }
  491. for _, item := range pipeline.items {
  492. item.Configure(facts)
  493. }
  494. for _, item := range pipeline.items {
  495. item.Initialize(pipeline.repository)
  496. }
  497. }
  498. // Run method executes the pipeline.
  499. //
  500. // commits is a slice with the sequential commit history. It shall start from
  501. // the root (ascending order).
  502. //
  503. // Returns the mapping from each LeafPipelineItem to the corresponding analysis result.
  504. // There is always a "nil" record with CommonAnalysisResult.
  505. func (pipeline *Pipeline) Run(commits []*object.Commit) (map[LeafPipelineItem]interface{}, error) {
  506. startRunTime := time.Now()
  507. onProgress := pipeline.OnProgress
  508. if onProgress == nil {
  509. onProgress = func(int, int) {}
  510. }
  511. for index, commit := range commits {
  512. onProgress(index, len(commits))
  513. state := map[string]interface{}{"commit": commit, "index": index}
  514. for _, item := range pipeline.items {
  515. update, err := item.Consume(state)
  516. if err != nil {
  517. log.Printf("%s failed on commit #%d %s\n",
  518. item.Name(), index, commit.Hash.String())
  519. return nil, err
  520. }
  521. for _, key := range item.Provides() {
  522. val, ok := update[key]
  523. if !ok {
  524. panic(fmt.Sprintf("%s: Consume() did not return %s", item.Name(), key))
  525. }
  526. state[key] = val
  527. }
  528. }
  529. }
  530. onProgress(len(commits), len(commits))
  531. result := map[LeafPipelineItem]interface{}{}
  532. for _, item := range pipeline.items {
  533. if casted, ok := item.(LeafPipelineItem); ok {
  534. result[casted] = casted.Finalize()
  535. }
  536. }
  537. result[nil] = &CommonAnalysisResult{
  538. BeginTime: commits[0].Author.When.Unix(),
  539. EndTime: commits[len(commits)-1].Author.When.Unix(),
  540. CommitsNumber: len(commits),
  541. RunTime: time.Since(startRunTime),
  542. }
  543. return result, nil
  544. }
  545. // LoadCommitsFromFile reads the file by the specified FS path and generates the sequence of commits
  546. // by interpreting each line as a Git commit hash.
  547. func LoadCommitsFromFile(path string, repository *git.Repository) ([]*object.Commit, error) {
  548. var file io.ReadCloser
  549. if path != "-" {
  550. var err error
  551. file, err = os.Open(path)
  552. if err != nil {
  553. return nil, err
  554. }
  555. defer file.Close()
  556. } else {
  557. file = os.Stdin
  558. }
  559. scanner := bufio.NewScanner(file)
  560. commits := []*object.Commit{}
  561. for scanner.Scan() {
  562. hash := plumbing.NewHash(scanner.Text())
  563. if len(hash) != 20 {
  564. return nil, errors.New("invalid commit hash " + scanner.Text())
  565. }
  566. commit, err := repository.CommitObject(hash)
  567. if err != nil {
  568. return nil, err
  569. }
  570. commits = append(commits, commit)
  571. }
  572. return commits, nil
  573. }