code.gitea.io/gitea@v1.21.7/services/repository/files/diff.go (about)

     1  // Copyright 2019 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package files
     5  
     6  import (
     7  	"context"
     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.
    15  func GetDiffPreview(ctx context.Context, repo *repo_model.Repository, branch, treePath, content string) (*gitdiff.Diff, error) {
    16  	if branch == "" {
    17  		branch = repo.DefaultBranch
    18  	}
    19  	t, err := NewTemporaryUploadRepository(ctx, repo)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	defer t.Close()
    24  	if err := t.Clone(branch, true); 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  }