github.com/scorpionis/hub@v2.2.1+incompatible/commands/utils.go (about)

     1  package commands
     2  
     3  import (
     4  	"bufio"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"github.com/github/hub/github"
    11  	"github.com/github/hub/utils"
    12  )
    13  
    14  type listFlag []string
    15  
    16  func (l *listFlag) String() string {
    17  	return strings.Join([]string(*l), ",")
    18  }
    19  
    20  func (l *listFlag) Set(value string) error {
    21  	for _, flag := range strings.Split(value, ",") {
    22  		*l = append(*l, flag)
    23  	}
    24  	return nil
    25  }
    26  
    27  func isDir(file string) bool {
    28  	f, err := os.Open(file)
    29  	if err != nil {
    30  		return false
    31  	}
    32  	defer f.Close()
    33  
    34  	fi, err := f.Stat()
    35  	if err != nil {
    36  		return false
    37  	}
    38  
    39  	return fi.IsDir()
    40  }
    41  
    42  func gitRemoteForProject(project *github.Project) (foundRemote *github.Remote) {
    43  	remotes, err := github.Remotes()
    44  	utils.Check(err)
    45  	for _, remote := range remotes {
    46  		remoteProject, pErr := remote.Project()
    47  		if pErr == nil && remoteProject.SameAs(project) {
    48  			foundRemote = &remote
    49  			return
    50  		}
    51  	}
    52  
    53  	return nil
    54  }
    55  
    56  func isEmptyDir(path string) bool {
    57  	fullPath := filepath.Join(path, "*")
    58  	match, _ := filepath.Glob(fullPath)
    59  	return match == nil
    60  }
    61  
    62  func getTitleAndBodyFromFlags(messageFlag, fileFlag string) (title, body string, err error) {
    63  	if messageFlag != "" {
    64  		title, body = readMsg(messageFlag)
    65  	} else if fileFlag != "" {
    66  		var (
    67  			content []byte
    68  			err     error
    69  		)
    70  
    71  		if fileFlag == "-" {
    72  			content, err = ioutil.ReadAll(os.Stdin)
    73  		} else {
    74  			content, err = ioutil.ReadFile(fileFlag)
    75  		}
    76  		utils.Check(err)
    77  
    78  		title, body = readMsg(string(content))
    79  	}
    80  
    81  	return
    82  }
    83  
    84  func readMsg(msg string) (title, body string) {
    85  	s := bufio.NewScanner(strings.NewReader(msg))
    86  	if s.Scan() {
    87  		title = s.Text()
    88  		body = strings.TrimLeft(msg, title)
    89  
    90  		title = strings.TrimSpace(title)
    91  		body = strings.TrimSpace(body)
    92  	}
    93  
    94  	return
    95  }
    96  
    97  func runInLocalRepo(fn func(localRepo *github.GitHubRepo, project *github.Project, client *github.Client)) {
    98  	localRepo, err := github.LocalRepo()
    99  	utils.Check(err)
   100  
   101  	project, err := localRepo.CurrentProject()
   102  	utils.Check(err)
   103  
   104  	client := github.NewClient(project.Host)
   105  	fn(localRepo, project, client)
   106  
   107  	os.Exit(0)
   108  }