github.com/StackExchange/blackbox/v2@v2.0.1-0.20220331193400-d84e904973ab/pkg/commitlater/commitlater.go (about) 1 package commitlater 2 3 import ( 4 "fmt" 5 ) 6 7 type future struct { 8 message string // Message that describes this transaction. 9 dir string // Basedir of the files 10 files []string // Names of the files 11 display []string // Names as to be displayed to the user 12 } 13 14 // List of futures to be done in the future. 15 type List struct { 16 items []*future 17 } 18 19 // Add queues up a future commit. 20 func (list *List) Add(message string, repobasedir string, files []string) { 21 item := &future{ 22 message: message, 23 dir: repobasedir, 24 files: files, 25 } 26 list.items = append(list.items, item) 27 } 28 29 func sameDirs(l *List) bool { 30 if len(l.items) <= 1 { 31 return true 32 } 33 for _, k := range l.items[1:] { 34 if k.dir != l.items[0].dir { 35 return false 36 } 37 } 38 return true 39 } 40 41 // Flush executes queued commits. 42 func (list *List) Flush( 43 title string, 44 fadd func([]string) error, 45 fcommit func([]string, string, []string) error, 46 ) error { 47 48 // Just list the individual commit commands. 49 if title == "" || len(list.items) < 2 || !sameDirs(list) { 50 for _, fut := range list.items { 51 err := fadd(fut.files) 52 if err != nil { 53 return fmt.Errorf("add files1 (%q) failed: %w", fut.files, err) 54 } 55 err = fcommit([]string{fut.message}, fut.dir, fut.files) 56 if err != nil { 57 return fmt.Errorf("commit files (%q) failed: %w", fut.files, err) 58 } 59 } 60 return nil 61 } 62 63 // Create a long commit message. 64 var m []string 65 var f []string 66 for _, fut := range list.items { 67 err := fadd(fut.files) 68 if err != nil { 69 return fmt.Errorf("add files2 (%q) failed: %w", fut.files, err) 70 } 71 m = append(m, fut.message) 72 f = append(f, fut.files...) 73 } 74 msg := []string{title} 75 for _, mm := range m { 76 msg = append(msg, " * "+mm) 77 } 78 err := fcommit(msg, list.items[0].dir, f) 79 if err != nil { 80 return fmt.Errorf("commit files (%q) failed: %w", f, err) 81 } 82 83 return nil 84 }