pipeline.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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 git commits to analyse. Multiple branches are supported.
  501. //
  502. // Returns the mapping from each LeafPipelineItem to the corresponding analysis result.
  503. // There is always a "nil" record with CommonAnalysisResult.
  504. func (pipeline *Pipeline) Run(commits []*object.Commit) (map[LeafPipelineItem]interface{}, error) {
  505. startRunTime := time.Now()
  506. onProgress := pipeline.OnProgress
  507. if onProgress == nil {
  508. onProgress = func(int, int) {}
  509. }
  510. for index, commit := range commits {
  511. onProgress(index, len(commits))
  512. state := map[string]interface{}{"commit": commit, "index": index}
  513. for _, item := range pipeline.items {
  514. update, err := item.Consume(state)
  515. if err != nil {
  516. log.Printf("%s failed on commit #%d %s\n",
  517. item.Name(), index, commit.Hash.String())
  518. return nil, err
  519. }
  520. for _, key := range item.Provides() {
  521. val, ok := update[key]
  522. if !ok {
  523. panic(fmt.Sprintf("%s: Consume() did not return %s", item.Name(), key))
  524. }
  525. state[key] = val
  526. }
  527. }
  528. }
  529. onProgress(len(commits), len(commits))
  530. result := map[LeafPipelineItem]interface{}{}
  531. for _, item := range pipeline.items {
  532. if casted, ok := item.(LeafPipelineItem); ok {
  533. result[casted] = casted.Finalize()
  534. }
  535. }
  536. result[nil] = &CommonAnalysisResult{
  537. BeginTime: commits[0].Author.When.Unix(),
  538. EndTime: commits[len(commits)-1].Author.When.Unix(),
  539. CommitsNumber: len(commits),
  540. RunTime: time.Since(startRunTime),
  541. }
  542. return result, nil
  543. }
  544. // LoadCommitsFromFile reads the file by the specified FS path and generates the sequence of commits
  545. // by interpreting each line as a Git commit hash.
  546. func LoadCommitsFromFile(path string, repository *git.Repository) ([]*object.Commit, error) {
  547. var file io.ReadCloser
  548. if path != "-" {
  549. var err error
  550. file, err = os.Open(path)
  551. if err != nil {
  552. return nil, err
  553. }
  554. defer file.Close()
  555. } else {
  556. file = os.Stdin
  557. }
  558. scanner := bufio.NewScanner(file)
  559. commits := []*object.Commit{}
  560. for scanner.Scan() {
  561. hash := plumbing.NewHash(scanner.Text())
  562. if len(hash) != 20 {
  563. return nil, errors.New("invalid commit hash " + scanner.Text())
  564. }
  565. commit, err := repository.CommitObject(hash)
  566. if err != nil {
  567. return nil, err
  568. }
  569. commits = append(commits, commit)
  570. }
  571. return commits, nil
  572. }
  573. const (
  574. runActionCommit = 0
  575. runActionFork = iota
  576. runActionMerge = iota
  577. )
  578. type runAction struct {
  579. Action int
  580. Commit *object.Commit
  581. Items []int
  582. }
  583. func prepareRunPlan(commits []*object.Commit) []runAction {
  584. hashes, dag := buildDag(commits)
  585. leaveRootComponent(hashes, dag)
  586. numParents := bindNumParents(hashes, dag)
  587. mergedDag, mergedSeq := mergeDag(numParents, hashes, dag)
  588. orderNodes := bindOrderNodes(mergedDag)
  589. collapseFastForwards(orderNodes, hashes, mergedDag, dag, mergedSeq)
  590. /*fmt.Printf("digraph Hercules {\n")
  591. for i, c := range order {
  592. commit := hashes[c]
  593. fmt.Printf(" \"%s\"[label=\"[%d] %s\"]\n", commit.Hash.String(), i, commit.Hash.String()[:6])
  594. for _, child := range mergedDag[commit.Hash] {
  595. fmt.Printf(" \"%s\" -> \"%s\"\n", commit.Hash.String(), child.Hash.String())
  596. }
  597. }
  598. fmt.Printf("}\n")*/
  599. plan := generatePlan(orderNodes, numParents, hashes, mergedDag, dag, mergedSeq)
  600. plan = optimizePlan(plan)
  601. return plan
  602. }
  603. // buildDag generates the raw commit DAG and the commit hash map.
  604. func buildDag(commits []*object.Commit) (
  605. map[string]*object.Commit, map[plumbing.Hash][]*object.Commit) {
  606. hashes := map[string]*object.Commit{}
  607. for _, commit := range commits {
  608. hashes[commit.Hash.String()] = commit
  609. }
  610. dag := map[plumbing.Hash][]*object.Commit{}
  611. for _, commit := range commits {
  612. if _, exists := dag[commit.Hash]; !exists {
  613. dag[commit.Hash] = make([]*object.Commit, 0, 1)
  614. }
  615. for _, parent := range commit.ParentHashes {
  616. if _, exists := hashes[parent.String()]; !exists {
  617. continue
  618. }
  619. children := dag[parent]
  620. if children == nil {
  621. children = make([]*object.Commit, 0, 1)
  622. }
  623. dag[parent] = append(children, commit)
  624. }
  625. }
  626. return hashes, dag
  627. }
  628. // bindNumParents returns curried "numParents" function.
  629. func bindNumParents(
  630. hashes map[string]*object.Commit,
  631. dag map[plumbing.Hash][]*object.Commit) func(c *object.Commit) int {
  632. return func(c *object.Commit) int {
  633. r := 0
  634. for _, parent := range c.ParentHashes {
  635. if p, exists := hashes[parent.String()]; exists {
  636. for _, pc := range dag[p.Hash] {
  637. if pc.Hash == c.Hash {
  638. r++
  639. break
  640. }
  641. }
  642. }
  643. }
  644. return r
  645. }
  646. }
  647. // leaveRootComponent runs connected components analysis and throws away everything
  648. // but the part which grows from the root.
  649. func leaveRootComponent(
  650. hashes map[string]*object.Commit,
  651. dag map[plumbing.Hash][]*object.Commit) {
  652. visited := map[plumbing.Hash]bool{}
  653. var sets [][]plumbing.Hash
  654. for key := range dag {
  655. if visited[key] {
  656. continue
  657. }
  658. var set []plumbing.Hash
  659. for queue := []plumbing.Hash{key}; len(queue) > 0; {
  660. head := queue[len(queue)-1]
  661. queue = queue[:len(queue)-1]
  662. if visited[head] {
  663. continue
  664. }
  665. set = append(set, head)
  666. visited[head] = true
  667. for _, c := range dag[head] {
  668. if !visited[c.Hash] {
  669. queue = append(queue, c.Hash)
  670. }
  671. }
  672. if commit, exists := hashes[head.String()]; exists {
  673. for _, p := range commit.ParentHashes {
  674. if !visited[p] {
  675. if _, exists := hashes[p.String()]; exists {
  676. queue = append(queue, p)
  677. }
  678. }
  679. }
  680. }
  681. }
  682. sets = append(sets, set)
  683. }
  684. if len(sets) > 1 {
  685. maxlen := 0
  686. maxind := -1
  687. for i, set := range sets {
  688. if len(set) > maxlen {
  689. maxlen = len(set)
  690. maxind = i
  691. }
  692. }
  693. for i, set := range sets {
  694. if i == maxind {
  695. continue
  696. }
  697. for _, h := range set {
  698. log.Printf("warning: dropped %s from the analysis - disjoint", h.String())
  699. delete(dag, h)
  700. delete(hashes, h.String())
  701. }
  702. }
  703. }
  704. }
  705. // bindOrderNodes returns curried "orderNodes" function.
  706. func bindOrderNodes(mergedDag map[plumbing.Hash][]*object.Commit) func(reverse bool) []string {
  707. return func(reverse bool) []string {
  708. graph := toposort.NewGraph()
  709. keys := make([]plumbing.Hash, 0, len(mergedDag))
  710. for key := range mergedDag {
  711. keys = append(keys, key)
  712. }
  713. sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
  714. for _, key := range keys {
  715. graph.AddNode(key.String())
  716. }
  717. for _, key := range keys {
  718. children := mergedDag[key]
  719. sort.Slice(children, func(i, j int) bool {
  720. return children[i].Hash.String() < children[j].Hash.String()
  721. })
  722. for _, c := range children {
  723. graph.AddEdge(key.String(), c.Hash.String())
  724. }
  725. }
  726. order, ok := graph.Toposort()
  727. if !ok {
  728. // should never happen
  729. panic("Could not topologically sort the DAG of commits")
  730. }
  731. if reverse {
  732. // one day this must appear in the standard library...
  733. for i, j := 0, len(order)-1; i < len(order)/2; i, j = i+1, j-1 {
  734. order[i], order[j] = order[j], order[i]
  735. }
  736. }
  737. return order
  738. }
  739. }
  740. // mergeDag turns sequences of consecutive commits into single nodes.
  741. func mergeDag(
  742. numParents func(c *object.Commit) int,
  743. hashes map[string]*object.Commit,
  744. dag map[plumbing.Hash][]*object.Commit) (
  745. mergedDag, mergedSeq map[plumbing.Hash][]*object.Commit) {
  746. parentOf := func(c *object.Commit) plumbing.Hash {
  747. var parent plumbing.Hash
  748. for _, p := range c.ParentHashes {
  749. if _, exists := hashes[p.String()]; exists {
  750. if parent != plumbing.ZeroHash {
  751. // more than one parent
  752. return plumbing.ZeroHash
  753. }
  754. parent = p
  755. }
  756. }
  757. return parent
  758. }
  759. mergedDag = map[plumbing.Hash][]*object.Commit{}
  760. mergedSeq = map[plumbing.Hash][]*object.Commit{}
  761. visited := map[plumbing.Hash]bool{}
  762. for ch := range dag {
  763. c := hashes[ch.String()]
  764. if visited[c.Hash] {
  765. continue
  766. }
  767. for true {
  768. parent := parentOf(c)
  769. if parent == plumbing.ZeroHash || len(dag[parent]) != 1 {
  770. break
  771. }
  772. c = hashes[parent.String()]
  773. }
  774. head := c
  775. var seq []*object.Commit
  776. children := dag[c.Hash]
  777. for true {
  778. visited[c.Hash] = true
  779. seq = append(seq, c)
  780. if len(children) != 1 {
  781. break
  782. }
  783. c = children[0]
  784. children = dag[c.Hash]
  785. if numParents(c) != 1 {
  786. break
  787. }
  788. }
  789. mergedSeq[head.Hash] = seq
  790. mergedDag[head.Hash] = dag[seq[len(seq)-1].Hash]
  791. }
  792. return
  793. }
  794. // collapseFastForwards removes the fast forward merges.
  795. func collapseFastForwards(
  796. orderNodes func(reverse bool) []string,
  797. hashes map[string]*object.Commit,
  798. mergedDag, dag, mergedSeq map[plumbing.Hash][]*object.Commit) {
  799. for _, strkey := range orderNodes(true) {
  800. key := hashes[strkey].Hash
  801. vals, exists := mergedDag[key]
  802. if !exists {
  803. continue
  804. }
  805. if len(vals) == 2 {
  806. grand1 := mergedDag[vals[0].Hash]
  807. grand2 := mergedDag[vals[1].Hash]
  808. if len(grand2) == 1 && vals[0].Hash == grand2[0].Hash {
  809. mergedDag[key] = mergedDag[vals[0].Hash]
  810. dag[key] = vals[1:]
  811. delete(mergedDag, vals[0].Hash)
  812. delete(mergedDag, vals[1].Hash)
  813. mergedSeq[key] = append(mergedSeq[key], mergedSeq[vals[1].Hash]...)
  814. mergedSeq[key] = append(mergedSeq[key], mergedSeq[vals[0].Hash]...)
  815. delete(mergedSeq, vals[0].Hash)
  816. delete(mergedSeq, vals[1].Hash)
  817. }
  818. // symmetric
  819. if len(grand1) == 1 && vals[1].Hash == grand1[0].Hash {
  820. mergedDag[key] = mergedDag[vals[1].Hash]
  821. dag[key] = vals[:1]
  822. delete(mergedDag, vals[0].Hash)
  823. delete(mergedDag, vals[1].Hash)
  824. mergedSeq[key] = append(mergedSeq[key], mergedSeq[vals[0].Hash]...)
  825. mergedSeq[key] = append(mergedSeq[key], mergedSeq[vals[1].Hash]...)
  826. delete(mergedSeq, vals[0].Hash)
  827. delete(mergedSeq, vals[1].Hash)
  828. }
  829. }
  830. }
  831. }
  832. // generatePlan creates the list of actions from the commit DAG.
  833. func generatePlan(
  834. orderNodes func(reverse bool) []string,
  835. numParents func(c *object.Commit) int,
  836. hashes map[string]*object.Commit,
  837. mergedDag, dag, mergedSeq map[plumbing.Hash][]*object.Commit) []runAction {
  838. var plan []runAction
  839. branches := map[plumbing.Hash]int{}
  840. counter := 1
  841. for seqIndex, name := range orderNodes(false) {
  842. commit := hashes[name]
  843. if seqIndex == 0 {
  844. branches[commit.Hash] = 0
  845. }
  846. var branch int
  847. {
  848. var exists bool
  849. branch, exists = branches[commit.Hash]
  850. if !exists {
  851. branch = -1
  852. }
  853. }
  854. branchExists := func() bool { return branch >= 0 }
  855. appendCommit := func(c *object.Commit, branch int) {
  856. plan = append(plan, runAction{
  857. Action: runActionCommit,
  858. Commit: c,
  859. Items: []int{branch},
  860. })
  861. }
  862. appendMergeIfNeeded := func() {
  863. if numParents(commit) < 2 {
  864. return
  865. }
  866. // merge after the merge commit (the first in the sequence)
  867. var items []int
  868. minBranch := 1 << 31
  869. for _, parent := range commit.ParentHashes {
  870. if _, exists := hashes[parent.String()]; exists {
  871. parentBranch := branches[parent]
  872. if len(dag[parent]) == 1 && minBranch > parentBranch {
  873. minBranch = parentBranch
  874. }
  875. items = append(items, parentBranch)
  876. if parentBranch != branch {
  877. appendCommit(commit, parentBranch)
  878. }
  879. }
  880. }
  881. if minBranch < 1 << 31 {
  882. branch = minBranch
  883. branches[commit.Hash] = minBranch
  884. } else if !branchExists() {
  885. panic("!branchExists()")
  886. }
  887. plan = append(plan, runAction{
  888. Action: runActionMerge,
  889. Commit: nil,
  890. Items: items,
  891. })
  892. }
  893. if subseq, exists := mergedSeq[commit.Hash]; exists {
  894. for subseqIndex, offspring := range subseq {
  895. if branchExists() {
  896. appendCommit(offspring, branch)
  897. }
  898. if subseqIndex == 0 {
  899. appendMergeIfNeeded()
  900. }
  901. }
  902. branches[subseq[len(subseq)-1].Hash] = branch
  903. }
  904. if len(mergedDag[commit.Hash]) > 1 {
  905. branches[mergedDag[commit.Hash][0].Hash] = branch
  906. children := []int{branch}
  907. for i, child := range mergedDag[commit.Hash] {
  908. if i > 0 {
  909. branches[child.Hash] = counter
  910. children = append(children, counter)
  911. counter++
  912. }
  913. }
  914. plan = append(plan, runAction{
  915. Action: runActionFork,
  916. Commit: nil,
  917. Items: children,
  918. })
  919. }
  920. }
  921. return plan
  922. }
  923. // optimizePlan removes "dead" nodes.
  924. //
  925. // | *
  926. // * /
  927. // |\/
  928. // |/
  929. // *
  930. //
  931. func optimizePlan(plan []runAction) []runAction {
  932. lives := map[int][]int{}
  933. for i, p := range plan {
  934. if p.Action == runActionCommit {
  935. lives[p.Items[0]] = append(lives[p.Items[0]], i)
  936. }
  937. }
  938. branchesToDelete := map[int]bool{}
  939. for key, life := range lives {
  940. if len(life) == 1 {
  941. branchesToDelete[key] = true
  942. }
  943. }
  944. if len(branchesToDelete) == 0 {
  945. return plan
  946. }
  947. var optimizedPlan []runAction
  948. for _, p := range plan {
  949. switch p.Action {
  950. case runActionCommit:
  951. if !branchesToDelete[p.Items[0]] {
  952. optimizedPlan = append(optimizedPlan, p)
  953. }
  954. case runActionFork:
  955. var newBranches []int
  956. for _, b := range p.Items {
  957. if !branchesToDelete[b] {
  958. newBranches = append(newBranches, b)
  959. }
  960. }
  961. if len(newBranches) > 1 {
  962. optimizedPlan = append(optimizedPlan, runAction{
  963. Action: runActionFork,
  964. Commit: p.Commit,
  965. Items: newBranches,
  966. })
  967. }
  968. case runActionMerge:
  969. var newBranches []int
  970. for _, b := range p.Items {
  971. if !branchesToDelete[b] {
  972. newBranches = append(newBranches, b)
  973. }
  974. }
  975. if len(newBranches) > 1 {
  976. optimizedPlan = append(optimizedPlan, runAction{
  977. Action: runActionMerge,
  978. Commit: p.Commit,
  979. Items: newBranches,
  980. })
  981. }
  982. }
  983. }
  984. // single commit can be detected as redundant
  985. if len(optimizedPlan) > 0 {
  986. return optimizedPlan
  987. }
  988. return plan
  989. // TODO(vmarkovtsev): there can be also duplicate redundant merges, e.g.
  990. /*
  991. 0 4e34f03d829fbacb71cde0e010de87ea945dc69a [3]
  992. 0 4e34f03d829fbacb71cde0e010de87ea945dc69a [12]
  993. 2 [3 12]
  994. 0 06716c2b39422938b77ddafa4d5c39bb9e4476da [3]
  995. 0 06716c2b39422938b77ddafa4d5c39bb9e4476da [12]
  996. 2 [3 12]
  997. 0 1219c7bf9e0e1a93459a052ab8b351bfc379dc19 [12]
  998. */
  999. }