golang.zx2c4.com/wireguard/windows@v0.5.4-0.20230123132234-dcc0eb72a04b/ui/filesave.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package ui
     7  
     8  import (
     9  	"os"
    10  
    11  	"github.com/lxn/walk"
    12  
    13  	"golang.zx2c4.com/wireguard/windows/l18n"
    14  )
    15  
    16  func writeFileWithOverwriteHandling(owner walk.Form, filePath string, write func(file *os.File) error) bool {
    17  	showError := func(err error) bool {
    18  		if err == nil {
    19  			return false
    20  		}
    21  
    22  		showErrorCustom(owner, l18n.Sprintf("Writing file failed"), err.Error())
    23  
    24  		return true
    25  	}
    26  
    27  	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o600)
    28  	if err != nil {
    29  		if os.IsExist(err) {
    30  			if walk.DlgCmdNo == walk.MsgBox(owner, l18n.Sprintf("Writing file failed"), l18n.Sprintf(`File ā€˜%s’ already exists.
    31  
    32  Do you want to overwrite it?`, filePath), walk.MsgBoxYesNo|walk.MsgBoxDefButton2|walk.MsgBoxIconWarning) {
    33  				return false
    34  			}
    35  
    36  			if file, err = os.Create(filePath); err != nil {
    37  				return !showError(err)
    38  			}
    39  		} else {
    40  			return !showError(err)
    41  		}
    42  	}
    43  	defer file.Close()
    44  
    45  	return !showError(write(file))
    46  }