github.com/c3pm-labs/c3pm@v0.3.0/ctpm/publish.go (about)

     1  package ctpm
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/bmatcuk/doublestar"
     6  	"github.com/c3pm-labs/c3pm/api"
     7  	"github.com/c3pm-labs/c3pm/config"
     8  	"os"
     9  	"path/filepath"
    10  )
    11  
    12  func isFileInList(path string, rules []string) (bool, error) {
    13  	for _, rule := range rules {
    14  		ok, err := doublestar.Match(rule, path)
    15  		if err != nil {
    16  			return false, fmt.Errorf("failed to match [%s] with [%s] regex: %w", path, rule, err)
    17  		}
    18  		if ok {
    19  			return true, nil
    20  		}
    21  	}
    22  	return false, nil
    23  }
    24  
    25  func getFilesFromRules(included []string, excluded []string) ([]string, error) {
    26  	var files []string
    27  	err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
    28  		if err != nil {
    29  			return fmt.Errorf("publish list files walk: %w", err)
    30  		}
    31  		if info.IsDir() {
    32  			return nil
    33  		}
    34  		isIncluded, err := isFileInList(path, included)
    35  		if err != nil {
    36  			return fmt.Errorf("could not find if path [%s] is included: %w", path, err)
    37  		}
    38  		if isIncluded {
    39  			isExcluded, err := isFileInList(path, excluded)
    40  			if err != nil {
    41  				return fmt.Errorf("could not find if path [%s] is excluded: %w", path, err)
    42  			}
    43  			if !isExcluded {
    44  				files = append(files, path)
    45  			}
    46  		}
    47  		return nil
    48  	})
    49  	return files, err
    50  }
    51  
    52  // Publish function makes an array of the files to include in the tarball
    53  // based on the Include and Exclude fields of the c3pm.yaml
    54  // The array is then given to the Upload function in the client
    55  // We enforce the exclusion of the .git and .c3pm directories and we enforce
    56  // the inclusion of the c3pm.yml file
    57  func Publish(pc *config.ProjectConfig, client api.API) error {
    58  	included := append(pc.Manifest.Publish.Include, "c3pm.yml")
    59  	excluded := append(pc.Manifest.Publish.Exclude, ".git/**", ".c3pm/**")
    60  
    61  	files, err := getFilesFromRules(included, excluded)
    62  	if err != nil {
    63  		return fmt.Errorf("failed to list files to publish: %w", err)
    64  	}
    65  	return client.Upload(files)
    66  }