Use check attribute code to check the assigned language of a file and send that in to
chroma as a hint for the language of the file.
Signed-off-by: Andrew Thornton <art27@cantab.net>
To apply a sanitisation rules only for a specify external renderer they must use the renderer name, e.g. `[markup.sanitizer.asciidoc.rule-1]`.
If the rule is defined above the renderer ini section or the name does not match a renderer it is applied to every renderer.
+## Highlight Mappings (`highlight.mapping`)
+
+- `file_extension e.g. .toml`: **language e.g. ini**. File extension to language mapping overrides.
+
+- Gitea will highlight files using the `linguist-language` or `gitlab-language` attribute from the `.gitattributes` file
+if available. If this is not set or the language is unavailable, the file extension will be looked up
+in this mapping or the filetype using heuristics.
+
## Time (`time`)
- `FORMAT`: Time format to display on UI. i.e. RFC1123 or 2006-01-02 15:04:05
AllAttributes bool
Attributes []string
Filenames []string
+ IndexFile string
+ WorkTree string
}
// CheckAttribute return the Blame object of file
return nil, fmt.Errorf("git version missing: %v", err)
}
+ env := []string{}
+
+ if len(opts.IndexFile) > 0 && CheckGitVersionAtLeast("1.7.8") == nil {
+ env = append(env, "GIT_INDEX_FILE="+opts.IndexFile)
+ }
+ if len(opts.WorkTree) > 0 && CheckGitVersionAtLeast("1.7.8") == nil {
+ env = append(env, "GIT_WORK_TREE="+opts.WorkTree)
+ }
+
+ if len(env) > 0 {
+ env = append(os.Environ(), env...)
+ }
+
stdOut := new(bytes.Buffer)
stdErr := new(bytes.Buffer)
cmd := NewCommand(cmdArgs...)
- if err := cmd.RunInDirPipeline(repo.Path, stdOut, stdErr); err != nil {
+ if err := cmd.RunInDirTimeoutEnvPipeline(env, -1, repo.Path, stdOut, stdErr); err != nil {
return nil, fmt.Errorf("failed to run check-attr: %v\n%s\n%s", err, stdOut.String(), stdErr.String())
}
"bytes"
"context"
"os"
+ "path/filepath"
"strings"
"code.gitea.io/gitea/modules/log"
}
// ReadTreeToTemporaryIndex reads a treeish to a temporary index file
-func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename string, cancel context.CancelFunc, err error) {
- tmpIndex, err := os.CreateTemp("", "index")
+func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename, tmpDir string, cancel context.CancelFunc, err error) {
+ tmpDir, err = os.MkdirTemp("", "index")
if err != nil {
return
}
- filename = tmpIndex.Name()
+
+ filename = filepath.Join(tmpDir, ".tmp-index")
cancel = func() {
- err := util.Remove(filename)
+ err := util.RemoveAll(tmpDir)
if err != nil {
log.Error("failed to remove tmp index file: %v", err)
}
err = repo.ReadTreeToIndex(treeish, filename)
if err != nil {
defer cancel()
- return "", func() {}, err
+ return "", "", func() {}, err
}
return
}
"bytes"
"context"
"io"
- "os"
+ "strings"
"code.gitea.io/gitea/modules/analyze"
"code.gitea.io/gitea/modules/log"
- "code.gitea.io/gitea/modules/util"
"github.com/go-enry/go-enry/v2"
"github.com/go-git/go-git/v5"
var checker *CheckAttributeReader
if CheckGitVersionAtLeast("1.7.8") == nil {
- indexFilename, deleteTemporaryFile, err := repo.ReadTreeToTemporaryIndex(commitID)
+ indexFilename, workTree, deleteTemporaryFile, err := repo.ReadTreeToTemporaryIndex(commitID)
if err == nil {
defer deleteTemporaryFile()
- tmpWorkTree, err := os.MkdirTemp("", "empty-work-dir")
- if err == nil {
- defer func() {
- _ = util.RemoveAll(tmpWorkTree)
+ checker = &CheckAttributeReader{
+ Attributes: []string{"linguist-vendored", "linguist-generated", "linguist-language", "gitlab-language"},
+ Repo: repo,
+ IndexFile: indexFilename,
+ WorkTree: workTree,
+ }
+ ctx, cancel := context.WithCancel(DefaultContext)
+ if err := checker.Init(ctx); err != nil {
+ log.Error("Unable to open checker for %s. Error: %v", commitID, err)
+ } else {
+ go func() {
+ err = checker.Run()
+ if err != nil {
+ log.Error("Unable to open checker for %s. Error: %v", commitID, err)
+ cancel()
+ }
}()
-
- checker = &CheckAttributeReader{
- Attributes: []string{"linguist-vendored", "linguist-generated", "linguist-language"},
- Repo: repo,
- IndexFile: indexFilename,
- WorkTree: tmpWorkTree,
- }
- ctx, cancel := context.WithCancel(DefaultContext)
- if err := checker.Init(ctx); err != nil {
- log.Error("Unable to open checker for %s. Error: %v", commitID, err)
- } else {
- go func() {
- err = checker.Run()
- if err != nil {
- log.Error("Unable to open checker for %s. Error: %v", commitID, err)
- cancel()
- }
- }()
- }
- defer cancel()
}
+ defer cancel()
}
}
sizes[language] += f.Size
return nil
+ } else if language, has := attrs["gitlab-language"]; has && language != "unspecified" && language != "" {
+ // strip off a ? if present
+ if idx := strings.IndexByte(language, '?'); idx >= 0 {
+ language = language[:idx]
+ }
+ if len(language) != 0 {
+ // group languages, such as Pug -> HTML; SCSS -> CSS
+ group := enry.GetLanguageGroup(language)
+ if len(group) != 0 {
+ language = group
+ }
+
+ sizes[language] += f.Size
+ return nil
+ }
}
}
}
"context"
"io"
"math"
- "os"
+ "strings"
"code.gitea.io/gitea/modules/analyze"
"code.gitea.io/gitea/modules/log"
- "code.gitea.io/gitea/modules/util"
"github.com/go-enry/go-enry/v2"
)
var checker *CheckAttributeReader
if CheckGitVersionAtLeast("1.7.8") == nil {
- indexFilename, deleteTemporaryFile, err := repo.ReadTreeToTemporaryIndex(commitID)
+ indexFilename, worktree, deleteTemporaryFile, err := repo.ReadTreeToTemporaryIndex(commitID)
if err == nil {
defer deleteTemporaryFile()
- tmpWorkTree, err := os.MkdirTemp("", "empty-work-dir")
- if err == nil {
- defer func() {
- _ = util.RemoveAll(tmpWorkTree)
+ checker = &CheckAttributeReader{
+ Attributes: []string{"linguist-vendored", "linguist-generated", "linguist-language", "gitlab-language"},
+ Repo: repo,
+ IndexFile: indexFilename,
+ WorkTree: worktree,
+ }
+ ctx, cancel := context.WithCancel(DefaultContext)
+ if err := checker.Init(ctx); err != nil {
+ log.Error("Unable to open checker for %s. Error: %v", commitID, err)
+ } else {
+ go func() {
+ err = checker.Run()
+ if err != nil {
+ log.Error("Unable to open checker for %s. Error: %v", commitID, err)
+ cancel()
+ }
}()
-
- checker = &CheckAttributeReader{
- Attributes: []string{"linguist-vendored", "linguist-generated", "linguist-language"},
- Repo: repo,
- IndexFile: indexFilename,
- WorkTree: tmpWorkTree,
- }
- ctx, cancel := context.WithCancel(DefaultContext)
- if err := checker.Init(ctx); err != nil {
- log.Error("Unable to open checker for %s. Error: %v", commitID, err)
- } else {
- go func() {
- err = checker.Run()
- if err != nil {
- log.Error("Unable to open checker for %s. Error: %v", commitID, err)
- cancel()
- }
- }()
- }
- defer cancel()
}
+ defer cancel()
}
}
sizes[language] += f.Size()
continue
+ } else if language, has := attrs["gitlab-language"]; has && language != "unspecified" && language != "" {
+ // strip off a ? if present
+ if idx := strings.IndexByte(language, '?'); idx >= 0 {
+ language = language[:idx]
+ }
+ if len(language) != 0 {
+ // group languages, such as Pug -> HTML; SCSS -> CSS
+ group := enry.GetLanguageGroup(language)
+ if len(group) != 0 {
+ language = group
+ }
+
+ sizes[language] += f.Size()
+ continue
+ }
}
+
}
}
}
// Code returns a HTML version of code string with chroma syntax highlighting classes
-func Code(fileName, code string) string {
+func Code(fileName, language, code string) string {
NewContext()
// diff view newline will be passed as empty, change to literal \n so it can be copied
}
var lexer chroma.Lexer
- if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
- //use mapped value to find lexer
- lexer = lexers.Get(val)
+
+ if len(language) > 0 {
+ lexer = lexers.Get(language)
+
+ if lexer == nil {
+ // Attempt stripping off the '?'
+ if idx := strings.IndexByte(language, '?'); idx > 0 {
+ lexer = lexers.Get(language[:idx])
+ }
+ }
+ }
+
+ if lexer == nil {
+ if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
+ //use mapped value to find lexer
+ lexer = lexers.Get(val)
+ }
}
if lexer == nil {
}
// File returns a slice of chroma syntax highlighted lines of code
-func File(numLines int, fileName string, code []byte) []string {
+func File(numLines int, fileName, language string, code []byte) []string {
NewContext()
if len(code) > sizeLimit {
htmlw := bufio.NewWriter(&htmlbuf)
var lexer chroma.Lexer
- if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
- lexer = lexers.Get(val)
+
+ // provided language overrides everything
+ if len(language) > 0 {
+ lexer = lexers.Get(language)
+ }
+
+ if lexer == nil {
+ if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
+ lexer = lexers.Get(val)
+ }
}
if lexer == nil {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- if got := File(tt.numLines, tt.fileName, []byte(tt.code)); !reflect.DeepEqual(got, tt.want) {
+ if got := File(tt.numLines, tt.fileName, "", []byte(tt.code)); !reflect.DeepEqual(got, tt.want) {
t.Errorf("File() = %v, want %v", got, tt.want)
}
})
Language: result.Language,
Color: result.Color,
LineNumbers: lineNumbers,
- FormattedLines: highlight.Code(result.Filename, formattedLinesBuffer.String()),
+ FormattedLines: highlight.Code(result.Filename, "", formattedLinesBuffer.String()),
}, nil
}
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/unittest"
+ "code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/gitdiff"
t.Run("with given branch", func(t *testing.T) {
diff, err := GetDiffPreview(ctx.Repo.Repository, branch, treePath, content)
assert.NoError(t, err)
- assert.EqualValues(t, expectedDiff, diff)
+ expectedBs, err := json.Marshal(expectedDiff)
+ assert.NoError(t, err)
+ bs, err := json.Marshal(diff)
+ assert.NoError(t, err)
+ assert.EqualValues(t, expectedBs, bs)
})
t.Run("empty branch, same results", func(t *testing.T) {
diff, err := GetDiffPreview(ctx.Repo.Repository, "", treePath, content)
assert.NoError(t, err)
- assert.EqualValues(t, expectedDiff, diff)
+ expectedBs, err := json.Marshal(expectedDiff)
+ assert.NoError(t, err)
+ bs, err := json.Marshal(diff)
+ assert.NoError(t, err)
+ assert.EqualValues(t, expectedBs, bs)
})
}
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/highlight"
+ "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames map[string]*models.UserCommit, previousCommits map[string]string) {
repoLink := ctx.Repo.RepoLink
+ language := ""
+
+ indexFilename, worktree, deleteTemporaryFile, err := ctx.Repo.GitRepo.ReadTreeToTemporaryIndex(ctx.Repo.CommitID)
+ if err == nil {
+ defer deleteTemporaryFile()
+
+ filename2attribute2info, err := ctx.Repo.GitRepo.CheckAttribute(git.CheckAttributeOpts{
+ CachedOnly: true,
+ Attributes: []string{"linguist-language", "gitlab-language"},
+ Filenames: []string{ctx.Repo.TreePath},
+ IndexFile: indexFilename,
+ WorkTree: worktree,
+ })
+ if err != nil {
+ log.Error("Unable to load attributes for %-v:%s. Error: %v", ctx.Repo.Repository, ctx.Repo.TreePath, err)
+ }
+
+ language = filename2attribute2info[ctx.Repo.TreePath]["linguist-language"]
+ if language == "" || language == "unspecified" {
+ language = filename2attribute2info[ctx.Repo.TreePath]["gitlab-language"]
+ }
+ if language == "unspecified" {
+ language = ""
+ }
+ }
var lines = make([]string, 0)
rows := make([]*blameRow, 0)
line += "\n"
}
fileName := fmt.Sprintf("%v", ctx.Data["FileName"])
- line = highlight.Code(fileName, line)
+ line = highlight.Code(fileName, language, line)
br.Code = gotemplate.HTML(line)
rows = append(rows, br)
lineNums := linesBytesCount(buf)
ctx.Data["NumLines"] = strconv.Itoa(lineNums)
ctx.Data["NumLinesSet"] = true
- ctx.Data["FileContent"] = highlight.File(lineNums, blob.Name(), buf)
+
+ language := ""
+
+ indexFilename, worktree, deleteTemporaryFile, err := ctx.Repo.GitRepo.ReadTreeToTemporaryIndex(ctx.Repo.CommitID)
+ if err == nil {
+ defer deleteTemporaryFile()
+
+ filename2attribute2info, err := ctx.Repo.GitRepo.CheckAttribute(git.CheckAttributeOpts{
+ CachedOnly: true,
+ Attributes: []string{"linguist-language", "gitlab-language"},
+ Filenames: []string{ctx.Repo.TreePath},
+ IndexFile: indexFilename,
+ WorkTree: worktree,
+ })
+ if err != nil {
+ log.Error("Unable to load attributes for %-v:%s. Error: %v", ctx.Repo.Repository, ctx.Repo.TreePath, err)
+ }
+
+ language = filename2attribute2info[ctx.Repo.TreePath]["linguist-language"]
+ if language == "" || language == "unspecified" {
+ language = filename2attribute2info[ctx.Repo.TreePath]["gitlab-language"]
+ }
+ if language == "unspecified" {
+ language = ""
+ }
+ }
+ ctx.Data["FileContent"] = highlight.File(lineNums, blob.Name(), language, buf)
}
if !isLFSFile {
if ctx.Repo.CanEnableEditor() {
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/process"
"code.gitea.io/gitea/modules/setting"
- "code.gitea.io/gitea/modules/util"
"github.com/sergi/go-diff/diffmatchpatch"
stdcharset "golang.org/x/net/html/charset"
// DiffSection represents a section of a DiffFile.
type DiffSection struct {
+ file *DiffFile
FileName string
Name string
Lines []*DiffLine
diff2 string
)
+ language := ""
+ if diffSection.file != nil {
+ language = diffSection.file.Language
+ }
+
// try to find equivalent diff line. ignore, otherwise
switch diffLine.Type {
case DiffLineSection:
case DiffLineAdd:
compareDiffLine = diffSection.GetLine(DiffLineDel, diffLine.RightIdx)
if compareDiffLine == nil {
- return template.HTML(highlight.Code(diffSection.FileName, diffLine.Content[1:]))
+ return template.HTML(highlight.Code(diffSection.FileName, language, diffLine.Content[1:]))
}
diff1 = compareDiffLine.Content
diff2 = diffLine.Content
case DiffLineDel:
compareDiffLine = diffSection.GetLine(DiffLineAdd, diffLine.LeftIdx)
if compareDiffLine == nil {
- return template.HTML(highlight.Code(diffSection.FileName, diffLine.Content[1:]))
+ return template.HTML(highlight.Code(diffSection.FileName, language, diffLine.Content[1:]))
}
diff1 = diffLine.Content
diff2 = compareDiffLine.Content
default:
if strings.IndexByte(" +-", diffLine.Content[0]) > -1 {
- return template.HTML(highlight.Code(diffSection.FileName, diffLine.Content[1:]))
+ return template.HTML(highlight.Code(diffSection.FileName, language, diffLine.Content[1:]))
}
- return template.HTML(highlight.Code(diffSection.FileName, diffLine.Content))
+ return template.HTML(highlight.Code(diffSection.FileName, language, diffLine.Content))
}
- diffRecord := diffMatchPatch.DiffMain(highlight.Code(diffSection.FileName, diff1[1:]), highlight.Code(diffSection.FileName, diff2[1:]), true)
+ diffRecord := diffMatchPatch.DiffMain(highlight.Code(diffSection.FileName, language, diff1[1:]), highlight.Code(diffSection.FileName, language, diff2[1:]), true)
diffRecord = diffMatchPatch.DiffCleanupEfficiency(diffRecord)
return diffToHTML(diffSection.FileName, diffRecord, diffLine.Type)
IsProtected bool
IsGenerated bool
IsVendored bool
+ Language string
}
// GetType returns type of diff file.
line := sb.String()
// Create a new section to represent this hunk
- curSection = &DiffSection{}
+ curSection = &DiffSection{file: curFile}
lastLeftIdx = -1
curFile.Sections = append(curFile.Sections, curSection)
rightLine++
if curSection == nil {
// Create a new section to represent this hunk
- curSection = &DiffSection{}
+ curSection = &DiffSection{file: curFile}
curFile.Sections = append(curFile.Sections, curSection)
lastLeftIdx = -1
}
}
if curSection == nil {
// Create a new section to represent this hunk
- curSection = &DiffSection{}
+ curSection = &DiffSection{file: curFile}
curFile.Sections = append(curFile.Sections, curSection)
lastLeftIdx = -1
}
lastLeftIdx = -1
if curSection == nil {
// Create a new section to represent this hunk
- curSection = &DiffSection{}
+ curSection = &DiffSection{file: curFile}
curFile.Sections = append(curFile.Sections, curSection)
}
curSection.Lines = append(curSection.Lines, diffLine)
var checker *git.CheckAttributeReader
if git.CheckGitVersionAtLeast("1.7.8") == nil {
- indexFilename, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(afterCommitID)
+ indexFilename, worktree, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(afterCommitID)
if err == nil {
defer deleteTemporaryFile()
- workdir, err := os.MkdirTemp("", "empty-work-dir")
- if err != nil {
- log.Error("Unable to create temporary directory: %v", err)
- return nil, err
- }
- defer func() {
- _ = util.RemoveAll(workdir)
- }()
checker = &git.CheckAttributeReader{
- Attributes: []string{"linguist-vendored", "linguist-generated"},
+ Attributes: []string{"linguist-vendored", "linguist-generated", "linguist-language", "gitlab-language"},
Repo: gitRepo,
IndexFile: indexFilename,
- WorkTree: workdir,
+ WorkTree: worktree,
}
ctx, cancel := context.WithCancel(git.DefaultContext)
if err := checker.Init(ctx); err != nil {
gotGenerated = generated == "false"
}
}
+ if language, has := attrs["linguist-language"]; has && language != "unspecified" && language != "" {
+ diffFile.Language = language
+ } else if language, has := attrs["gitlab-language"]; has && language != "unspecified" && language != "" {
+ diffFile.Language = language
+ }
} else {
log.Error("Unexpected error: %v", err)
}
func TestDiffToHTML_14231(t *testing.T) {
setting.Cfg = ini.Empty()
- diffRecord := diffMatchPatch.DiffMain(highlight.Code("main.v", " run()\n"), highlight.Code("main.v", " run(db)\n"), true)
+ diffRecord := diffMatchPatch.DiffMain(highlight.Code("main.v", "", " run()\n"), highlight.Code("main.v", "", " run(db)\n"), true)
diffRecord = diffMatchPatch.DiffCleanupEfficiency(diffRecord)
expected := ` <span class="n">run</span><span class="added-code"><span class="o">(</span><span class="n">db</span></span><span class="o">)</span>`