Skip to content

Commit

Permalink
add branch switch (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
zizdlp authored Sep 29, 2024
1 parent e38f55d commit 2148663
Show file tree
Hide file tree
Showing 41 changed files with 318 additions and 205 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ ZBook does **not support online editing**. We believe that tools like Git in loc

ZBook plans to support the following features:

- [ ] Branch switching, allowing users to preview specific branches before merging into the main branch.
- [x] Branch switching, allowing users to preview specific branches before merging into the main branch.
- [ ] MkDocs-style theme extensions.
- [ ] GitHub-style admonitions.
- [ ] MkDocs-style collapsible admonitions.
Expand Down
2 changes: 1 addition & 1 deletion README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ ZBook 不支持**在线编辑**。我们认为 Git 在本地环境如 VS Code

zbook计划支持如下功能:

- [ ] 分支切换,动机是合并main分支之前,可以先查看特定分支的显示效果
- [x] 分支切换,动机是合并main分支之前,可以先查看特定分支的显示效果
- [ ] 类似mkdocs的风格扩展
- [ ] github 风格的admonition
- [ ] mkdocs 风格的折叠式admonition
Expand Down
1 change: 1 addition & 0 deletions zbook_backend/db/migration/000005_add_repos.up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ CREATE TABLE "repos" (
"theme_color" text NOT NULL CHECK (length(trim(theme_color)) > 0),
"created_at" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
"branch" varchar(255) NOT NULL DEFAULT '',
"fts_repo_en" TSVECTOR,
"fts_repo_zh" TSVECTOR
);
Expand Down
5 changes: 3 additions & 2 deletions zbook_backend/db/query/repo.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ INSERT INTO repos (
repo_description,
sync_token,
commit_id,
visibility_level
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
visibility_level,
branch
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
RETURNING *;

-- name: UpdateRepoConfig :exec
Expand Down
3 changes: 2 additions & 1 deletion zbook_backend/db/sqlc/comment.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions zbook_backend/db/sqlc/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

48 changes: 35 additions & 13 deletions zbook_backend/db/sqlc/repo.sql.go

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions zbook_backend/db/sqlc/tx_create_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,18 @@ func (store *SQLStore) CreateRepoTx(ctx context.Context, arg CreateRepoTxParams)
gitURL := util.GetGitURL(result.Repo.GitProtocol, result.Repo.GitHost, result.Repo.GitUsername, result.Repo.GitRepo)
if arg.GitAccessToken.Valid {
if result.Repo.GitHost == "github" {
err = operations.CloneWithToken(gitURL, cloneDir, arg.GitAccessToken.String)
err = operations.CloneWithToken(gitURL, cloneDir, arg.GitAccessToken.String, arg.Branch)
if err != nil {
return status.Errorf(codes.Internal, "clone repo failed: %s", err)
}
} else {
err = operations.CloneWithPassword(gitURL, cloneDir, arg.GitUsername, arg.GitAccessToken.String)
err = operations.CloneWithPassword(gitURL, cloneDir, arg.GitUsername, arg.GitAccessToken.String, arg.Branch)
if err != nil {
return status.Errorf(codes.Internal, "clone repo failed: %s", err)
}
}
} else {
err = operations.Clone(gitURL, cloneDir)
err = operations.Clone(gitURL, cloneDir, arg.Branch)
if err != nil {
return status.Errorf(codes.Internal, "clone repo failed: %s", err)
}
Expand Down
6 changes: 3 additions & 3 deletions zbook_backend/db/sqlc/tx_manual_sync_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,18 @@ func (store *SQLStore) ManualSyncRepoTx(ctx context.Context, arg ManualSyncRepoT
gitURL := util.GetGitURL(repo.GitProtocol, repo.GitHost, repo.GitUsername, repo.GitRepo)
if repo.GitAccessToken.Valid {
if repo.GitHost == "github" {
err = operations.CloneWithToken(gitURL, cloneDir, repo.GitAccessToken.String)
err = operations.CloneWithToken(gitURL, cloneDir, repo.GitAccessToken.String, repo.Branch)
if err != nil {
return status.Errorf(codes.Internal, "clone repo failed: %s", err)
}
} else {
err = operations.CloneWithPassword(gitURL, cloneDir, repo.GitUsername, repo.GitAccessToken.String)
err = operations.CloneWithPassword(gitURL, cloneDir, repo.GitUsername, repo.GitAccessToken.String, repo.Branch)
if err != nil {
return status.Errorf(codes.Internal, "clone repo failed: %s", err)
}
}
} else {
err = operations.Clone(gitURL, cloneDir)
err = operations.Clone(gitURL, cloneDir, repo.Branch)
if err != nil {
return status.Errorf(codes.Internal, "clone repo failed: %s", err)
}
Expand Down
6 changes: 6 additions & 0 deletions zbook_backend/doc/swagger/service_zbook_repo.swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,9 @@
},
"themeColor": {
"type": "string"
},
"branch": {
"type": "string"
}
},
"title": "1.CreateRepo"
Expand Down Expand Up @@ -691,6 +694,9 @@
},
"home": {
"type": "string"
},
"branch": {
"type": "string"
}
}
},
Expand Down
4 changes: 4 additions & 0 deletions zbook_backend/gapi/repo_create_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ func (server *Server) CreateRepo(ctx context.Context, req *rpcs.CreateRepoReques
VisibilityLevel: req.GetVisibilityLevel(),
ThemeSidebar: req.GetThemeSidebar(),
ThemeColor: req.GetThemeColor(),
Branch: req.Branch,
},
Username: authPayload.Username,
AfterCreate: func(cloneDir string, repoID int64, userID int64, addedFiles []string, modifiedFiles []string, deletedFiles []string) error {
Expand Down Expand Up @@ -83,6 +84,9 @@ func validateCreateRepoRequest(req *rpcs.CreateRepoRequest) (violations []*errde
if err := val.ValidateRepoThemeColor(req.GetThemeColor()); err != nil {
violations = append(violations, fieldViolation("theme_color", err))
}
if err := val.ValidateString(req.GetBranch(), 0, 255); err != nil {
violations = append(violations, fieldViolation("branch", err))
}

return violations
}
2 changes: 2 additions & 0 deletions zbook_backend/gapi/repo_list_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ func convertListRepos(reports []db.ListRepoRow, lang string) []*models.ListRepoI
UpdatedAt: timestamppb.New(reports[i].UpdatedAt),
CreatedAt: timestamppb.New(reports[i].CreatedAt),
Home: path,
Branch: reports[i].Branch,
},
)
}
Expand All @@ -159,6 +160,7 @@ func convertQueryRepo(reports []db.QueryRepoRow, lang string) []*models.ListRepo
UpdatedAt: timestamppb.New(reports[i].UpdatedAt),
CreatedAt: timestamppb.New(reports[i].CreatedAt),
Home: path,
Branch: reports[i].Branch,
},
)
}
Expand Down
2 changes: 2 additions & 0 deletions zbook_backend/gapi/repo_list_user_like_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ func convertListUserLikeRepo(repos []db.ListUserLikeRepoRow, lang string) []*mod
UpdatedAt: timestamppb.New(repos[i].UpdatedAt),
CreatedAt: timestamppb.New(repos[i].CreatedAt),
Home: path,
Branch: repos[i].Branch,
},
)
}
Expand All @@ -137,6 +138,7 @@ func convertQueryUserLikeRepo(repos []db.QueryUserLikeRepoRow, lang string) []*m
UpdatedAt: timestamppb.New(repos[i].UpdatedAt),
CreatedAt: timestamppb.New(repos[i].CreatedAt),
Home: path,
Branch: repos[i].Branch,
},
)
}
Expand Down
2 changes: 2 additions & 0 deletions zbook_backend/gapi/repo_list_user_own_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ func convertListUserOwnRepo(repos []db.ListUserOwnRepoRow, username string, lang
UpdatedAt: timestamppb.New(repos[i].UpdatedAt),
CreatedAt: timestamppb.New(repos[i].CreatedAt),
Home: path,
Branch: repos[i].Branch,
},
)
}
Expand Down Expand Up @@ -135,6 +136,7 @@ func convertQueryUserOwnRepo(repos []db.QueryUserOwnRepoRow, username string, la
UpdatedAt: timestamppb.New(repos[i].UpdatedAt),
CreatedAt: timestamppb.New(repos[i].CreatedAt),
Home: path,
Branch: repos[i].Branch,
},
)
}
Expand Down
40 changes: 29 additions & 11 deletions zbook_backend/operations/clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,15 @@ import (
)

// Clone clones a git repository from the specified URL into the specified directory.
func Clone(gitURL string, dir string) error {
// Create the git clone command with the directory parameter
cmd := exec.Command("git", "clone", gitURL, dir)
// Optionally, a specific branch can be cloned if provided.
func Clone(gitURL, dir, branch string) error {
// Create the git clone command with branch and directory parameter
args := []string{"clone", gitURL, dir}
if branch != "" {
args = append(args, "--branch", branch)
}

cmd := exec.Command("git", args...)

// Run the command and capture its output
output, err := cmd.CombinedOutput()
Expand All @@ -23,12 +29,18 @@ func Clone(gitURL string, dir string) error {

// CloneWithPassword clones a git repository from the specified URL into the specified directory.
// It supports cloning private repositories using either a personal access token (token)
// or basic authentication (username and password).
func CloneWithPassword(gitURL, dir, username, password string) error {
// or basic authentication (username and password). Optionally, a specific branch can be cloned if provided.
func CloneWithPassword(gitURL, dir, username, password, branch string) error {
// Construct the clone URL with username and password embedded
urlWithCredentials := embedCredentialsInURL(gitURL, username, password)
// Create the git clone command with the directory parameter
cmd := exec.Command("git", "clone", urlWithCredentials, dir)

// Create the git clone command with branch and directory parameter
args := []string{"clone", urlWithCredentials, dir}
if branch != "" {
args = append(args, "--branch", branch)
}

cmd := exec.Command("git", args...)

// Run the command and capture its output
output, err := cmd.CombinedOutput()
Expand All @@ -40,12 +52,18 @@ func CloneWithPassword(gitURL, dir, username, password string) error {
}

// CloneWithToken clones a git repository from the specified URL into the specified directory.
// It supports cloning private repositories using a personal access token.
func CloneWithToken(gitURL, dir, token string) error {
// It supports cloning private repositories using a personal access token. Optionally, a specific branch can be cloned if provided.
func CloneWithToken(gitURL, dir, token, branch string) error {
// Construct the clone URL with the token embedded
urlWithToken := embedTokenInURL(gitURL, token)
// Create the git clone command with the directory parameter
cmd := exec.Command("git", "clone", urlWithToken, dir)

// Create the git clone command with branch and directory parameter
args := []string{"clone", urlWithToken, dir}
if branch != "" {
args = append(args, "--branch", branch)
}

cmd := exec.Command("git", args...)

// Run the command and capture its output
output, err := cmd.CombinedOutput()
Expand Down
15 changes: 9 additions & 6 deletions zbook_backend/operations/clone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
func TestClone(t *testing.T) {
// 使用一个公开的 Git 仓库 URL 进行测试
gitURL := "https://github.com/zizdlp/zbook-user-guide.git"
branch := "main" // 你可以替换为要测试的具体分支

rsg := util.NewRandomStringGenerator()
randomString := rsg.RandomString(10)
Expand All @@ -21,8 +22,8 @@ func TestClone(t *testing.T) {
os.RemoveAll(cloneDir)
}

// 调用 Clone 函数
err := Clone(gitURL, cloneDir)
// 调用 Clone 函数并指定分支
err := Clone(gitURL, cloneDir, branch)

// 验证没有返回错误
require.NoError(t, err)
Expand All @@ -38,6 +39,7 @@ func TestCloneWithPassword(t *testing.T) {
t.Skip()
}
gitURL := "https://gitee.com/zizdlp/docs.git"
branch := "main" // 你可以替换为要测试的具体分支

rsg := util.NewRandomStringGenerator()
randomString := rsg.RandomString(10)
Expand All @@ -48,8 +50,8 @@ func TestCloneWithPassword(t *testing.T) {
}
password := os.Getenv("ZBOOK_TEST_PASSWORD")
username := "zizdlp"
// 调用 CloneWithPassword 函数
err := CloneWithPassword(gitURL, cloneDir, username, password)
// 调用 CloneWithPassword 函数并指定分支
err := CloneWithPassword(gitURL, cloneDir, username, password, branch)

// 验证没有返回错误
require.NoError(t, err)
Expand All @@ -65,6 +67,7 @@ func TestCloneWithToken(t *testing.T) {
t.Skip()
}
gitURL := "https://github.com/zizdlp/full-stack-guide.git"
branch := "main" // 你可以替换为要测试的具体分支

rsg := util.NewRandomStringGenerator()
randomString := rsg.RandomString(10)
Expand All @@ -74,8 +77,8 @@ func TestCloneWithToken(t *testing.T) {
os.RemoveAll(cloneDir)
}
token := os.Getenv("ZBOOK_TEST_TOKEN")
// 调用 CloneWithToken 函数
err := CloneWithToken(gitURL, cloneDir, token)
// 调用 CloneWithToken 函数并指定分支
err := CloneWithToken(gitURL, cloneDir, token, branch)

// 验证没有返回错误
require.NoError(t, err)
Expand Down
6 changes: 3 additions & 3 deletions zbook_backend/operations/get_diff_files_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestGetDiffFilesShouldOK(t *testing.T) {
}

// 调用 Clone 函数
err := Clone(gitURL, cloneDir)
err := Clone(gitURL, cloneDir, "")

// 验证没有返回错误
require.NoError(t, err)
Expand Down Expand Up @@ -76,7 +76,7 @@ func TestGetAllFilesShouldOK(t *testing.T) {
}

// 调用 Clone 函数
err := Clone(gitURL, cloneDir)
err := Clone(gitURL, cloneDir, "")

// 验证没有返回错误
require.NoError(t, err)
Expand Down Expand Up @@ -136,7 +136,7 @@ func TestGetDiffFilesRename(t *testing.T) {
}

// 调用 Clone 函数
err := Clone(gitURL, cloneDir)
err := Clone(gitURL, cloneDir, "")

// 验证没有返回错误
require.NoError(t, err)
Expand Down
2 changes: 1 addition & 1 deletion zbook_backend/operations/get_latest_commit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func TestGetLatestCommitShouldOK(t *testing.T) {
}

// 调用 Clone 函数
err := Clone(gitURL, cloneDir)
err := Clone(gitURL, cloneDir, "")

// 验证没有返回错误
require.NoError(t, err)
Expand Down
2 changes: 1 addition & 1 deletion zbook_backend/operations/list_markdowns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func TestListMarkdownFilesShouldOK(t *testing.T) {
}

// 调用 Clone 函数
err := Clone(gitURL, cloneDir)
err := Clone(gitURL, cloneDir, "")
// 验证没有返回错误
require.NoError(t, err)

Expand Down
Loading

0 comments on commit 2148663

Please sign in to comment.