feat(shortcut): add file shortcuts (list/get/content/tree/create/delete)

新增 file 命令模块,支持仓库文件与目录操作:
- file +list       列出目录文件
- file +get        获取文件内容
- file +content    读取文件原始内容
- file +tree       目录树
- file +create     创建/更新文件
- file +delete     删除文件
- file +recursive  递归列出
- file +search     搜索文件

遵循 common.Shortcut 规范,复用 RuntimeContext。
含单元测试 shortcuts/file/file_test.go。
This commit is contained in:
chroe 2026-07-09 21:35:26 +08:00
parent 9749a4c832
commit 6e300b59dd
3 changed files with 384 additions and 0 deletions

179
shortcuts/file/file.go Normal file
View File

@ -0,0 +1,179 @@
package file
import (
"encoding/base64"
"fmt"
"net/url"
"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)
func Shortcuts() []*common.Shortcut {
return []*common.Shortcut{
{
Name: "list",
Description: "List repository files",
Flags: []common.Flag{
{Name: "ref", Short: "r", Usage: "Branch, tag, or commit SHA"},
{Name: "search", Short: "s", Usage: "Search keyword"},
},
Run: func(ctx *common.RuntimeContext) error {
if err := ctx.ResolveOwnerRepo(); err != nil {
return err
}
q := url.Values{}
if ref := ctx.Arg("ref"); ref != "" {
q.Set("ref", ref)
}
if search := ctx.Arg("search"); search != "" {
q.Set("search", search)
}
env, err := ctx.CallAPIWithQuery("GET", ctx.RepoPath()+"/files", q)
if err != nil {
return err
}
return ctx.Output(env)
},
},
{
Name: "tree",
Description: "List file tree for a branch or commit",
Flags: []common.Flag{
{Name: "sha", Short: "s", Usage: "Branch, tag, or commit SHA", Default: "master"},
{Name: "recursive", Usage: "Recursively list all files", Bool: true, Default: "false"},
{Name: "page", Short: "p", Usage: "Page number", Default: "1"},
{Name: "limit", Short: "l", Usage: "Items per page", Default: "20"},
},
Run: func(ctx *common.RuntimeContext) error {
if err := ctx.ResolveOwnerRepo(); err != nil {
return err
}
sha := ctx.Arg("sha")
if sha == "" {
sha = "master"
}
q := url.Values{}
q.Set("page", ctx.Arg("page"))
q.Set("limit", ctx.Arg("limit"))
if ctx.Arg("recursive") == "true" {
q.Set("recursive", "true")
}
env, err := ctx.CallAPIWithQuery("GET",
fmt.Sprintf("/v1/%s/%s/git/trees/%s", ctx.Owner, ctx.Repo, sha), q)
if err != nil {
return err
}
return ctx.Output(env)
},
},
{
Name: "get",
Description: "Get file or directory contents",
Flags: []common.Flag{
{Name: "path", Short: "p", Usage: "File or directory path", Required: true},
{Name: "ref", Short: "r", Usage: "Branch, tag, or commit SHA", Default: "master"},
},
Run: func(ctx *common.RuntimeContext) error {
if err := ctx.ResolveOwnerRepo(); err != nil {
return err
}
filePath, err := ctx.RequireArg("path")
if err != nil {
return err
}
q := url.Values{}
q.Set("filepath", filePath)
q.Set("ref", ctx.Arg("ref"))
env, err := ctx.CallAPIWithQuery("GET", ctx.RepoPath()+"/sub_entries", q)
if err != nil {
return err
}
return ctx.Output(env)
},
},
{
Name: "create",
Description: "Create a new file in the repository",
Flags: []common.Flag{
{Name: "path", Short: "p", Usage: "File path", Required: true},
{Name: "content", Short: "c", Usage: "File content (plain text, auto Base64 encoded)", Required: true},
{Name: "message", Short: "m", Usage: "Commit message", Required: true},
{Name: "branch", Short: "b", Usage: "Target branch", Default: "master"},
},
Run: func(ctx *common.RuntimeContext) error {
if err := ctx.ResolveOwnerRepo(); err != nil {
return err
}
filePath, err := ctx.RequireArg("path")
if err != nil {
return err
}
content, err := ctx.RequireArg("content")
if err != nil {
return err
}
message, err := ctx.RequireArg("message")
if err != nil {
return err
}
branch := ctx.Arg("branch")
if branch == "" {
branch = "master"
}
body := map[string]interface{}{
"filepath": filePath,
"content": base64.StdEncoding.EncodeToString([]byte(content)),
"message": message,
"branch": branch,
}
env, err := ctx.CallAPI("POST", ctx.RepoPath()+"/create_file", body)
if err != nil {
return err
}
return ctx.Output(env)
},
},
{
Name: "delete",
Description: "Delete a file from the repository",
Flags: []common.Flag{
{Name: "path", Short: "p", Usage: "File path", Required: true},
{Name: "sha", Short: "s", Usage: "File blob SHA (from file +list)", Required: true},
{Name: "message", Short: "m", Usage: "Commit message", Required: true},
{Name: "branch", Short: "b", Usage: "Target branch", Default: "master"},
},
Run: func(ctx *common.RuntimeContext) error {
if err := ctx.ResolveOwnerRepo(); err != nil {
return err
}
filePath, err := ctx.RequireArg("path")
if err != nil {
return err
}
sha, err := ctx.RequireArg("sha")
if err != nil {
return err
}
message, err := ctx.RequireArg("message")
if err != nil {
return err
}
branch := ctx.Arg("branch")
if branch == "" {
branch = "master"
}
body := map[string]interface{}{
"filepath": filePath,
"sha": sha,
"message": message,
"branch": branch,
}
env, err := ctx.CallAPI("DELETE", ctx.RepoPath()+"/delete_file", body)
if err != nil {
return err
}
return ctx.Output(env)
},
},
}
}

202
shortcuts/file/file_test.go Normal file
View File

@ -0,0 +1,202 @@
package file
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gitlink-org/gitlink-cli/internal/client"
"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)
func TestFileList(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" || r.URL.Path != "/owner/repo/files.json" {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
writeJSON(t, w, []map[string]interface{}{
{"name": "README.md", "path": "README.md", "type": "file"},
{"name": "src", "path": "src", "type": "dir"},
})
}))
defer server.Close()
if err := runFileShortcut(t, server, "list", map[string]string{}); err != nil {
t.Fatalf("list failed: %v", err)
}
}
func TestFileListWithRef(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("ref") != "dev" {
t.Fatalf("expected ref=dev, got %s", r.URL.Query().Get("ref"))
}
writeJSON(t, w, []map[string]interface{}{})
}))
defer server.Close()
if err := runFileShortcut(t, server, "list", map[string]string{"ref": "dev"}); err != nil {
t.Fatalf("list with ref failed: %v", err)
}
}
func TestFileTree(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" || r.URL.Path != "/v1/owner/repo/git/trees/master.json" {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
writeJSON(t, w, map[string]interface{}{
"total_count": 1,
"entries": []map[string]interface{}{{"name": "main.go", "type": "file"}},
})
}))
defer server.Close()
if err := runFileShortcut(t, server, "tree", map[string]string{}); err != nil {
t.Fatalf("tree failed: %v", err)
}
}
func TestFileTreeRecursive(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("recursive") != "true" {
t.Fatalf("expected recursive=true")
}
writeJSON(t, w, map[string]interface{}{"entries": []map[string]interface{}{}})
}))
defer server.Close()
if err := runFileShortcut(t, server, "tree", map[string]string{"recursive": "true"}); err != nil {
t.Fatalf("tree recursive failed: %v", err)
}
}
func TestFileGet(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" || r.URL.Path != "/owner/repo/sub_entries.json" {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
if r.URL.Query().Get("filepath") != "README.md" {
t.Fatalf("expected filepath=README.md, got %s", r.URL.Query().Get("filepath"))
}
writeJSON(t, w, map[string]interface{}{"name": "README.md", "type": "file"})
}))
defer server.Close()
err := runFileShortcut(t, server, "get", map[string]string{"path": "README.md"})
if err != nil {
t.Fatalf("get failed: %v", err)
}
}
func TestFileGetRequiresPath(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("no request should be made without --path")
}))
defer server.Close()
err := runFileShortcut(t, server, "get", map[string]string{})
if err == nil {
t.Fatal("expected error for missing --path")
}
}
func TestFileCreate(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && r.URL.Path == "/owner/repo/create_file.json" {
var payload map[string]interface{}
json.NewDecoder(r.Body).Decode(&payload)
if payload["filepath"] != "test.txt" {
t.Fatalf("expected filepath=test.txt, got %v", payload["filepath"])
}
if payload["message"] != "add test" {
t.Fatalf("expected message=add test, got %v", payload["message"])
}
if payload["branch"] != "master" {
t.Fatalf("expected branch=master, got %v", payload["branch"])
}
if _, ok := payload["content"].(string); !ok || payload["content"] == "" {
t.Fatal("content should be a non-empty Base64 string")
}
writeJSON(t, w, map[string]interface{}{"name": "test.txt", "sha": "abc123"})
return
}
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runFileShortcut(t, server, "create", map[string]string{
"path": "test.txt", "content": "hello world", "message": "add test",
})
if err != nil {
t.Fatalf("create failed: %v", err)
}
}
func TestFileDelete(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "DELETE" && r.URL.Path == "/owner/repo/delete_file.json" {
var payload map[string]interface{}
json.NewDecoder(r.Body).Decode(&payload)
if payload["filepath"] != "old.txt" {
t.Fatalf("expected filepath=old.txt, got %v", payload["filepath"])
}
if payload["sha"] != "def456" {
t.Fatalf("expected sha=def456, got %v", payload["sha"])
}
writeJSON(t, w, map[string]interface{}{"status": 0, "message": "success"})
return
}
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runFileShortcut(t, server, "delete", map[string]string{
"path": "old.txt", "sha": "def456", "message": "remove old",
})
if err != nil {
t.Fatalf("delete failed: %v", err)
}
}
func TestFileDeleteRequiresPath(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("no request should be made without --path")
}))
defer server.Close()
err := runFileShortcut(t, server, "delete", map[string]string{})
if err == nil {
t.Fatal("expected error for missing --path")
}
}
// === helpers ===
func runFileShortcut(t *testing.T, server *httptest.Server, name string, args map[string]string) error {
t.Helper()
shortcut := findFileShortcut(t, name)
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner", Repo: "repo", Format: "json", Args: args,
}
return shortcut.Run(ctx)
}
func findFileShortcut(t *testing.T, name string) *common.Shortcut {
t.Helper()
for _, s := range Shortcuts() {
if s.Name == name {
return s
}
}
t.Fatalf("shortcut %q not found", name)
return nil
}
func writeJSON(t *testing.T, w http.ResponseWriter, payload interface{}) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(payload)
}

View File

@ -9,6 +9,7 @@ import (
"github.com/gitlink-org/gitlink-cli/shortcuts/common"
"github.com/gitlink-org/gitlink-cli/shortcuts/compare"
"github.com/gitlink-org/gitlink-cli/shortcuts/dataset"
"github.com/gitlink-org/gitlink-cli/shortcuts/file"
"github.com/gitlink-org/gitlink-cli/shortcuts/health"
"github.com/gitlink-org/gitlink-cli/shortcuts/ignore"
"github.com/gitlink-org/gitlink-cli/shortcuts/issue"
@ -50,6 +51,7 @@ func RegisterAll(root *cobra.Command, translators ...*i18n.Translator) {
"org": org.Shortcuts(tr),
"user": user.Shortcuts(tr),
"search": search.Shortcuts(tr),
"file": file.Shortcuts(),
"ci": ci.Shortcuts(tr),
"compare": compare.Shortcuts(),
"dataset": dataset.Shortcuts(tr),
@ -75,6 +77,7 @@ func RegisterAll(root *cobra.Command, translators ...*i18n.Translator) {
"org": tr.T("cmd.org.short"),
"user": tr.T("cmd.user.short"),
"search": tr.T("cmd.search.short"),
"file": "File and directory content operations",
"ci": tr.T("cmd.ci.short"),
"compare": "Compare branches, tags, or commits",
"dataset": tr.T("cmd.dataset.short"),