summaryrefslogtreecommitdiffstats
path: root/modules/git/repo_tree_nogogit.go
blob: 867c3fa5aae0f1f37a4eea1732325a891b044f87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// +build !gogit

package git

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"strings"
)

func (repo *Repository) getTree(id SHA1) (*Tree, error) {
	stdoutReader, stdoutWriter := io.Pipe()
	defer func() {
		_ = stdoutReader.Close()
		_ = stdoutWriter.Close()
	}()

	go func() {
		stderr := &strings.Builder{}
		err := NewCommand("cat-file", "--batch").RunInDirFullPipeline(repo.Path, stdoutWriter, stderr, strings.NewReader(id.String()+"\n"))
		if err != nil {
			_ = stdoutWriter.CloseWithError(ConcatenateError(err, stderr.String()))
		} else {
			_ = stdoutWriter.Close()
		}
	}()

	bufReader := bufio.NewReader(stdoutReader)
	// ignore the SHA
	_, typ, size, err := ReadBatchLine(bufReader)
	if err != nil {
		return nil, err
	}

	switch typ {
	case "tag":
		resolvedID := id
		data, err := ioutil.ReadAll(io.LimitReader(bufReader, size))
		if err != nil {
			return nil, err
		}
		tag, err := parseTagData(data)
		if err != nil {
			return nil, err
		}
		commit, err := tag.Commit()
		if err != nil {
			return nil, err
		}
		commit.Tree.ResolvedID = resolvedID
		log("tag.commit.Tree: %s %v", commit.Tree.ID.String(), commit.Tree.repo)
		return &commit.Tree, nil
	case "commit":
		commit, err := CommitFromReader(repo, id, io.LimitReader(bufReader, size))
		if err != nil {
			_ = stdoutReader.CloseWithError(err)
			return nil, err
		}
		commit.Tree.ResolvedID = commit.ID
		log("commit.Tree: %s %v", commit.Tree.ID.String(), commit.Tree.repo)
		return &commit.Tree, nil
	case "tree":
		stdoutReader.Close()
		tree := NewTree(repo, id)
		tree.ResolvedID = id
		return tree, nil
	default:
		_ = stdoutReader.CloseWithError(fmt.Errorf("unknown typ: %s", typ))
		return nil, ErrNotExist{
			ID: id.String(),
		}
	}
}

// GetTree find the tree object in the repository.
func (repo *Repository) GetTree(idStr string) (*Tree, error) {
	if len(idStr) != 40 {
		res, err := NewCommand("rev-parse", "--verify", idStr).RunInDir(repo.Path)
		if err != nil {
			return nil, err
		}
		if len(res) > 0 {
			idStr = res[:len(res)-1]
		}
	}
	id, err := NewIDFromString(idStr)
	if err != nil {
		return nil, err
	}

	return repo.getTree(id)
}