bridge.go

  1// Package core contains the target-agnostic code to define and run a bridge
  2package core
  3
  4import (
  5	"context"
  6	"fmt"
  7	"os"
  8	"reflect"
  9	"regexp"
 10	"sort"
 11	"strings"
 12	"time"
 13
 14	"github.com/pkg/errors"
 15
 16	"github.com/MichaelMure/git-bug/cache"
 17	"github.com/MichaelMure/git-bug/repository"
 18)
 19
 20var ErrImportNotSupported = errors.New("import is not supported")
 21var ErrExportNotSupported = errors.New("export is not supported")
 22
 23const (
 24	ConfigKeyTarget = "target"
 25
 26	MetaKeyOrigin = "origin"
 27
 28	bridgeConfigKeyPrefix = "git-bug.bridge"
 29)
 30
 31var bridgeImpl map[string]reflect.Type
 32var bridgeLoginMetaKey map[string]string
 33
 34// Bridge is a wrapper around a BridgeImpl that will bind low-level
 35// implementation with utility code to provide high-level functions.
 36type Bridge struct {
 37	Name           string
 38	repo           *cache.RepoCache
 39	impl           BridgeImpl
 40	importer       Importer
 41	exporter       Exporter
 42	conf           Configuration
 43	initImportDone bool
 44	initExportDone bool
 45}
 46
 47// Register will register a new BridgeImpl
 48func Register(impl BridgeImpl) {
 49	if bridgeImpl == nil {
 50		bridgeImpl = make(map[string]reflect.Type)
 51	}
 52	if bridgeLoginMetaKey == nil {
 53		bridgeLoginMetaKey = make(map[string]string)
 54	}
 55	bridgeImpl[impl.Target()] = reflect.TypeOf(impl).Elem()
 56	bridgeLoginMetaKey[impl.Target()] = impl.LoginMetaKey()
 57}
 58
 59// Targets return all known bridge implementation target
 60func Targets() []string {
 61	var result []string
 62
 63	for key := range bridgeImpl {
 64		result = append(result, key)
 65	}
 66
 67	sort.Strings(result)
 68
 69	return result
 70}
 71
 72// TargetExist return true if the given target has a bridge implementation
 73func TargetExist(target string) bool {
 74	_, ok := bridgeImpl[target]
 75	return ok
 76}
 77
 78// LoginMetaKey return the metadata key used to store the remote bug-tracker login
 79// on the user identity. The corresponding value is used to match identities and
 80// credentials.
 81func LoginMetaKey(target string) (string, error) {
 82	metaKey, ok := bridgeLoginMetaKey[target]
 83	if !ok {
 84		return "", fmt.Errorf("unknown bridge target %v", target)
 85	}
 86
 87	return metaKey, nil
 88}
 89
 90// Instantiate a new Bridge for a repo, from the given target and name
 91func NewBridge(repo *cache.RepoCache, target string, name string) (*Bridge, error) {
 92	implType, ok := bridgeImpl[target]
 93	if !ok {
 94		return nil, fmt.Errorf("unknown bridge target %v", target)
 95	}
 96
 97	impl := reflect.New(implType).Interface().(BridgeImpl)
 98
 99	bridge := &Bridge{
100		Name: name,
101		repo: repo,
102		impl: impl,
103	}
104
105	return bridge, nil
106}
107
108// LoadBridge instantiate a new bridge from a repo configuration
109func LoadBridge(repo *cache.RepoCache, name string) (*Bridge, error) {
110	conf, err := loadConfig(repo, name)
111	if err != nil {
112		return nil, err
113	}
114
115	target := conf[ConfigKeyTarget]
116	bridge, err := NewBridge(repo, target, name)
117	if err != nil {
118		return nil, err
119	}
120
121	err = bridge.impl.ValidateConfig(conf)
122	if err != nil {
123		return nil, errors.Wrap(err, "invalid configuration")
124	}
125
126	// will avoid reloading configuration before an export or import call
127	bridge.conf = conf
128	return bridge, nil
129}
130
131// Attempt to retrieve a default bridge for the given repo. If zero or multiple
132// bridge exist, it fails.
133func DefaultBridge(repo *cache.RepoCache) (*Bridge, error) {
134	bridges, err := ConfiguredBridges(repo)
135	if err != nil {
136		return nil, err
137	}
138
139	if len(bridges) == 0 {
140		return nil, fmt.Errorf("no configured bridge")
141	}
142
143	if len(bridges) > 1 {
144		return nil, fmt.Errorf("multiple bridge are configured, you need to select one explicitely")
145	}
146
147	return LoadBridge(repo, bridges[0])
148}
149
150// ConfiguredBridges return the list of bridge that are configured for the given
151// repo
152func ConfiguredBridges(repo repository.RepoConfig) ([]string, error) {
153	configs, err := repo.LocalConfig().ReadAll(bridgeConfigKeyPrefix + ".")
154	if err != nil {
155		return nil, errors.Wrap(err, "can't read configured bridges")
156	}
157
158	re := regexp.MustCompile(bridgeConfigKeyPrefix + `.([^.]+)`)
159
160	set := make(map[string]interface{})
161
162	for key := range configs {
163		res := re.FindStringSubmatch(key)
164
165		if res == nil {
166			continue
167		}
168
169		set[res[1]] = nil
170	}
171
172	result := make([]string, len(set))
173
174	i := 0
175	for key := range set {
176		result[i] = key
177		i++
178	}
179
180	return result, nil
181}
182
183// Check if a bridge exist
184func BridgeExist(repo repository.RepoConfig, name string) bool {
185	keyPrefix := fmt.Sprintf("git-bug.bridge.%s.", name)
186
187	conf, err := repo.LocalConfig().ReadAll(keyPrefix)
188
189	return err == nil && len(conf) > 0
190}
191
192// Remove a configured bridge
193func RemoveBridge(repo repository.RepoConfig, name string) error {
194	re := regexp.MustCompile(`^[a-zA-Z0-9]+`)
195
196	if !re.MatchString(name) {
197		return fmt.Errorf("bad bridge fullname: %s", name)
198	}
199
200	keyPrefix := fmt.Sprintf("git-bug.bridge.%s", name)
201	return repo.LocalConfig().RemoveAll(keyPrefix)
202}
203
204// Configure run the target specific configuration process
205func (b *Bridge) Configure(params BridgeParams, interactive bool) error {
206	validateParams(params, b.impl)
207
208	conf, err := b.impl.Configure(b.repo, params, interactive)
209	if err != nil {
210		return err
211	}
212
213	err = b.impl.ValidateConfig(conf)
214	if err != nil {
215		return fmt.Errorf("invalid configuration: %v", err)
216	}
217
218	b.conf = conf
219	return b.storeConfig(conf)
220}
221
222func validateParams(params BridgeParams, impl BridgeImpl) {
223	validParams := impl.ValidParams()
224
225	paramsValue := reflect.ValueOf(params)
226	paramsType := paramsValue.Type()
227
228	for i := 0; i < paramsValue.NumField(); i++ {
229		name := paramsType.Field(i).Name
230		val := paramsValue.Field(i).Interface().(string)
231		_, valid := validParams[name]
232		if val != "" && !valid {
233			_, _ = fmt.Fprintln(os.Stderr, params.fieldWarning(name, impl.Target()))
234		}
235	}
236}
237
238func (b *Bridge) storeConfig(conf Configuration) error {
239	for key, val := range conf {
240		storeKey := fmt.Sprintf("git-bug.bridge.%s.%s", b.Name, key)
241
242		err := b.repo.LocalConfig().StoreString(storeKey, val)
243		if err != nil {
244			return errors.Wrap(err, "error while storing bridge configuration")
245		}
246	}
247
248	return nil
249}
250
251func (b *Bridge) ensureConfig() error {
252	if b.conf == nil {
253		conf, err := loadConfig(b.repo, b.Name)
254		if err != nil {
255			return err
256		}
257		b.conf = conf
258	}
259
260	return nil
261}
262
263func loadConfig(repo repository.RepoConfig, name string) (Configuration, error) {
264	keyPrefix := fmt.Sprintf("git-bug.bridge.%s.", name)
265
266	pairs, err := repo.LocalConfig().ReadAll(keyPrefix)
267	if err != nil {
268		return nil, errors.Wrap(err, "error while reading bridge configuration")
269	}
270
271	result := make(Configuration, len(pairs))
272	for key, value := range pairs {
273		key := strings.TrimPrefix(key, keyPrefix)
274		result[key] = value
275	}
276
277	return result, nil
278}
279
280func (b *Bridge) getImporter() Importer {
281	if b.importer == nil {
282		b.importer = b.impl.NewImporter()
283	}
284
285	return b.importer
286}
287
288func (b *Bridge) getExporter() Exporter {
289	if b.exporter == nil {
290		b.exporter = b.impl.NewExporter()
291	}
292
293	return b.exporter
294}
295
296func (b *Bridge) ensureImportInit(ctx context.Context) error {
297	if b.initImportDone {
298		return nil
299	}
300
301	importer := b.getImporter()
302	if importer != nil {
303		err := importer.Init(ctx, b.repo, b.conf)
304		if err != nil {
305			return err
306		}
307	}
308
309	b.initImportDone = true
310	return nil
311}
312
313func (b *Bridge) ensureExportInit(ctx context.Context) error {
314	if b.initExportDone {
315		return nil
316	}
317
318	exporter := b.getExporter()
319	if exporter != nil {
320		err := exporter.Init(ctx, b.repo, b.conf)
321		if err != nil {
322			return err
323		}
324	}
325
326	b.initExportDone = true
327	return nil
328}
329
330func (b *Bridge) ImportAllSince(ctx context.Context, since time.Time) (<-chan ImportResult, error) {
331	// 5 seconds before the actual start just to be sure.
332	importStartTime := time.Now().Add(-5 * time.Second)
333
334	importer := b.getImporter()
335	if importer == nil {
336		return nil, ErrImportNotSupported
337	}
338
339	err := b.ensureConfig()
340	if err != nil {
341		return nil, err
342	}
343
344	err = b.ensureImportInit(ctx)
345	if err != nil {
346		return nil, err
347	}
348
349	events, err := importer.ImportAll(ctx, b.repo, since)
350	if err != nil {
351		return nil, err
352	}
353
354	out := make(chan ImportResult)
355	go func() {
356		defer close(out)
357		noError := true
358
359		// relay all events while checking that everything went well
360		for event := range events {
361			if event.Event == ImportEventError {
362				noError = false
363			}
364			out <- event
365		}
366
367		// store the last import time ONLY if no error happened
368		if noError {
369			key := fmt.Sprintf("git-bug.bridge.%s.lastImportTime", b.Name)
370			err = b.repo.LocalConfig().StoreTimestamp(key, importStartTime)
371		}
372	}()
373
374	return out, nil
375}
376
377func (b *Bridge) ImportAll(ctx context.Context) (<-chan ImportResult, error) {
378	// If possible, restart from the last import time
379	lastImport, err := b.repo.LocalConfig().ReadTimestamp(fmt.Sprintf("git-bug.bridge.%s.lastImportTime", b.Name))
380	if err == nil {
381		return b.ImportAllSince(ctx, lastImport)
382	}
383
384	return b.ImportAllSince(ctx, time.Time{})
385}
386
387func (b *Bridge) ExportAll(ctx context.Context, since time.Time) (<-chan ExportResult, error) {
388	exporter := b.getExporter()
389	if exporter == nil {
390		return nil, ErrExportNotSupported
391	}
392
393	err := b.ensureConfig()
394	if err != nil {
395		return nil, err
396	}
397
398	err = b.ensureExportInit(ctx)
399	if err != nil {
400		return nil, err
401	}
402
403	return exporter.ExportAll(ctx, b.repo, since)
404}