bridge.go

  1// Package core contains the target-agnostic code to define and run a bridge
  2package core
  3
  4import (
  5	"fmt"
  6	"reflect"
  7	"regexp"
  8	"sort"
  9	"strings"
 10	"time"
 11
 12	"github.com/pkg/errors"
 13
 14	"github.com/MichaelMure/git-bug/cache"
 15	"github.com/MichaelMure/git-bug/repository"
 16)
 17
 18var ErrImportNotSupported = errors.New("import is not supported")
 19var ErrExportNotSupported = errors.New("export is not supported")
 20
 21const (
 22	keyTarget             = "target"
 23	bridgeConfigKeyPrefix = "git-bug.bridge"
 24)
 25
 26var bridgeImpl map[string]reflect.Type
 27
 28// BridgeParams holds parameters to simplify the bridge configuration without
 29// having to make terminal prompts.
 30type BridgeParams struct {
 31	Owner   string
 32	Project string
 33	URL     string
 34	Token   string
 35}
 36
 37// Bridge is a wrapper around a BridgeImpl that will bind low-level
 38// implementation with utility code to provide high-level functions.
 39type Bridge struct {
 40	Name     string
 41	repo     *cache.RepoCache
 42	impl     BridgeImpl
 43	importer Importer
 44	exporter Exporter
 45	conf     Configuration
 46	initDone bool
 47}
 48
 49// Register will register a new BridgeImpl
 50func Register(impl BridgeImpl) {
 51	if bridgeImpl == nil {
 52		bridgeImpl = make(map[string]reflect.Type)
 53	}
 54	bridgeImpl[impl.Target()] = reflect.TypeOf(impl)
 55}
 56
 57// Targets return all known bridge implementation target
 58func Targets() []string {
 59	var result []string
 60
 61	for key := range bridgeImpl {
 62		result = append(result, key)
 63	}
 64
 65	sort.Strings(result)
 66
 67	return result
 68}
 69
 70// Instantiate a new Bridge for a repo, from the given target and name
 71func NewBridge(repo *cache.RepoCache, target string, name string) (*Bridge, error) {
 72	implType, ok := bridgeImpl[target]
 73	if !ok {
 74		return nil, fmt.Errorf("unknown bridge target %v", target)
 75	}
 76
 77	impl := reflect.New(implType).Elem().Interface().(BridgeImpl)
 78
 79	bridge := &Bridge{
 80		Name: name,
 81		repo: repo,
 82		impl: impl,
 83	}
 84
 85	return bridge, nil
 86}
 87
 88// LoadBridge instantiate a new bridge from a repo configuration
 89func LoadBridge(repo *cache.RepoCache, name string) (*Bridge, error) {
 90	conf, err := loadConfig(repo, name)
 91	if err != nil {
 92		return nil, err
 93	}
 94
 95	target := conf[keyTarget]
 96	bridge, err := NewBridge(repo, target, name)
 97	if err != nil {
 98		return nil, err
 99	}
100
101	err = bridge.impl.ValidateConfig(conf)
102	if err != nil {
103		return nil, errors.Wrap(err, "invalid configuration")
104	}
105
106	// will avoid reloading configuration before an export or import call
107	bridge.conf = conf
108	return bridge, nil
109}
110
111// Attempt to retrieve a default bridge for the given repo. If zero or multiple
112// bridge exist, it fails.
113func DefaultBridge(repo *cache.RepoCache) (*Bridge, error) {
114	bridges, err := ConfiguredBridges(repo)
115	if err != nil {
116		return nil, err
117	}
118
119	if len(bridges) == 0 {
120		return nil, fmt.Errorf("no configured bridge")
121	}
122
123	if len(bridges) > 1 {
124		return nil, fmt.Errorf("multiple bridge are configured, you need to select one explicitely")
125	}
126
127	return LoadBridge(repo, bridges[0])
128}
129
130// ConfiguredBridges return the list of bridge that are configured for the given
131// repo
132func ConfiguredBridges(repo repository.RepoCommon) ([]string, error) {
133	configs, err := repo.ReadConfigs(bridgeConfigKeyPrefix + ".")
134	if err != nil {
135		return nil, errors.Wrap(err, "can't read configured bridges")
136	}
137
138	re, err := regexp.Compile(bridgeConfigKeyPrefix + `.([^.]+)`)
139	if err != nil {
140		panic(err)
141	}
142
143	set := make(map[string]interface{})
144
145	for key := range configs {
146		res := re.FindStringSubmatch(key)
147
148		if res == nil {
149			continue
150		}
151
152		set[res[1]] = nil
153	}
154
155	result := make([]string, len(set))
156
157	i := 0
158	for key := range set {
159		result[i] = key
160		i++
161	}
162
163	return result, nil
164}
165
166// Remove a configured bridge
167func RemoveBridge(repo repository.RepoCommon, name string) error {
168	re, err := regexp.Compile(`^[a-zA-Z0-9]+`)
169	if err != nil {
170		panic(err)
171	}
172
173	if !re.MatchString(name) {
174		return fmt.Errorf("bad bridge fullname: %s", name)
175	}
176
177	keyPrefix := fmt.Sprintf("git-bug.bridge.%s", name)
178	return repo.RmConfigs(keyPrefix)
179}
180
181// Configure run the target specific configuration process
182func (b *Bridge) Configure(params BridgeParams) error {
183	conf, err := b.impl.Configure(b.repo, params)
184	if err != nil {
185		return err
186	}
187
188	err = b.impl.ValidateConfig(conf)
189	if err != nil {
190		return fmt.Errorf("invalid configuration: %v", err)
191	}
192
193	b.conf = conf
194	return b.storeConfig(conf)
195}
196
197func (b *Bridge) storeConfig(conf Configuration) error {
198	for key, val := range conf {
199		storeKey := fmt.Sprintf("git-bug.bridge.%s.%s", b.Name, key)
200
201		err := b.repo.StoreConfig(storeKey, val)
202		if err != nil {
203			return errors.Wrap(err, "error while storing bridge configuration")
204		}
205	}
206
207	return nil
208}
209
210func (b *Bridge) ensureConfig() error {
211	if b.conf == nil {
212		conf, err := loadConfig(b.repo, b.Name)
213		if err != nil {
214			return err
215		}
216		b.conf = conf
217	}
218
219	return nil
220}
221
222func loadConfig(repo *cache.RepoCache, name string) (Configuration, error) {
223	keyPrefix := fmt.Sprintf("git-bug.bridge.%s.", name)
224
225	pairs, err := repo.ReadConfigs(keyPrefix)
226	if err != nil {
227		return nil, errors.Wrap(err, "error while reading bridge configuration")
228	}
229
230	result := make(Configuration, len(pairs))
231	for key, value := range pairs {
232		key := strings.TrimPrefix(key, keyPrefix)
233		result[key] = value
234	}
235
236	return result, nil
237}
238
239func (b *Bridge) getImporter() Importer {
240	if b.importer == nil {
241		b.importer = b.impl.NewImporter()
242	}
243
244	return b.importer
245}
246
247func (b *Bridge) getExporter() Exporter {
248	if b.exporter == nil {
249		b.exporter = b.impl.NewExporter()
250	}
251
252	return b.exporter
253}
254
255func (b *Bridge) ensureInit() error {
256	if b.initDone {
257		return nil
258	}
259
260	importer := b.getImporter()
261	if importer != nil {
262		err := importer.Init(b.conf)
263		if err != nil {
264			return err
265		}
266	}
267
268	exporter := b.getExporter()
269	if exporter != nil {
270		err := exporter.Init(b.conf)
271		if err != nil {
272			return err
273		}
274	}
275
276	b.initDone = true
277
278	return nil
279}
280
281func (b *Bridge) ImportAll(since time.Time) error {
282	importer := b.getImporter()
283	if importer == nil {
284		return ErrImportNotSupported
285	}
286
287	err := b.ensureConfig()
288	if err != nil {
289		return err
290	}
291
292	err = b.ensureInit()
293	if err != nil {
294		return err
295	}
296
297	return importer.ImportAll(b.repo, since)
298}
299
300func (b *Bridge) ExportAll(since time.Time) (<-chan ExportResult, error) {
301	exporter := b.getExporter()
302	if exporter == nil {
303		return nil, ErrExportNotSupported
304	}
305
306	err := b.ensureConfig()
307	if err != nil {
308		return nil, err
309	}
310
311	err = b.ensureInit()
312	if err != nil {
313		return nil, err
314	}
315
316	return exporter.ExportAll(b.repo, since), nil
317}