github.com/wtfutil/wtf@v0.43.0/modules/mercurial/hg_repo.go (about)

     1  package mercurial
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"path"
     8  	"strings"
     9  
    10  	"github.com/wtfutil/wtf/utils"
    11  )
    12  
    13  type MercurialRepo struct {
    14  	Branch       string
    15  	Bookmark     string
    16  	ChangedFiles []string
    17  	Commits      []string
    18  	Repository   string
    19  	Path         string
    20  }
    21  
    22  func NewMercurialRepo(repoPath string, commitCount int, commitFormat string) *MercurialRepo {
    23  	repo := MercurialRepo{Path: repoPath}
    24  
    25  	repo.Branch = strings.TrimSpace(repo.branch())
    26  	repo.Bookmark = strings.TrimSpace(repo.bookmark())
    27  	repo.ChangedFiles = repo.changedFiles()
    28  	repo.Commits = repo.commits(commitCount, commitFormat)
    29  	repo.Repository = strings.TrimSpace(repo.Path)
    30  
    31  	return &repo
    32  }
    33  
    34  /* -------------------- Unexported Functions -------------------- */
    35  
    36  func (repo *MercurialRepo) branch() string {
    37  	arg := []string{"branch", repo.repoPath()}
    38  
    39  	cmd := exec.Command("hg", arg...)
    40  	str := utils.ExecuteCommand(cmd)
    41  
    42  	return str
    43  }
    44  
    45  func (repo *MercurialRepo) bookmark() string {
    46  	bookmark, err := os.ReadFile(path.Join(repo.Path, ".hg", "bookmarks.current"))
    47  	if err != nil {
    48  		return ""
    49  	}
    50  	return string(bookmark)
    51  }
    52  
    53  func (repo *MercurialRepo) changedFiles() []string {
    54  	arg := []string{"status", repo.repoPath()}
    55  
    56  	cmd := exec.Command("hg", arg...)
    57  	str := utils.ExecuteCommand(cmd)
    58  
    59  	data := strings.Split(str, "\n")
    60  
    61  	return data
    62  }
    63  
    64  func (repo *MercurialRepo) commits(commitCount int, commitFormat string) []string {
    65  	numStr := fmt.Sprintf("-l %d", commitCount)
    66  	commitStr := fmt.Sprintf("--template=\"%s\n\"", commitFormat)
    67  
    68  	arg := []string{"log", repo.repoPath(), numStr, commitStr}
    69  
    70  	cmd := exec.Command("hg", arg...)
    71  	str := utils.ExecuteCommand(cmd)
    72  
    73  	data := strings.Split(str, "\n")
    74  
    75  	return data
    76  }
    77  
    78  func (repo *MercurialRepo) pull() string {
    79  	arg := []string{"pull", repo.repoPath()}
    80  	cmd := exec.Command("hg", arg...)
    81  	str := utils.ExecuteCommand(cmd)
    82  	return str
    83  }
    84  
    85  func (repo *MercurialRepo) checkout(branch string) string {
    86  	arg := []string{"checkout", repo.repoPath(), branch}
    87  	cmd := exec.Command("hg", arg...)
    88  	str := utils.ExecuteCommand(cmd)
    89  	return str
    90  }
    91  
    92  func (repo *MercurialRepo) repoPath() string {
    93  	return fmt.Sprintf("--repository=%s", repo.Path)
    94  }