pipeline.go 19 KB

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