manus-tracker

tracker for scientific manuscripts
git clone git://src.adamsgaard.dk/manus-tracker # fast
git clone https://src.adamsgaard.dk/manus-tracker.git # slow
Log | Files | Refs | README Back to index

shared.go (1711B)


      1 package bib
      2 
      3 import (
      4 	"errors"
      5 	"os"
      6 )
      7 
      8 func loadIndex(path string) (*Index, error) {
      9 	es, err := ParseFile(path)
     10 	if err != nil && !errors.Is(err, os.ErrNotExist) {
     11 		return nil, err
     12 	}
     13 	return NewIndex(es), nil
     14 }
     15 
     16 // Add resolves query to a DOI and appends its entry to path unless the DOI
     17 // is already present. It returns the entry and whether it was added.
     18 func (c *Client) Add(path, query string) (*Entry, bool, error) {
     19 	ix, err := loadIndex(path)
     20 	if err != nil {
     21 		return nil, false, err
     22 	}
     23 	doi, err := c.Lookup(query)
     24 	if err != nil {
     25 		return nil, false, err
     26 	}
     27 	if e, ok := ix.ByDOI[doi]; ok {
     28 		return e, false, nil
     29 	}
     30 	e, err := c.Fetch(doi)
     31 	if err != nil {
     32 		return nil, false, err
     33 	}
     34 	if k := ix.FreeKey(e.Key); k != e.Key {
     35 		Rekey(e, k)
     36 	}
     37 	return e, true, Append(path, []*Entry{e})
     38 }
     39 
     40 type ImportResult struct {
     41 	Added   []*Entry
     42 	Dups    []*Entry
     43 	Renamed map[string]string
     44 }
     45 
     46 // Import appends entries from es that path lacks. Entries whose DOI, or
     47 // whose key and title, already exist are skipped; key clashes are renamed.
     48 func Import(path string, es []*Entry) (ImportResult, error) {
     49 	r := ImportResult{Renamed: map[string]string{}}
     50 	ix, err := loadIndex(path)
     51 	if err != nil {
     52 		return r, err
     53 	}
     54 	for _, e := range es {
     55 		if d := e.DOI(); d != "" {
     56 			if _, ok := ix.ByDOI[d]; ok {
     57 				r.Dups = append(r.Dups, e)
     58 				continue
     59 			}
     60 		}
     61 		if old, ok := ix.ByKey[e.Key]; ok {
     62 			if old.Fields["title"] == e.Fields["title"] {
     63 				r.Dups = append(r.Dups, e)
     64 				continue
     65 			}
     66 			k := ix.FreeKey(e.Key)
     67 			r.Renamed[e.Key] = k
     68 			Rekey(e, k)
     69 		}
     70 		r.Added = append(r.Added, e)
     71 		ix.ByKey[e.Key] = e
     72 		if d := e.DOI(); d != "" {
     73 			ix.ByDOI[d] = e
     74 		}
     75 	}
     76 	return r, Append(path, r.Added)
     77 }