|
| 1 | +// Copyright 2021 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 | + |
| 5 | +package repository |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "os" |
| 11 | + "path/filepath" |
| 12 | + |
| 13 | + "code.gitea.io/gitea/modules/git" |
| 14 | +) |
| 15 | + |
| 16 | +// SyncGitAttributes copies the content of the .gitattributes file from the default branch into repo.git/info/attributes. |
| 17 | +func SyncGitAttributes(gitRepo *git.Repository, sourceBranch string) error { |
| 18 | + commit, err := gitRepo.GetBranchCommit(sourceBranch) |
| 19 | + if err != nil { |
| 20 | + return err |
| 21 | + } |
| 22 | + |
| 23 | + attributesBlob, err := commit.GetBlobByPath("/.gitattributes") |
| 24 | + if err != nil { |
| 25 | + if git.IsErrNotExist(err) { |
| 26 | + return nil |
| 27 | + } |
| 28 | + return err |
| 29 | + } |
| 30 | + |
| 31 | + infoPath := filepath.Join(gitRepo.Path, "info") |
| 32 | + if err := os.MkdirAll(infoPath, 0700); err != nil { |
| 33 | + return fmt.Errorf("Error creating directory [%s]: %v", infoPath, err) |
| 34 | + } |
| 35 | + attributesPath := filepath.Join(infoPath, "attributes") |
| 36 | + |
| 37 | + attributesFile, err := os.OpenFile(attributesPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) |
| 38 | + if err != nil { |
| 39 | + return fmt.Errorf("Error creating file [%s]: %v", attributesPath, err) |
| 40 | + } |
| 41 | + defer attributesFile.Close() |
| 42 | + |
| 43 | + blobReader, err := attributesBlob.DataAsync() |
| 44 | + if err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + defer blobReader.Close() |
| 48 | + |
| 49 | + _, err = io.Copy(attributesFile, blobReader) |
| 50 | + return err |
| 51 | +} |
0 commit comments