1package commands
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "sync"
8 "time"
9
10 "github.com/spf13/cobra"
11
12 "github.com/MichaelMure/git-bug/bridge"
13 "github.com/MichaelMure/git-bug/bridge/core"
14 "github.com/MichaelMure/git-bug/cache"
15 "github.com/MichaelMure/git-bug/util/interrupt"
16)
17
18func runBridgePull(cmd *cobra.Command, args []string) error {
19 backend, err := cache.NewRepoCache(repo)
20 if err != nil {
21 return err
22 }
23 defer backend.Close()
24 interrupt.RegisterCleaner(backend.Close)
25
26 var b *core.Bridge
27
28 if len(args) == 0 {
29 b, err = bridge.DefaultBridge(backend)
30 } else {
31 b, err = bridge.LoadBridge(backend, args[0])
32 }
33
34 if err != nil {
35 return err
36 }
37
38 parentCtx := context.Background()
39 ctx, cancel := context.WithCancel(parentCtx)
40 defer cancel()
41
42 // buffered channel to avoid send block at the end
43 done := make(chan struct{}, 1)
44
45 var mu sync.Mutex
46 interruptCount := 0
47 interrupt.RegisterCleaner(func() error {
48 mu.Lock()
49 if interruptCount > 0 {
50 fmt.Println("Received another interrupt before graceful stop, terminating...")
51 os.Exit(0)
52 }
53
54 interruptCount++
55 mu.Unlock()
56
57 fmt.Println("Received interrupt signal, stopping the import...\n(Hit ctrl-c again to kill the process.)")
58
59 // send signal to stop the importer
60 cancel()
61
62 // block until importer gracefully shutdown
63 <-done
64 return nil
65 })
66
67 // TODO: by default import only new events
68 events, err := b.ImportAll(ctx, time.Time{})
69 if err != nil {
70 return err
71 }
72
73 importedIssues := 0
74 importedIdentities := 0
75 for result := range events {
76 if result.Event != core.ImportEventNothing {
77 fmt.Println(result.String())
78 }
79
80 switch result.Event {
81 case core.ImportEventBug:
82 importedIssues++
83 case core.ImportEventIdentity:
84 importedIdentities++
85 }
86 }
87
88 // send done signal
89 close(done)
90
91 fmt.Printf("Successfully imported %d issues and %d identities with %s bridge\n", importedIssues, importedIdentities, b.Name)
92
93 return nil
94}
95
96var bridgePullCmd = &cobra.Command{
97 Use: "pull [<name>]",
98 Short: "Pull updates.",
99 PreRunE: loadRepo,
100 RunE: runBridgePull,
101 Args: cobra.MaximumNArgs(1),
102}
103
104func init() {
105 bridgeCmd.AddCommand(bridgePullCmd)
106}