Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Substitute variables in path names of template repos too #25294

Merged
merged 15 commits into from
Jun 20, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/content/doc/usage/template-repositories.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ a/b/c/d.json

In any file matched by the above globs, certain variables will be expanded.

Matching filenames and paths can also be expanded, and are conservatively sanitized to support cross-platform filesystems.

All variables must be of the form `$VAR` or `${VAR}`. To escape an expansion, use a double `$$`, such as `$$VAR` or `$${VAR}`

| Variable | Expands To | Transformable |
Expand Down
18 changes: 18 additions & 0 deletions modules/repository/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"

Expand Down Expand Up @@ -195,6 +196,14 @@ func generateRepoCommit(ctx context.Context, repo, templateRepo, generateRepo *r
0o644); err != nil {
return err
}

// Substitute filename variables
if err := os.Rename(path,
filepath.FromSlash(filepath.Join(tmpDirSlash,
fileNameEscape(generateExpansion(base, templateRepo, generateRepo))))); err != nil {
return err
}

break
}
}
Expand Down Expand Up @@ -353,3 +362,12 @@ func GenerateRepository(ctx context.Context, doer, owner *user_model.User, templ

return generateRepo, nil
}

// Escapes user input to valid OS filenames
//
// https://github.com/sindresorhus/filename-reserved-regex
func fileNameEscape(s string) string {
kdumontnu marked this conversation as resolved.
Show resolved Hide resolved
re := regexp.MustCompile(`(?i)[<>:\"/\\|?*\x{0000}-\x{001F}]|^(con|prn|aux|nul|com\d|lpt\d)$`)
kdumontnu marked this conversation as resolved.
Show resolved Hide resolved

return re.ReplaceAllString(s, "_")
}
silverwind marked this conversation as resolved.
Show resolved Hide resolved
9 changes: 9 additions & 0 deletions modules/repository/generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,12 @@ func TestGiteaTemplate(t *testing.T) {
})
}
}

func TestFileNameEscape(t *testing.T) {
assert.Equal(t, "test_CON", fileNameEscape("test_CON"))
assert.Equal(t, "http___localhost_3003_user_test.git", fileNameEscape("http://localhost:3003/user/test.git"))
assert.Equal(t, "_", fileNameEscape("CON"))
assert.Equal(t, "_", fileNameEscape("con"))
assert.Equal(t, "_", fileNameEscape("\u0000"))
assert.Equal(t, "目标", fileNameEscape("目标"))
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
x��AJ�0�a�9�\@Ij2��C�w�"��h�i���޷q���~�{_ � ����+c�)M���* rȉSD&��M��*�l�pm*��5fE_�P�8���D�QC�ɕa�o?��+\>���f۸����O��HH9G"x��{w��;��8
i�s�������0��9�/�IH
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1 +1 @@
aacbdfe9e1c4b47f60abe81849045fa4e96f1d75
2a83b349fa234131fc5db6f2a0498d3f4d3d6038
38 changes: 31 additions & 7 deletions tests/integration/repo_generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"

"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/tests"

"github.com/stretchr/testify/assert"
)

func testRepoGenerate(t *testing.T, session *TestSession, templateOwnerName, templateRepoName, generateOwnerName, generateRepoName string) *httptest.ResponseRecorder {
func testRepoGenerate(t *testing.T, session *TestSession, templateID, templateOwnerName, templateRepoName, generateOwnerName, generateRepoName string) *httptest.ResponseRecorder {
generateOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: generateOwnerName})

// Step0: check the existence of the generated repo
Expand All @@ -41,28 +43,50 @@ func testRepoGenerate(t *testing.T, session *TestSession, templateOwnerName, tem
_, exists = htmlDoc.doc.Find(fmt.Sprintf(".owner.dropdown .item[data-value=\"%d\"]", generateOwner.ID)).Attr("data-value")
assert.True(t, exists, fmt.Sprintf("Generate owner '%s' is not present in select box", generateOwnerName))
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"uid": fmt.Sprintf("%d", generateOwner.ID),
"repo_name": generateRepoName,
"git_content": "true",
"_csrf": htmlDoc.GetCSRF(),
"uid": fmt.Sprintf("%d", generateOwner.ID),
"repo_name": generateRepoName,
"repo_template": templateID,
"git_content": "true",
})
session.MakeRequest(t, req, http.StatusSeeOther)

// Step4: check the existence of the generated repo
req = NewRequestf(t, "GET", "/%s/%s", generateOwnerName, generateRepoName)
session.MakeRequest(t, req, http.StatusOK)

// Step5: check substituted values in Readme
req = NewRequestf(t, "GET", "/%s/%s/raw/branch/master/README.md", generateOwnerName, generateRepoName)
resp = session.MakeRequest(t, req, http.StatusOK)
body := fmt.Sprintf(`# %s Readme
Owner: %s
Link: /%s/%s
Clone URL: %s%s/%s.git`,
generateRepoName,
strings.ToUpper(generateOwnerName),
generateOwnerName,
generateRepoName,
setting.AppURL,
generateOwnerName,
generateRepoName)
assert.Equal(t, body, resp.Body.String())

// Step6: check substituted values in substituted file path ${REPO_NAME}
req = NewRequestf(t, "GET", "/%s/%s/raw/branch/master/%s.log", generateOwnerName, generateRepoName, generateRepoName)
resp = session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, generateRepoName, resp.Body.String())

return resp
}

func TestRepoGenerate(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
testRepoGenerate(t, session, "user27", "template1", "user1", "generated1")
testRepoGenerate(t, session, "44", "user27", "template1", "user1", "generated1")
}

func TestRepoGenerateToOrg(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user2")
testRepoGenerate(t, session, "user27", "template1", "user2", "generated2")
testRepoGenerate(t, session, "44", "user27", "template1", "user2", "generated2")
}