-
Notifications
You must be signed in to change notification settings - Fork 75
feat(cli): 支持安全下载单个远端文件 / safely download one remote file #485
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
Open
Jinghao-coding
wants to merge
1
commit into
raids-lab:main
Choose a base branch
from
Jinghao-coding:codex/issue-478-file-download
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,329 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| pathpkg "path" | ||
| "path/filepath" | ||
| "strings" | ||
| "unicode" | ||
|
|
||
| "github.com/raids-lab/crater/cli/internal/api" | ||
| "github.com/raids-lab/crater/cli/internal/clierror" | ||
| "github.com/raids-lab/crater/cli/internal/completion" | ||
| "github.com/raids-lab/crater/cli/internal/i18n" | ||
| "github.com/raids-lab/crater/cli/internal/output" | ||
| "github.com/raids-lab/crater/cli/pkg/errorcodes" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| var fileRemoteRoots = []string{"user", "public", "account"} | ||
|
|
||
| var fileCmd = &cobra.Command{ | ||
| Use: "file", | ||
| Short: "Download remote files", | ||
| Long: "Download files from user, public, and account storage spaces.", | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| if len(args) > 0 { | ||
| return errUnknownSubcommand(cmd, args[0]) | ||
| } | ||
| return cmd.Help() | ||
| }, | ||
| } | ||
|
|
||
| var fileDownloadCmd = &cobra.Command{ | ||
| Use: "download <remote-file> [local-path]", | ||
| Short: "Download one remote file", | ||
| Args: fileDownloadArgs, | ||
| RunE: runFileDownload, | ||
| } | ||
|
|
||
| type fileDownloadDeps struct { | ||
| client func() (api.FileDownloadClient, error) | ||
| stdout io.Writer | ||
| json bool | ||
| } | ||
|
|
||
| type fileDownloadInput struct { | ||
| remotePath string | ||
| localPath string | ||
| overwrite bool | ||
| } | ||
|
|
||
| type fileDownloadResult struct { | ||
| RemotePath string | ||
| LocalPath string | ||
| Bytes int64 | ||
| Overwrite bool | ||
| } | ||
|
|
||
| func fileDownloadArgs(cmd *cobra.Command, args []string) error { | ||
| if len(args) > 2 { | ||
| return errTooManyArgs(cmd, len(args), 2) | ||
| } | ||
| if len(args) == 0 { | ||
| return errUsageFromIssues([]usageIssue{{ | ||
| Code: errorcodes.ErrMissingRequiredFlag, | ||
| Message: i18n.T("err_missing_required_arg", i18n.T("file_label_remote_file"), "remote-file"), | ||
| Field: "remote-file", | ||
| }}) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func runFileDownload(cmd *cobra.Command, args []string) error { | ||
| return runFileDownloadWith(cmd, args, fileDownloadDeps{ | ||
| client: activeFileDownloadClient, | ||
| stdout: os.Stdout, | ||
| json: outputJSON, | ||
| }) | ||
| } | ||
|
|
||
| func activeFileDownloadClient() (api.FileDownloadClient, error) { | ||
| return activeAPIClient() | ||
| } | ||
|
|
||
| func runFileDownloadWith(cmd *cobra.Command, args []string, deps fileDownloadDeps) error { | ||
| remotePath, err := normalizeRemotePath(args[0], false) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if len(strings.Split(remotePath, "/")) < 2 { | ||
| return invalidFilePathIssue(i18n.T("err_file_path_not_file", args[0])) | ||
| } | ||
|
|
||
| localPath, err := resolveLocalDownloadPath(remotePath, args) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| overwrite, _ := cmd.Flags().GetBool("overwrite") | ||
| result, err := downloadToLocal(cmd.Context(), deps.client, fileDownloadInput{ | ||
| remotePath: remotePath, | ||
| localPath: localPath, | ||
| overwrite: overwrite, | ||
| }) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| return writeFileDownloadResult(deps.stdout, deps.json, result) | ||
| } | ||
|
|
||
| func resolveLocalDownloadPath(remotePath string, args []string) (string, error) { | ||
| if len(args) == 1 { | ||
| return pathpkg.Base(remotePath), nil | ||
| } | ||
| raw := args[1] | ||
| if raw == "" || strings.HasSuffix(raw, string(filepath.Separator)) { | ||
| return "", invalidLocalPathIssue(i18n.T("err_file_local_path_invalid", raw)) | ||
| } | ||
| cleaned := filepath.Clean(raw) | ||
| if cleaned == "." || cleaned == string(filepath.Separator) { | ||
| return "", invalidLocalPathIssue(i18n.T("err_file_local_path_invalid", raw)) | ||
| } | ||
| return cleaned, nil | ||
| } | ||
|
|
||
| func downloadToLocal( | ||
| ctx context.Context, | ||
| clientFactory func() (api.FileDownloadClient, error), | ||
| input fileDownloadInput, | ||
| ) (fileDownloadResult, error) { | ||
| existed, err := inspectDownloadTarget(input.localPath) | ||
| if err != nil { | ||
| return fileDownloadResult{}, err | ||
| } | ||
| if existed && !input.overwrite { | ||
| return fileDownloadResult{}, invalidLocalPathIssue(i18n.T("err_file_local_exists", input.localPath)) | ||
| } | ||
|
|
||
| parent := filepath.Dir(input.localPath) | ||
| prefix := "." + filepath.Base(input.localPath) + ".crater-" | ||
| temporary, err := os.CreateTemp(parent, prefix) | ||
| if err != nil { | ||
| return fileDownloadResult{}, localFileError("err_file_local_temp", input.localPath, err) | ||
| } | ||
| temporaryPath := temporary.Name() | ||
| temporaryOpen := true | ||
| defer func() { | ||
| if temporaryOpen { | ||
| _ = temporary.Close() | ||
| } | ||
| _ = os.Remove(temporaryPath) | ||
| }() | ||
|
|
||
| client, err := clientFactory() | ||
| if err != nil { | ||
| return fileDownloadResult{}, err | ||
| } | ||
| written, err := client.DownloadFile(ctx, input.remotePath, temporary) | ||
| if err != nil { | ||
| var destinationErr *api.DestinationWriteError | ||
| if errors.As(err, &destinationErr) { | ||
| return fileDownloadResult{}, localFileError("err_file_local_write", input.localPath, destinationErr.Cause) | ||
| } | ||
| return fileDownloadResult{}, cliErrFromAPI(err) | ||
| } | ||
| if err := temporary.Sync(); err != nil { | ||
| return fileDownloadResult{}, localFileError("err_file_local_sync", input.localPath, err) | ||
| } | ||
| if err := temporary.Close(); err != nil { | ||
| temporaryOpen = false | ||
| return fileDownloadResult{}, localFileError("err_file_local_close", input.localPath, err) | ||
| } | ||
| temporaryOpen = false | ||
|
|
||
| if input.overwrite { | ||
| if err := os.Rename(temporaryPath, input.localPath); err != nil { | ||
| return fileDownloadResult{}, localFileError("err_file_local_publish", input.localPath, err) | ||
| } | ||
| } else if err := os.Link(temporaryPath, input.localPath); err != nil { | ||
| if os.IsExist(err) { | ||
| return fileDownloadResult{}, invalidLocalPathIssue(i18n.T("err_file_local_exists", input.localPath)) | ||
| } | ||
| return fileDownloadResult{}, localFileError("err_file_local_publish", input.localPath, err) | ||
| } | ||
|
|
||
| return fileDownloadResult{ | ||
| RemotePath: input.remotePath, | ||
| LocalPath: input.localPath, | ||
| Bytes: written, | ||
| Overwrite: input.overwrite, | ||
| }, nil | ||
| } | ||
|
|
||
| func inspectDownloadTarget(localPath string) (bool, error) { | ||
| info, err := os.Lstat(localPath) | ||
| if err != nil { | ||
| if os.IsNotExist(err) { | ||
| return false, nil | ||
| } | ||
| return false, localFileError("err_file_local_stat", localPath, err) | ||
| } | ||
| if info.IsDir() { | ||
| return false, invalidLocalPathIssue(i18n.T("err_file_local_directory", localPath)) | ||
| } | ||
| return true, nil | ||
| } | ||
|
|
||
| func writeFileDownloadResult(writer io.Writer, jsonOutput bool, result fileDownloadResult) error { | ||
| if jsonOutput { | ||
| return output.WriteSuccessJSON(writer, output.SuccessEnvelope(map[string]interface{}{ | ||
| "remote_path": result.RemotePath, | ||
| "local_path": result.LocalPath, | ||
| "bytes": result.Bytes, | ||
| "overwrite": result.Overwrite, | ||
| })) | ||
| } | ||
| _, err := fmt.Fprintln(writer, i18n.T("file_download_success", result.RemotePath, result.LocalPath, result.Bytes)) | ||
| if err != nil { | ||
| return &clierror.Error{ | ||
| Category: errorcodes.CategorySystem, | ||
| Code: errorcodes.ErrCommandExecution, | ||
| Message: i18n.T("err_file_output", err.Error()), | ||
| Context: map[string]interface{}{"msg": err.Error()}, | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func localFileError(key, localPath string, cause error) *clierror.Error { | ||
| return &clierror.Error{ | ||
| Category: errorcodes.CategorySystem, | ||
| Code: errorcodes.ErrCommandExecution, | ||
| Message: i18n.T(key, localPath, cause.Error()), | ||
| Context: map[string]interface{}{ | ||
| "path": localPath, | ||
| "msg": cause.Error(), | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| func normalizeRemotePath(remotePath string, allowEmpty bool) (string, error) { | ||
| if remotePath == "" { | ||
| if allowEmpty { | ||
| return "", nil | ||
| } | ||
| return "", invalidFilePathIssue(i18n.T("err_file_path_invalid", remotePath)) | ||
| } | ||
| if strings.ContainsRune(remotePath, '\\') { | ||
| return "", invalidFilePathIssue(i18n.T("err_file_path_invalid", remotePath)) | ||
| } | ||
| for _, character := range remotePath { | ||
| if unicode.IsControl(character) { | ||
| return "", invalidFilePathIssue(i18n.T("err_file_path_invalid", remotePath)) | ||
| } | ||
| } | ||
|
|
||
| trimmed := strings.Trim(remotePath, "/") | ||
| rawSegments := strings.Split(trimmed, "/") | ||
| segments := make([]string, 0, len(rawSegments)) | ||
| for _, segment := range rawSegments { | ||
| if segment == ".." { | ||
| return "", invalidFilePathIssue(i18n.T("err_file_path_invalid", remotePath)) | ||
| } | ||
| if segment == "" || segment == "." { | ||
| continue | ||
| } | ||
| segments = append(segments, segment) | ||
| } | ||
| if len(segments) == 0 { | ||
| if allowEmpty { | ||
| return "", nil | ||
| } | ||
| return "", invalidFilePathIssue(i18n.T("err_file_path_invalid", remotePath)) | ||
| } | ||
| if !isFileRemoteRoot(segments[0]) { | ||
| return "", invalidFilePathIssue(i18n.T("err_file_path_root", remotePath)) | ||
| } | ||
| return strings.Join(segments, "/"), nil | ||
| } | ||
|
|
||
| func invalidFilePathIssue(message string) error { | ||
| return errUsageFromIssues([]usageIssue{{ | ||
| Code: errorcodes.ErrInvalidFlagValue, | ||
| Message: message, | ||
| Field: "remote-file", | ||
| }}) | ||
| } | ||
|
|
||
| func invalidLocalPathIssue(message string) error { | ||
| return errUsageFromIssues([]usageIssue{{ | ||
| Code: errorcodes.ErrInvalidFlagValue, | ||
| Message: message, | ||
| Field: "local-path", | ||
| }}) | ||
| } | ||
|
|
||
| func isFileRemoteRoot(value string) bool { | ||
| for _, root := range fileRemoteRoots { | ||
| if value == root { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| func fileRemoteRootCompleter(ctx completion.Context) ([]completion.Candidate, error) { | ||
| prefix := strings.ToLower(completion.CurrentWordPrefix(ctx)) | ||
| candidates := make([]completion.Candidate, 0, len(fileRemoteRoots)) | ||
| for _, root := range fileRemoteRoots { | ||
| if prefix != "" && !strings.HasPrefix(root, prefix) { | ||
| continue | ||
| } | ||
| candidates = append(candidates, completion.Candidate{ | ||
| Value: root, | ||
| Description: i18n.T("file_root_" + root + "_desc"), | ||
| }) | ||
| } | ||
| return candidates, nil | ||
| } | ||
|
|
||
| func init() { | ||
| fileDownloadCmd.Flags().Bool("overwrite", false, "Replace an existing local file") | ||
| fileCmd.AddCommand(fileDownloadCmd) | ||
| rootCmd.AddCommand(fileCmd) | ||
| completion.RegisterPositional([]string{"file", "download"}, 0, fileRemoteRootCompleter) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make command interruption cancel the request and unwind this cleanup path. The inspected entrypoint calls
rootCmd.Execute()without a signal-aware context (cli/main.go:13,cli/cmd/root.go:71), so pressing Ctrl-C during a large download invokes Go's default SIGINT termination and skips all deferred functions, leaving the potentially large.crater-*temporary file behind indefinitely.Useful? React with 👍 / 👎.