aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/ui/filesave.go
blob: 4b5c294765318eaf30129e765b58af4fdd1c2deb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
 */

package ui

import (
	"fmt"
	"os"

	"github.com/lxn/walk"
)

func writeFileWithOverwriteHandling(owner walk.Form, filePath string, write func(file *os.File) error) bool {
	showError := func(err error) bool {
		if err == nil {
			return false
		}

		showErrorCustom(owner, "Writing file failed", err.Error())

		return true
	}

	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
	if err != nil {
		if os.IsExist(err) {
			if walk.DlgCmdNo == walk.MsgBox(owner, "Writing file failed", fmt.Sprintf(`File ‘%s’ already exists.

Do you want to overwrite it?`, filePath), walk.MsgBoxYesNo|walk.MsgBoxDefButton2|walk.MsgBoxIconWarning) {
				return false
			}

			if file, err = os.Create(filePath); err != nil {
				return !showError(err)
			}
		} else {
			return !showError(err)
		}
	}
	defer file.Close()

	return !showError(write(file))
}