github.com/bhameyie/otto@v0.2.1-0.20160406174117-16052efa52ec/builtin/app/ruby/gemfile.go (about)

     1  package rubyapp
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  	"regexp"
     9  )
    10  
    11  var (
    12  	// regexp for finding gems in a gemfile
    13  	gemGemfileRegexp = `\s*gem\s+['"]%s['"]`
    14  
    15  	// regexp for finding gems in a gemfile.lock
    16  	gemGemfileLockRegexp = `\s*%s\s+\(`
    17  )
    18  
    19  // HasGem checks if the Ruby project in the given directory has the
    20  // specified gem. This uses Gemfile and Gemfile.lock to find this gem.
    21  //
    22  // If no Gemfile is in the directory, false is always returned.
    23  func HasGem(dir, name string) (bool, error) {
    24  	// Check normal Gemfile
    25  	ok, err := hasGemGemfile(dir, name)
    26  	if ok || err != nil {
    27  		return ok, err
    28  	}
    29  
    30  	// Check Gemfile.lock
    31  	ok, err = hasGemGemfileLock(dir, name)
    32  	if ok || err != nil {
    33  		return ok, err
    34  	}
    35  
    36  	// Nope!
    37  	return false, nil
    38  }
    39  
    40  func hasGemGemfile(dir, name string) (bool, error) {
    41  	path := filepath.Join(dir, "Gemfile")
    42  	reStr := fmt.Sprintf(gemGemfileRegexp, name)
    43  	return hasGemRaw(path, reStr)
    44  }
    45  
    46  func hasGemGemfileLock(dir, name string) (bool, error) {
    47  	path := filepath.Join(dir, "Gemfile.lock")
    48  	reStr := fmt.Sprintf(gemGemfileLockRegexp, name)
    49  	return hasGemRaw(path, reStr)
    50  }
    51  
    52  func hasGemRaw(path, reStr string) (bool, error) {
    53  	if _, err := os.Stat(path); err != nil {
    54  		if os.IsNotExist(err) {
    55  			err = nil
    56  		}
    57  
    58  		return false, err
    59  	}
    60  
    61  	// Try to find it!
    62  	f, err := os.Open(path)
    63  	if err != nil {
    64  		return false, err
    65  	}
    66  	defer f.Close()
    67  
    68  	re := regexp.MustCompile(reStr)
    69  	return re.MatchReader(bufio.NewReader(f)), nil
    70  }