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

Move tmp files for edit command next to config file. #386

Merged
merged 1 commit into from
Feb 7, 2024
Merged
Changes from all 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
22 changes: 20 additions & 2 deletions cmd/gmailctl/cmd/edit_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,7 @@ func copyToTmp(path string) (string, error) {
return "", errors.WithCause(err, config.ErrNotFound)
}

// Use the same extension as the original file.
tmp, err := os.CreateTemp("", fmt.Sprintf("gmailctl-*%s", filepath.Ext(path)))
tmp, err := createTmp(path)
if err != nil {
return "", fmt.Errorf("creating tmp file: %w", err)
}
Expand All @@ -156,6 +155,25 @@ func copyToTmp(path string) (string, error) {
return res, tmp.Close()
}

func createTmp(originalPath string) (*os.File, error) {
// First try in the same directory as the original file. This is useful to
// allow IDEs to access libraries imported from the same directory.
preferredDir := filepath.Dir(originalPath)
// Use the same extension as the original file.
pattern := fmt.Sprintf("gmailctl-tmp-*%s", filepath.Ext(originalPath))
tmp, err := os.CreateTemp(preferredDir, pattern)
if err == nil {
return tmp, nil
}

// Fall back to the system temporary directory.
tmp, err = os.CreateTemp("", pattern)
if err != nil {
return nil, fmt.Errorf("creating tmp file: %w", err)
}
return tmp, err
}

func spawnEditor(path string) error {
var editors []string
if edvar := os.Getenv("EDITOR"); edvar != "" {
Expand Down
Loading