From 94d06be035bac468129903c9f32e785baf3c1c3b Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Wed, 14 Feb 2024 19:50:31 +0100 Subject: Extract linguist code to method (#29168) --- services/repository/files/content.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'services') diff --git a/services/repository/files/content.go b/services/repository/files/content.go index c278d7f835..f2a7677688 100644 --- a/services/repository/files/content.go +++ b/services/repository/files/content.go @@ -270,3 +270,34 @@ func GetBlobBySHA(ctx context.Context, repo *repo_model.Repository, gitRepo *git Content: content, }, nil } + +// TryGetContentLanguage tries to get the (linguist) language of the file content +func TryGetContentLanguage(gitRepo *git.Repository, commitID, treePath string) (string, error) { + indexFilename, worktree, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(commitID) + if err != nil { + return "", err + } + + defer deleteTemporaryFile() + + filename2attribute2info, err := gitRepo.CheckAttribute(git.CheckAttributeOpts{ + CachedOnly: true, + Attributes: []string{"linguist-language", "gitlab-language"}, + Filenames: []string{treePath}, + IndexFile: indexFilename, + WorkTree: worktree, + }) + if err != nil { + return "", err + } + + language := filename2attribute2info[treePath]["linguist-language"] + if language == "" || language == "unspecified" { + language = filename2attribute2info[treePath]["gitlab-language"] + } + if language == "unspecified" { + language = "" + } + + return language, nil +} -- cgit v1.2.3