Skip to content

Commit 94c4953

Browse files
committed
Merge branch 'main' into custom-regexp-external-issues
2 parents 2639ced + 2ae45ce commit 94c4953

File tree

11 files changed

+232
-1
lines changed

11 files changed

+232
-1
lines changed

options/locale/locale_en-US.ini

+3
Original file line numberDiff line numberDiff line change
@@ -2289,6 +2289,9 @@ topic.done = Done
22892289
topic.count_prompt = You can not select more than 25 topics
22902290
topic.format_prompt = Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
22912291

2292+
find_file.go_to_file = Go to file
2293+
find_file.no_matching = No matching file found
2294+
22922295
error.csv.too_large = Can't render this file because it is too large.
22932296
error.csv.unexpected = Can't render this file because it contains an unexpected character in line %d and column %d.
22942297
error.csv.invalid_field_count = Can't render this file because it has a wrong number of fields in line %d.

routers/web/repo/find.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright 2022 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 repo
6+
7+
import (
8+
"net/http"
9+
10+
"code.gitea.io/gitea/modules/base"
11+
"code.gitea.io/gitea/modules/context"
12+
)
13+
14+
const (
15+
tplFindFiles base.TplName = "repo/find/files"
16+
)
17+
18+
// FindFiles render the page to find repository files
19+
func FindFiles(ctx *context.Context) {
20+
path := ctx.Params("*")
21+
ctx.Data["TreeLink"] = ctx.Repo.RepoLink + "/src/" + path
22+
ctx.Data["DataLink"] = ctx.Repo.RepoLink + "/tree-list/" + path
23+
ctx.HTML(http.StatusOK, tplFindFiles)
24+
}

routers/web/repo/treelist.go

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Copyright 2022 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 repo
6+
7+
import (
8+
"net/http"
9+
10+
"code.gitea.io/gitea/modules/base"
11+
"code.gitea.io/gitea/modules/context"
12+
"code.gitea.io/gitea/modules/git"
13+
14+
"github.com/go-enry/go-enry/v2"
15+
)
16+
17+
// TreeList get all files' entries of a repository
18+
func TreeList(ctx *context.Context) {
19+
tree, err := ctx.Repo.Commit.SubTree("/")
20+
if err != nil {
21+
ctx.ServerError("Repo.Commit.SubTree", err)
22+
return
23+
}
24+
25+
entries, err := tree.ListEntriesRecursive()
26+
if err != nil {
27+
ctx.ServerError("ListEntriesRecursive", err)
28+
return
29+
}
30+
entries.CustomSort(base.NaturalSortLess)
31+
32+
files := make([]string, 0, len(entries))
33+
for _, entry := range entries {
34+
if !isExcludedEntry(entry) {
35+
files = append(files, entry.Name())
36+
}
37+
}
38+
ctx.JSON(http.StatusOK, files)
39+
}
40+
41+
func isExcludedEntry(entry *git.TreeEntry) bool {
42+
if entry.IsDir() {
43+
return true
44+
}
45+
46+
if entry.IsSubModule() {
47+
return true
48+
}
49+
50+
if enry.IsVendor(entry.Name()) {
51+
return true
52+
}
53+
54+
return false
55+
}

routers/web/web.go

+6
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,12 @@ func RegisterRoutes(m *web.Route) {
831831
m.Group("/milestone", func() {
832832
m.Get("/{id}", repo.MilestoneIssuesAndPulls)
833833
}, reqRepoIssuesOrPullsReader, context.RepoRef())
834+
m.Get("/find/*", repo.FindFiles)
835+
m.Group("/tree-list", func() {
836+
m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.TreeList)
837+
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.TreeList)
838+
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.TreeList)
839+
})
834840
m.Get("/compare", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists, ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff)
835841
m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
836842
Get(ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff).

templates/repo/find/files.tmpl

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{{template "base/head" .}}
2+
<div class="page-content repository">
3+
{{template "repo/header" .}}
4+
<div class="ui container">
5+
<div class="df ac">
6+
<a href="{{$.RepoLink}}">{{.RepoName}}</a>
7+
<span class="mx-3">/</span>
8+
<div class="ui input f1">
9+
<input id="repo-file-find-input" type="text" autofocus data-url-data-link="{{.DataLink}}" data-url-tree-link="{{.TreeLink}}">
10+
</div>
11+
</div>
12+
<table id="repo-find-file-table" class="ui single line table">
13+
<tbody>
14+
</tbody>
15+
</table>
16+
<div id="repo-find-file-no-result" class="ui row center mt-5" hidden>
17+
<h3>{{.i18n.Tr "repo.find_file.no_matching"}}</h3>
18+
</div>
19+
</div>
20+
</div>
21+
{{template "base/footer" .}}

templates/repo/home.tmpl

+5
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,11 @@
7373
</a>
7474
</div>
7575
{{end}}
76+
<div class="fitted item mx-0">
77+
<a href="{{.BaseRepo.Link}}/find/{{.BranchNameSubURL}}" class="ui compact basic button">
78+
{{.i18n.Tr "repo.find_file.go_to_file"}}
79+
</a>
80+
</div>
7681
{{else}}
7782
<div class="fitted item"><span class="ui breadcrumb repo-path"><a class="section" href="{{.RepoLink}}/src/{{.BranchNameSubURL}}" title="{{.Repository.Name}}">{{EllipsisString .Repository.Name 30}}</a>{{range $i, $v := .TreeNames}}<span class="divider">/</span>{{if eq $i $l}}<span class="active section" title="{{$v}}">{{EllipsisString $v 30}}</span>{{else}}{{ $p := index $.Paths $i}}<span class="section"><a href="{{$.BranchLink}}/{{PathEscapeSegments $p}}" title="{{$v}}">{{EllipsisString $v 30}}</a></span>{{end}}{{end}}</span></div>
7883
{{end}}

web_src/js/features/repo-findfile.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import $ from 'jquery';
2+
3+
import {svg} from '../svg.js';
4+
import {strSubMatch} from '../utils.js';
5+
const {csrf} = window.config;
6+
7+
const threshold = 50;
8+
let files = [];
9+
let $repoFindFileInput, $repoFindFileTableBody, $repoFindFileNoResult;
10+
11+
function filterRepoFiles(filter) {
12+
const treeLink = $repoFindFileInput.attr('data-url-tree-link');
13+
$repoFindFileTableBody.empty();
14+
15+
const fileRes = [];
16+
if (filter) {
17+
for (let i = 0; i < files.length && fileRes.length < threshold; i++) {
18+
const subMatch = strSubMatch(files[i], filter);
19+
if (subMatch.length > 1) {
20+
fileRes.push(subMatch);
21+
}
22+
}
23+
} else {
24+
for (let i = 0; i < files.length && i < threshold; i++) {
25+
fileRes.push([files[i]]);
26+
}
27+
}
28+
29+
const tmplRow = `<tr><td><a></a></td></tr>`;
30+
31+
$repoFindFileNoResult.toggle(fileRes.length === 0);
32+
for (const matchRes of fileRes) {
33+
const $row = $(tmplRow);
34+
const $a = $row.find('a');
35+
$a.attr('href', `${treeLink}/${matchRes.join('')}`);
36+
const $octiconFile = $(svg('octicon-file')).addClass('mr-3');
37+
$a.append($octiconFile);
38+
// if the target file path is "abc/xyz", to search "bx", then the matchRes is ['a', 'b', 'c/', 'x', 'yz']
39+
// the matchRes[odd] is matched and highlighted to red.
40+
for (let j = 0; j < matchRes.length; j++) {
41+
if (!matchRes[j]) continue;
42+
const $span = $('<span>').text(matchRes[j]);
43+
if (j % 2 === 1) $span.addClass('ui text red');
44+
$a.append($span);
45+
}
46+
$repoFindFileTableBody.append($row);
47+
}
48+
}
49+
50+
async function loadRepoFiles() {
51+
files = await $.ajax({
52+
url: $repoFindFileInput.attr('data-url-data-link'),
53+
headers: {'X-Csrf-Token': csrf}
54+
});
55+
filterRepoFiles($repoFindFileInput.val());
56+
}
57+
58+
export function initFindFileInRepo() {
59+
$repoFindFileInput = $('#repo-file-find-input');
60+
if (!$repoFindFileInput.length) return;
61+
62+
$repoFindFileTableBody = $('#repo-find-file-table tbody');
63+
$repoFindFileNoResult = $('#repo-find-file-no-result');
64+
$repoFindFileInput.on('input', () => filterRepoFiles($repoFindFileInput.val()));
65+
66+
loadRepoFiles();
67+
}

web_src/js/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {initMarkupAnchors} from './markup/anchors.js';
2121
import {initNotificationCount, initNotificationsTable} from './features/notification.js';
2222
import {initRepoIssueContentHistory} from './features/repo-issue-content.js';
2323
import {initStopwatch} from './features/stopwatch.js';
24+
import {initFindFileInRepo} from './features/repo-findfile.js';
2425
import {initCommentContent, initMarkupContent} from './markup/content.js';
2526

2627
import {initUserAuthLinkAccountView, initUserAuthOauth2} from './features/user-auth.js';
@@ -124,6 +125,7 @@ $(document).ready(() => {
124125
initSshKeyFormParser();
125126
initStopwatch();
126127
initTableSort();
128+
initFindFileInRepo();
127129

128130
initAdminCommon();
129131
initAdminEmails();

web_src/js/svg.js

+2
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import octiconRepo from '../../public/img/svg/octicon-repo.svg';
1515
import octiconRepoForked from '../../public/img/svg/octicon-repo-forked.svg';
1616
import octiconRepoTemplate from '../../public/img/svg/octicon-repo-template.svg';
1717
import octiconTriangleDown from '../../public/img/svg/octicon-triangle-down.svg';
18+
import octiconFile from '../../public/img/svg/octicon-file.svg';
1819

1920
import Vue from 'vue';
2021

@@ -36,6 +37,7 @@ export const svgs = {
3637
'octicon-repo-forked': octiconRepoForked,
3738
'octicon-repo-template': octiconRepoTemplate,
3839
'octicon-triangle-down': octiconTriangleDown,
40+
'octicon-file': octiconFile,
3941
};
4042

4143
const parser = new DOMParser();

web_src/js/utils.js

+32
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,35 @@ export function parseIssueHref(href) {
5858
const [_, owner, repo, type, index] = /([^/]+)\/([^/]+)\/(issues|pulls)\/([0-9]+)/.exec(path) || [];
5959
return {owner, repo, type, index};
6060
}
61+
62+
// return the sub-match result as an array: [unmatched, matched, unmatched, matched, ...]
63+
// res[even] is unmatched, res[odd] is matched, see unit tests for examples
64+
export function strSubMatch(full, sub) {
65+
const res = [''];
66+
let i = 0, j = 0;
67+
for (; i < sub.length && j < full.length;) {
68+
while (j < full.length) {
69+
if (sub[i] === full[j]) {
70+
if (res.length % 2 !== 0) res.push('');
71+
res[res.length - 1] += full[j];
72+
j++;
73+
i++;
74+
} else {
75+
if (res.length % 2 === 0) res.push('');
76+
res[res.length - 1] += full[j];
77+
j++;
78+
break;
79+
}
80+
}
81+
}
82+
if (i !== sub.length) {
83+
// if the sub string doesn't match the full, only return the full as unmatched.
84+
return [full];
85+
}
86+
if (j < full.length) {
87+
// append remaining chars from full to result as unmatched
88+
if (res.length % 2 === 0) res.push('');
89+
res[res.length - 1] += full.substring(j);
90+
}
91+
return res;
92+
}

web_src/js/utils.test.js

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {
2-
basename, extname, isObject, uniq, stripTags, joinPaths, parseIssueHref,
2+
basename, extname, isObject, uniq, stripTags, joinPaths, parseIssueHref, strSubMatch,
33
} from './utils.js';
44

55
test('basename', () => {
@@ -84,3 +84,17 @@ test('parseIssueHref', () => {
8484
expect(parseIssueHref('https://example.com/sub/sub2/owner/repo/issues/1#hash')).toEqual({owner: 'owner', repo: 'repo', type: 'issues', index: '1'});
8585
expect(parseIssueHref('')).toEqual({owner: undefined, repo: undefined, type: undefined, index: undefined});
8686
});
87+
88+
89+
test('strSubMatch', () => {
90+
expect(strSubMatch('abc', '')).toEqual(['abc']);
91+
expect(strSubMatch('abc', 'a')).toEqual(['', 'a', 'bc']);
92+
expect(strSubMatch('abc', 'b')).toEqual(['a', 'b', 'c']);
93+
expect(strSubMatch('abc', 'c')).toEqual(['ab', 'c']);
94+
expect(strSubMatch('abc', 'ac')).toEqual(['', 'a', 'b', 'c']);
95+
expect(strSubMatch('abc', 'z')).toEqual(['abc']);
96+
expect(strSubMatch('abc', 'az')).toEqual(['abc']);
97+
98+
expect(strSubMatch('aabbcc', 'abc')).toEqual(['', 'a', 'a', 'b', 'b', 'c', 'c']);
99+
expect(strSubMatch('the/directory', 'hedir')).toEqual(['t', 'he', '/', 'dir', 'ectory']);
100+
});

0 commit comments

Comments
 (0)