1// Copyright 2019 The Gitea Authors. All rights reserved.
2// Use of this source code is governed by a MIT-style
3// license that can be found in the LICENSE file.
4
5package files
6
7import (
8	"strings"
9
10	repo_model "code.gitea.io/gitea/models/repo"
11	"code.gitea.io/gitea/services/gitdiff"
12)
13
14// GetDiffPreview produces and returns diff result of a file which is not yet committed.
15func GetDiffPreview(repo *repo_model.Repository, branch, treePath, content string) (*gitdiff.Diff, error) {
16	if branch == "" {
17		branch = repo.DefaultBranch
18	}
19	t, err := NewTemporaryUploadRepository(repo)
20	if err != nil {
21		return nil, err
22	}
23	defer t.Close()
24	if err := t.Clone(branch); err != nil {
25		return nil, err
26	}
27	if err := t.SetDefaultIndex(); err != nil {
28		return nil, err
29	}
30
31	// Add the object to the database
32	objectHash, err := t.HashObject(strings.NewReader(content))
33	if err != nil {
34		return nil, err
35	}
36
37	// Add the object to the index
38	if err := t.AddObjectToIndex("100644", objectHash, treePath); err != nil {
39		return nil, err
40	}
41	return t.DiffIndex()
42}
43