github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/repo_tree.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // Copyright 2015 The Gogs Authors. All rights reserved.
     7  
     8  package git
     9  
    10  import (
    11  	"bytes"
    12  	"fmt"
    13  	"os"
    14  	"strings"
    15  	"time"
    16  )
    17  
    18  // CommitTreeOpts represents the possible options to CommitTree
    19  type CommitTreeOpts struct {
    20  	Parents    []string
    21  	Message    string
    22  	KeyID      string
    23  	NoGPGSign  bool
    24  	AlwaysSign bool
    25  }
    26  
    27  // CommitTree creates a commit from a given tree id for the user with provided message
    28  func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opts CommitTreeOpts) (SHA1, error) {
    29  	commitTimeStr := time.Now().Format(time.RFC3339)
    30  
    31  	// Because this may call hooks we should pass in the environment
    32  	env := append(os.Environ(),
    33  		"GIT_AUTHOR_NAME="+author.Name,
    34  		"GIT_AUTHOR_EMAIL="+author.Email,
    35  		"GIT_AUTHOR_DATE="+commitTimeStr,
    36  		"GIT_COMMITTER_NAME="+committer.Name,
    37  		"GIT_COMMITTER_EMAIL="+committer.Email,
    38  		"GIT_COMMITTER_DATE="+commitTimeStr,
    39  	)
    40  	cmd := NewCommand(repo.Ctx, "commit-tree", tree.ID.String())
    41  
    42  	for _, parent := range opts.Parents {
    43  		cmd.AddArguments("-p", parent)
    44  	}
    45  
    46  	messageBytes := new(bytes.Buffer)
    47  	_, _ = messageBytes.WriteString(opts.Message)
    48  	_, _ = messageBytes.WriteString("\n")
    49  
    50  	if opts.KeyID != "" || opts.AlwaysSign {
    51  		cmd.AddArguments(fmt.Sprintf("-S%s", opts.KeyID))
    52  	}
    53  
    54  	if opts.NoGPGSign {
    55  		cmd.AddArguments("--no-gpg-sign")
    56  	}
    57  
    58  	stdout := new(bytes.Buffer)
    59  	stderr := new(bytes.Buffer)
    60  	err := cmd.Run(&RunOpts{
    61  		Env:    env,
    62  		Dir:    repo.Path,
    63  		Stdin:  messageBytes,
    64  		Stdout: stdout,
    65  		Stderr: stderr,
    66  	})
    67  	if err != nil {
    68  		return SHA1{}, ConcatenateError(err, stderr.String())
    69  	}
    70  	return NewIDFromString(strings.TrimSpace(stdout.String()))
    71  }