github.com/bilus/oya@v0.0.3-0.20190301162104-da4acbd394c6/pkg/raw/imports.go (about)

     1  package raw
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  var importKey = "Import:"
    11  var projectKey = "Project:"
    12  var uriVal = "  %s: %s"
    13  var importRegexp = regexp.MustCompile("(?m)^" + importKey + "$")
    14  var projectRegexp = regexp.MustCompile("^" + projectKey)
    15  
    16  func (raw *Oyafile) AddImport(alias, uri string) error {
    17  	if gotIt := raw.isAlreadyImported(uri); gotIt {
    18  		return errors.Errorf("Pack already imported: %v", uri)
    19  	}
    20  
    21  	err := raw.addImport(alias, uri)
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	return raw.write()
    27  }
    28  
    29  func (raw *Oyafile) addImport(alias, uri string) error {
    30  	uriStr := fmt.Sprintf(uriVal, alias, uri)
    31  	if updated, err := raw.insertAfter(importRegexp, uriStr); err != nil || updated {
    32  		return err // nil if updated
    33  	}
    34  	if updated, err := raw.insertAfter(projectRegexp, importKey, uriStr); err != nil || updated {
    35  		return err // nil if updated
    36  	}
    37  
    38  	return raw.prepend(
    39  		importKey,
    40  		uriStr,
    41  	)
    42  }
    43  
    44  func (raw *Oyafile) isAlreadyImported(uri string) bool {
    45  	// BUG(bilus): This is slightly brittle because it will match any line that ends with the uri. It might be a good idea to add a raw.(*Oyafile).matchesWithin function along the lines of how insertBeforeWithin is written.
    46  	rx := regexp.MustCompile("(?m)" + uri + "$")
    47  	return raw.matches(rx)
    48  }