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 runBridgePush(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	done := make(chan struct{}, 1)
 43
 44	var mu sync.Mutex
 45	interruptCount := 0
 46	interrupt.RegisterCleaner(func() error {
 47		mu.Lock()
 48		if interruptCount > 0 {
 49			fmt.Println("Received another interrupt before graceful stop, terminating...")
 50			os.Exit(0)
 51		}
 52
 53		interruptCount++
 54		mu.Unlock()
 55
 56		fmt.Println("Received interrupt signal, stopping the import...\n(Hit ctrl-c again to kill the process.)")
 57
 58		// send signal to stop the importer
 59		cancel()
 60
 61		// block until importer gracefully shutdown
 62		<-done
 63		return nil
 64	})
 65
 66	events, err := b.ExportAll(ctx, time.Time{})
 67	if err != nil {
 68		return err
 69	}
 70
 71	exportedIssues := 0
 72	for result := range events {
 73		if result.Event != core.ExportEventNothing {
 74			fmt.Println(result.String())
 75		}
 76
 77		switch result.Event {
 78		case core.ExportEventBug:
 79			exportedIssues++
 80		}
 81	}
 82
 83	fmt.Printf("exported %d issues with %s bridge\n", exportedIssues, b.Name)
 84
 85	// send done signal
 86	close(done)
 87	return nil
 88}
 89
 90var bridgePushCmd = &cobra.Command{
 91	Use:     "push [<name>]",
 92	Short:   "Push updates.",
 93	PreRunE: loadRepo,
 94	RunE:    runBridgePush,
 95	Args:    cobra.MaximumNArgs(1),
 96}
 97
 98func init() {
 99	bridgeCmd.AddCommand(bridgePushCmd)
100}