bridge_pull.go

  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		fmt.Println(result.String())
 77
 78		switch result.Event {
 79		case core.ImportEventBug:
 80			importedIssues++
 81		case core.ImportEventIdentity:
 82			importedIdentities++
 83		}
 84	}
 85
 86	// send done signal
 87	close(done)
 88
 89	fmt.Printf("Successfully imported %d issues and %d identities with %s bridge\n", importedIssues, importedIdentities, b.Name)
 90
 91	return nil
 92}
 93
 94var bridgePullCmd = &cobra.Command{
 95	Use:     "pull [<name>]",
 96	Short:   "Pull updates.",
 97	PreRunE: loadRepo,
 98	RunE:    runBridgePull,
 99	Args:    cobra.MaximumNArgs(1),
100}
101
102func init() {
103	bridgeCmd.AddCommand(bridgePullCmd)
104}