github.com/anonymouse64/snapd@v0.0.0-20210824153203-04c4c42d842d/osutil/unlink.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2018 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package osutil 21 22 import ( 23 "os" 24 "syscall" 25 26 "github.com/snapcore/snapd/osutil/sys" 27 ) 28 29 // UnlinkMany removes multiple files from a single directory. 30 // 31 // If dirname is not a directory, this will fail. 32 // 33 // This will abort at the first removal error (but ENOENT is ignored). 34 // 35 // Filenames must refer to files. They don't necessarily have to be 36 // relative paths to the given dirname, but if they aren't why are you 37 // using this function? 38 // 39 // Errors are *os.PathError, for convenience 40 func UnlinkMany(dirname string, filenames []string) error { 41 dirfd, err := syscall.Open(dirname, syscall.O_RDONLY|syscall.O_CLOEXEC|syscall.O_DIRECTORY|sys.O_PATH, 0) 42 if err != nil { 43 return &os.PathError{ 44 Op: "open", 45 Path: dirname, 46 Err: err, 47 } 48 } 49 defer syscall.Close(dirfd) 50 51 return unlinkMany(dirfd, filenames) 52 } 53 54 func unlinkMany(dirfd int, filenames []string) error { 55 var err error 56 for _, filename := range filenames { 57 if err = sysUnlinkat(dirfd, filename); err != nil && err != syscall.ENOENT { 58 return &os.PathError{ 59 Op: "remove", 60 Path: filename, 61 Err: err, 62 } 63 } 64 } 65 return nil 66 } 67 68 // UnlinkManyAt is like UnlinkMany but takes an open directory *os.File 69 // instead of a dirname. 70 func UnlinkManyAt(dir *os.File, filenames []string) error { 71 return unlinkMany(int(dir.Fd()), filenames) 72 }