github.com/simonferquel/app@v0.6.1-0.20181012141724-68b7cccf26ac/internal/names.go (about)

     1  package internal
     2  
     3  import (
     4  	"fmt"
     5  	"path/filepath"
     6  	"regexp"
     7  	"strings"
     8  )
     9  
    10  const (
    11  	// AppExtension is the extension used by an application.
    12  	AppExtension = ".dockerapp"
    13  	// ImageLabel is the label used to distinguish applications from Docker images.
    14  	ImageLabel = "com.docker.application"
    15  	// MetadataFileName is metadata file name
    16  	MetadataFileName = "metadata.yml"
    17  	// ComposeFileName is compose file name
    18  	ComposeFileName = "docker-compose.yml"
    19  	// SettingsFileName is settings file name
    20  	SettingsFileName = "settings.yml"
    21  )
    22  
    23  var (
    24  	// FileNames lists the application file names, in order.
    25  	FileNames = []string{MetadataFileName, ComposeFileName, SettingsFileName}
    26  )
    27  
    28  var appNameRe, _ = regexp.Compile("^[a-zA-Z][a-zA-Z0-9_-]+$")
    29  
    30  // AppNameFromDir takes a path to an app directory and returns
    31  // the application's name
    32  func AppNameFromDir(dirName string) string {
    33  	return strings.TrimSuffix(filepath.Base(dirName), AppExtension)
    34  }
    35  
    36  // DirNameFromAppName takes an application name and returns the
    37  // corresponding directory name
    38  func DirNameFromAppName(appName string) string {
    39  	if strings.HasSuffix(strings.TrimSuffix(appName, "/"), AppExtension) {
    40  		return appName
    41  	}
    42  	return appName + AppExtension
    43  }
    44  
    45  // ValidateAppName takes an app name and returns an error if it doesn't
    46  // match the expected format
    47  func ValidateAppName(appName string) error {
    48  	if appNameRe.MatchString(appName) {
    49  		return nil
    50  	}
    51  	return fmt.Errorf(
    52  		"invalid app name: %s ; app names must start with a letter, and must contain only letters, numbers, '-' and '_' (regexp: %q)",
    53  		appName,
    54  		appNameRe.String(),
    55  	)
    56  }