├── .github └── workflows │ └── main.yml ├── .golangci.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── doc.go ├── example_test.go ├── go.mod ├── maybe ├── doc.go ├── maybe_unix.go └── maybe_windows.go ├── option.go ├── symlink_test.go ├── tempfile.go ├── tempfile_linux_test.go ├── tempfile_test.go ├── writefile.go └── writefile_test.go /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - master 7 | tags: 8 | - v* 9 | jobs: 10 | test: 11 | strategy: 12 | matrix: 13 | go-version: 14 | - 1.18.x 15 | - 1.19.x 16 | os: 17 | - macos-latest 18 | - ubuntu-latest 19 | - windows-latest 20 | runs-on: ${{ matrix.os }} 21 | steps: 22 | - name: Set up Go 23 | uses: actions/setup-go@v3 24 | with: 25 | go-version: ${{ matrix.go-version }} 26 | - name: Cache Go modules 27 | uses: actions/cache@v1 28 | with: 29 | path: ~/go/pkg/mod 30 | key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 31 | restore-keys: | 32 | ${{ runner.os }}-go- 33 | - name: Checkout 34 | uses: actions/checkout@v3 35 | - name: Linux test 36 | if: matrix.os == 'ubuntu-latest' 37 | run: | 38 | go test -c -race . 39 | sudo ./renameio.test -test.v 40 | - name: Non-Linux test 41 | if: matrix.os != 'ubuntu-latest' 42 | run: go test . 43 | lint: 44 | runs-on: ubuntu-latest 45 | steps: 46 | - name: Set up Go 47 | uses: actions/setup-go@v3 48 | with: 49 | go-version: 1.19.x 50 | - name: Checkout 51 | uses: actions/checkout@v3 52 | - name: Lint 53 | uses: golangci/golangci-lint-action@v3 54 | with: 55 | version: latest 56 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | linters: 2 | disable: 3 | - errcheck 4 | enable: 5 | - gofmt 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://github.com/google/renameio/workflows/Test/badge.svg)](https://github.com/google/renameio/actions?query=workflow%3ATest) 2 | [![PkgGoDev](https://pkg.go.dev/badge/github.com/google/renameio)](https://pkg.go.dev/github.com/google/renameio) 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/google/renameio)](https://goreportcard.com/report/github.com/google/renameio) 4 | 5 | The `renameio` Go package provides a way to atomically create or replace a file or 6 | symbolic link. 7 | 8 | ## Atomicity vs durability 9 | 10 | `renameio` concerns itself *only* with atomicity, i.e. making sure applications 11 | never see unexpected file content (a half-written file, or a 0-byte file). 12 | 13 | As a practical example, consider https://manpages.debian.org/: if there is a 14 | power outage while the site is updating, we are okay with losing the manpages 15 | which were being rendered at the time of the power outage. They will be added in 16 | a later run of the software. We are not okay with having a manpage replaced by a 17 | 0-byte file under any circumstances, though. 18 | 19 | ## Advantages of this package 20 | 21 | There are other packages for atomically replacing files, and sometimes ad-hoc 22 | implementations can be found in programs. 23 | 24 | A naive approach to the problem is to create a temporary file followed by a call 25 | to `os.Rename()`. However, there are a number of subtleties which make the 26 | correct sequence of operations hard to identify: 27 | 28 | * The temporary file should be removed when an error occurs, but a remove must 29 | not be attempted if the rename succeeded, as a new file might have been 30 | created with the same name. This renders a throwaway `defer 31 | os.Remove(t.Name())` insufficient; state must be kept. 32 | 33 | * The temporary file must be created on the same file system (same mount point) 34 | for the rename to work, but the TMPDIR environment variable should still be 35 | respected, e.g. to direct temporary files into a separate directory outside of 36 | the webserver’s document root but on the same file system. 37 | 38 | * On POSIX operating systems, the 39 | [`fsync`](https://manpages.debian.org/stretch/manpages-dev/fsync.2) system 40 | call must be used to ensure that the `os.Rename()` call will not result in a 41 | 0-length file. 42 | 43 | This package attempts to get all of these details right, provides an intuitive, 44 | yet flexible API and caters to use-cases where high performance is required. 45 | 46 | ## Major changes in v2 47 | 48 | With major version renameio/v2, `renameio.WriteFile` changes the way that 49 | permissions are handled. Before version 2, files were created with the 50 | permissions passed to the function, ignoring the 51 | [umask](https://en.wikipedia.org/wiki/Umask). From version 2 onwards, these 52 | permissions are further modified by process' umask (usually the user's 53 | preferred umask). 54 | 55 | If you were relying on the umask being ignored, add the 56 | `renameio.IgnoreUmask()` option to your `renameio.WriteFile` calls when 57 | upgrading to v2. 58 | 59 | ## Windows support 60 | 61 | It is [not possible to reliably write files atomically on 62 | Windows](https://github.com/golang/go/issues/22397#issuecomment-498856679), and 63 | [`chmod` is not reliably supported by the Go standard library on 64 | Windows](https://github.com/google/renameio/issues/17). 65 | 66 | As it is not possible to provide a correct implementation, this package does not 67 | export any functions on Windows. 68 | 69 | ## Disclaimer 70 | 71 | This is not an official Google product (experimental or otherwise), it 72 | is just code that happens to be owned by Google. 73 | 74 | This project is not affiliated with the Go project. 75 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package renameio provides a way to atomically create or replace a file or 16 | // symbolic link. 17 | // 18 | // Caveat: this package requires the file system rename(2) implementation to be 19 | // atomic. Notably, this is not the case when using NFS with multiple clients: 20 | // https://stackoverflow.com/a/41396801 21 | package renameio 22 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build !windows 16 | // +build !windows 17 | 18 | package renameio_test 19 | 20 | import ( 21 | "fmt" 22 | "log" 23 | 24 | "github.com/google/renameio/v2" 25 | ) 26 | 27 | func ExampleTempFile_justone() { 28 | persist := func(temperature float64) error { 29 | t, err := renameio.TempFile("", "/srv/www/metrics.txt") 30 | if err != nil { 31 | return err 32 | } 33 | defer t.Cleanup() 34 | if _, err := fmt.Fprintf(t, "temperature_degc %f\n", temperature); err != nil { 35 | return err 36 | } 37 | return t.CloseAtomicallyReplace() 38 | } 39 | // Thanks to the write package, a webserver exposing /srv/www never 40 | // serves an incomplete or missing file. 41 | if err := persist(31.2); err != nil { 42 | log.Fatal(err) 43 | } 44 | } 45 | 46 | func ExampleTempFile_many() { 47 | // Prepare for writing files to /srv/www, effectively caching calls to 48 | // TempDir which TempFile would otherwise need to make. 49 | dir := renameio.TempDir("/srv/www") 50 | persist := func(temperature float64) error { 51 | t, err := renameio.TempFile(dir, "/srv/www/metrics.txt") 52 | if err != nil { 53 | return err 54 | } 55 | defer t.Cleanup() 56 | if _, err := fmt.Fprintf(t, "temperature_degc %f\n", temperature); err != nil { 57 | return err 58 | } 59 | return t.CloseAtomicallyReplace() 60 | } 61 | 62 | // Imagine this was an endless loop, reading temperature sensor values. 63 | // Thanks to the write package, a webserver exposing /srv/www never 64 | // serves an incomplete or missing file. 65 | for { 66 | if err := persist(31.2); err != nil { 67 | log.Fatal(err) 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/google/renameio/v2 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /maybe/doc.go: -------------------------------------------------------------------------------- 1 | // Package maybe provides a way to atomically create or replace a file, if 2 | // technically possible. 3 | package maybe 4 | -------------------------------------------------------------------------------- /maybe/maybe_unix.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | // +build !windows 3 | 4 | package maybe 5 | 6 | import ( 7 | "os" 8 | 9 | "github.com/google/renameio/v2" 10 | ) 11 | 12 | // WriteFile mirrors ioutil.WriteFile. On Linux it uses renameio.WriteFile to 13 | // create or replace an existing file with the same name atomically. On Windows 14 | // files cannot be written atomically, so this function falls back to 15 | // ioutil.WriteFile, which does not write the file atomically and ignores most 16 | // permission bits. See https://github.com/google/renameio/issues/1 and 17 | // https://github.com/golang/go/issues/22397#issuecomment-498856679 for 18 | // discussion. 19 | // 20 | // Prefer using renameio.WriteFile instead so that you get an error if atomic 21 | // replacement is not possible on the runtime platform. maybe.WriteFile is meant 22 | // as a convenience wrapper if you are okay with atomic replacement not being 23 | // supported by the runtime platform. 24 | func WriteFile(filename string, data []byte, perm os.FileMode) error { 25 | return renameio.WriteFile(filename, data, perm) 26 | } 27 | -------------------------------------------------------------------------------- /maybe/maybe_windows.go: -------------------------------------------------------------------------------- 1 | package maybe 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | ) 7 | 8 | // WriteFile mirrors ioutil.WriteFile. On Linux it uses renameio.WriteFile to 9 | // create or replace an existing file with the same name atomically. On Windows 10 | // files cannot be written atomically, so this function falls back to 11 | // ioutil.WriteFile, which does not write the file atomically and ignores most 12 | // permission bits. See https://github.com/google/renameio/issues/1 and 13 | // https://github.com/golang/go/issues/22397#issuecomment-498856679 for 14 | // discussion. 15 | // 16 | // Prefer using renameio.WriteFile instead so that you get an error if atomic 17 | // replacement is not possible on the runtime platform. maybe.WriteFile is meant 18 | // as a convenience wrapper if you are okay with atomic replacement not being 19 | // supported by the runtime platform. 20 | func WriteFile(filename string, data []byte, perm os.FileMode) error { 21 | return ioutil.WriteFile(filename, data, perm) 22 | } 23 | -------------------------------------------------------------------------------- /option.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build !windows 16 | // +build !windows 17 | 18 | package renameio 19 | 20 | import "os" 21 | 22 | // Option is the interface implemented by all configuration function return 23 | // values. 24 | type Option interface { 25 | apply(*config) 26 | } 27 | 28 | type optionFunc func(*config) 29 | 30 | func (fn optionFunc) apply(cfg *config) { 31 | fn(cfg) 32 | } 33 | 34 | // WithTempDir configures the directory to use for temporary, uncommitted 35 | // files. Suitable for using a cached directory from 36 | // TempDir(filepath.Base(path)). 37 | func WithTempDir(dir string) Option { 38 | return optionFunc(func(cfg *config) { 39 | cfg.dir = dir 40 | }) 41 | } 42 | 43 | // WithPermissions sets the permissions for the target file while respecting 44 | // the umask(2). Bits set in the umask are removed from the permissions given 45 | // unless IgnoreUmask is used. 46 | func WithPermissions(perm os.FileMode) Option { 47 | perm &= os.ModePerm 48 | return optionFunc(func(cfg *config) { 49 | cfg.createPerm = perm 50 | }) 51 | } 52 | 53 | // IgnoreUmask causes the permissions configured using WithPermissions to be 54 | // applied directly without applying the umask. 55 | func IgnoreUmask() Option { 56 | return optionFunc(func(cfg *config) { 57 | cfg.ignoreUmask = true 58 | }) 59 | } 60 | 61 | // WithStaticPermissions sets the permissions for the target file ignoring the 62 | // umask(2). This is equivalent to calling Chmod() on the file handle or using 63 | // WithPermissions in combination with IgnoreUmask. 64 | func WithStaticPermissions(perm os.FileMode) Option { 65 | perm &= os.ModePerm 66 | return optionFunc(func(cfg *config) { 67 | cfg.chmod = &perm 68 | }) 69 | } 70 | 71 | // WithExistingPermissions configures the file creation to try to use the 72 | // permissions from an already existing target file. If the target file doesn't 73 | // exist yet or is not a regular file the default permissions are used unless 74 | // overridden using WithPermissions or WithStaticPermissions. 75 | func WithExistingPermissions() Option { 76 | return optionFunc(func(c *config) { 77 | c.attemptPermCopy = true 78 | }) 79 | } 80 | 81 | // WithReplaceOnClose causes PendingFile.Close() to actually call 82 | // CloseAtomicallyReplace(). This means PendingFile implements io.Closer while 83 | // maintaining atomicity per default. 84 | func WithReplaceOnClose() Option { 85 | return optionFunc(func(c *config) { 86 | c.renameOnClose = true 87 | }) 88 | } 89 | -------------------------------------------------------------------------------- /symlink_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build !windows 16 | // +build !windows 17 | 18 | package renameio 19 | 20 | import ( 21 | "bytes" 22 | "io/ioutil" 23 | "os" 24 | "path/filepath" 25 | "testing" 26 | ) 27 | 28 | func TestSymlink(t *testing.T) { 29 | d, err := ioutil.TempDir("", "tempdirtest") 30 | if err != nil { 31 | t.Fatal(err) 32 | } 33 | defer os.RemoveAll(d) 34 | 35 | want := []byte("Hello World") 36 | if err := ioutil.WriteFile(filepath.Join(d, "hello.txt"), want, 0644); err != nil { 37 | t.Fatal(err) 38 | } 39 | 40 | for i := 0; i < 2; i++ { 41 | if err := Symlink("hello.txt", filepath.Join(d, "hi.txt")); err != nil { 42 | t.Fatal(err) 43 | } 44 | 45 | got, err := ioutil.ReadFile(filepath.Join(d, "hi.txt")) 46 | if err != nil { 47 | t.Fatal(err) 48 | } 49 | if !bytes.Equal(got, want) { 50 | t.Fatalf("unexpected content: got %q, want %q", string(got), string(want)) 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /tempfile.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build !windows 16 | // +build !windows 17 | 18 | package renameio 19 | 20 | import ( 21 | "io/ioutil" 22 | "math/rand" 23 | "os" 24 | "path/filepath" 25 | "strconv" 26 | ) 27 | 28 | // Default permissions for created files 29 | const defaultPerm os.FileMode = 0o600 30 | 31 | // nextrandom is a function generating a random number. 32 | var nextrandom = rand.Int63 33 | 34 | // openTempFile creates a randomly named file and returns an open handle. It is 35 | // similar to ioutil.TempFile except that the directory must be given, the file 36 | // permissions can be controlled and patterns in the name are not supported. 37 | // The name is always suffixed with a random number. 38 | func openTempFile(dir, name string, perm os.FileMode) (*os.File, error) { 39 | prefix := filepath.Join(dir, name) 40 | 41 | for attempt := 0; ; { 42 | // Generate a reasonably random name which is unlikely to already 43 | // exist. O_EXCL ensures that existing files generate an error. 44 | name := prefix + strconv.FormatInt(nextrandom(), 10) 45 | 46 | f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, perm) 47 | if !os.IsExist(err) { 48 | return f, err 49 | } 50 | 51 | if attempt++; attempt > 10000 { 52 | return nil, &os.PathError{ 53 | Op: "tempfile", 54 | Path: name, 55 | Err: os.ErrExist, 56 | } 57 | } 58 | } 59 | } 60 | 61 | // TempDir checks whether os.TempDir() can be used as a temporary directory for 62 | // later atomically replacing files within dest. If no (os.TempDir() resides on 63 | // a different mount point), dest is returned. 64 | // 65 | // Note that the returned value ceases to be valid once either os.TempDir() 66 | // changes (e.g. on Linux, once the TMPDIR environment variable changes) or the 67 | // file system is unmounted. 68 | func TempDir(dest string) string { 69 | return tempDir("", filepath.Join(dest, "renameio-TempDir")) 70 | } 71 | 72 | func tempDir(dir, dest string) string { 73 | if dir != "" { 74 | return dir // caller-specified directory always wins 75 | } 76 | 77 | // Chose the destination directory as temporary directory so that we 78 | // definitely can rename the file, for which both temporary and destination 79 | // file need to point to the same mount point. 80 | fallback := filepath.Dir(dest) 81 | 82 | // The user might have overridden the os.TempDir() return value by setting 83 | // the TMPDIR environment variable. 84 | tmpdir := os.TempDir() 85 | 86 | testsrc, err := ioutil.TempFile(tmpdir, "."+filepath.Base(dest)) 87 | if err != nil { 88 | return fallback 89 | } 90 | cleanup := true 91 | defer func() { 92 | if cleanup { 93 | os.Remove(testsrc.Name()) 94 | } 95 | }() 96 | testsrc.Close() 97 | 98 | testdest, err := ioutil.TempFile(filepath.Dir(dest), "."+filepath.Base(dest)) 99 | if err != nil { 100 | return fallback 101 | } 102 | defer os.Remove(testdest.Name()) 103 | testdest.Close() 104 | 105 | if err := os.Rename(testsrc.Name(), testdest.Name()); err != nil { 106 | return fallback 107 | } 108 | cleanup = false // testsrc no longer exists 109 | return tmpdir 110 | } 111 | 112 | // PendingFile is a pending temporary file, waiting to replace the destination 113 | // path in a call to CloseAtomicallyReplace. 114 | type PendingFile struct { 115 | *os.File 116 | 117 | path string 118 | done bool 119 | closed bool 120 | replaceOnClose bool 121 | } 122 | 123 | // Cleanup is a no-op if CloseAtomicallyReplace succeeded, and otherwise closes 124 | // and removes the temporary file. 125 | // 126 | // This method is not safe for concurrent use by multiple goroutines. 127 | func (t *PendingFile) Cleanup() error { 128 | if t.done { 129 | return nil 130 | } 131 | // An error occurred. Close and remove the tempfile. Errors are returned for 132 | // reporting, there is nothing the caller can recover here. 133 | var closeErr error 134 | if !t.closed { 135 | closeErr = t.File.Close() 136 | } 137 | if err := os.Remove(t.Name()); err != nil { 138 | return err 139 | } 140 | t.done = true 141 | return closeErr 142 | } 143 | 144 | // CloseAtomicallyReplace closes the temporary file and atomically replaces 145 | // the destination file with it, i.e., a concurrent open(2) call will either 146 | // open the file previously located at the destination path (if any), or the 147 | // just written file, but the file will always be present. 148 | // 149 | // This method is not safe for concurrent use by multiple goroutines. 150 | func (t *PendingFile) CloseAtomicallyReplace() error { 151 | // Even on an ordered file system (e.g. ext4 with data=ordered) or file 152 | // systems with write barriers, we cannot skip the fsync(2) call as per 153 | // Theodore Ts'o (ext2/3/4 lead developer): 154 | // 155 | // > data=ordered only guarantees the avoidance of stale data (e.g., the previous 156 | // > contents of a data block showing up after a crash, where the previous data 157 | // > could be someone's love letters, medical records, etc.). Without the fsync(2) 158 | // > a zero-length file is a valid and possible outcome after the rename. 159 | if err := t.Sync(); err != nil { 160 | return err 161 | } 162 | t.closed = true 163 | if err := t.File.Close(); err != nil { 164 | return err 165 | } 166 | if err := os.Rename(t.Name(), t.path); err != nil { 167 | return err 168 | } 169 | t.done = true 170 | return nil 171 | } 172 | 173 | // Close closes the file. By default it just calls Close() on the underlying file. For PendingFiles created with 174 | // WithReplaceOnClose it calls CloseAtomicallyReplace() instead. 175 | func (t *PendingFile) Close() error { 176 | if t.replaceOnClose { 177 | return t.CloseAtomicallyReplace() 178 | } 179 | return t.File.Close() 180 | } 181 | 182 | // TempFile creates a temporary file destined to atomically creating or 183 | // replacing the destination file at path. 184 | // 185 | // If dir is the empty string, TempDir(filepath.Base(path)) is used. If you are 186 | // going to write a large number of files to the same file system, store the 187 | // result of TempDir(filepath.Base(path)) and pass it instead of the empty 188 | // string. 189 | // 190 | // The file's permissions will be 0600. You can change these by explicitly 191 | // calling Chmod on the returned PendingFile. 192 | func TempFile(dir, path string) (*PendingFile, error) { 193 | return NewPendingFile(path, WithTempDir(dir), WithStaticPermissions(defaultPerm)) 194 | } 195 | 196 | type config struct { 197 | dir, path string 198 | createPerm os.FileMode 199 | attemptPermCopy bool 200 | ignoreUmask bool 201 | chmod *os.FileMode 202 | renameOnClose bool 203 | } 204 | 205 | // NewPendingFile creates a temporary file destined to atomically creating or 206 | // replacing the destination file at path. 207 | // 208 | // TempDir(filepath.Base(path)) is used to store the temporary file. If you are 209 | // going to write a large number of files to the same file system, use the 210 | // result of TempDir(filepath.Base(path)) with the WithTempDir option. 211 | // 212 | // The file's permissions will be (0600 & ^umask). Use WithPermissions, 213 | // IgnoreUmask, WithStaticPermissions and WithExistingPermissions to control 214 | // them. 215 | func NewPendingFile(path string, opts ...Option) (*PendingFile, error) { 216 | cfg := config{ 217 | path: path, 218 | createPerm: defaultPerm, 219 | } 220 | 221 | for _, o := range opts { 222 | o.apply(&cfg) 223 | } 224 | 225 | if cfg.ignoreUmask && cfg.chmod == nil { 226 | cfg.chmod = &cfg.createPerm 227 | } 228 | 229 | if cfg.attemptPermCopy { 230 | // Try to determine permissions from an existing file. 231 | if existing, err := os.Lstat(cfg.path); err == nil && existing.Mode().IsRegular() { 232 | perm := existing.Mode() & os.ModePerm 233 | cfg.chmod = &perm 234 | 235 | // Try to already create file with desired permissions; at worst 236 | // a chmod will be needed afterwards. 237 | cfg.createPerm = perm 238 | } else if err != nil && !os.IsNotExist(err) { 239 | return nil, err 240 | } 241 | } 242 | 243 | f, err := openTempFile(tempDir(cfg.dir, cfg.path), "."+filepath.Base(cfg.path), cfg.createPerm) 244 | if err != nil { 245 | return nil, err 246 | } 247 | 248 | if cfg.chmod != nil { 249 | if fi, err := f.Stat(); err != nil { 250 | return nil, err 251 | } else if fi.Mode()&os.ModePerm != *cfg.chmod { 252 | if err := f.Chmod(*cfg.chmod); err != nil { 253 | return nil, err 254 | } 255 | } 256 | } 257 | 258 | return &PendingFile{File: f, path: cfg.path, replaceOnClose: cfg.renameOnClose}, nil 259 | } 260 | 261 | // Symlink wraps os.Symlink, replacing an existing symlink with the same name 262 | // atomically (os.Symlink fails when newname already exists, at least on Linux). 263 | func Symlink(oldname, newname string) error { 264 | // Fast path: if newname does not exist yet, we can skip the whole dance 265 | // below. 266 | if err := os.Symlink(oldname, newname); err == nil || !os.IsExist(err) { 267 | return err 268 | } 269 | 270 | // We need to use ioutil.TempDir, as we cannot overwrite a ioutil.TempFile, 271 | // and removing+symlinking creates a TOCTOU race. 272 | d, err := ioutil.TempDir(filepath.Dir(newname), "."+filepath.Base(newname)) 273 | if err != nil { 274 | return err 275 | } 276 | cleanup := true 277 | defer func() { 278 | if cleanup { 279 | os.RemoveAll(d) 280 | } 281 | }() 282 | 283 | symlink := filepath.Join(d, "tmp.symlink") 284 | if err := os.Symlink(oldname, symlink); err != nil { 285 | return err 286 | } 287 | 288 | if err := os.Rename(symlink, newname); err != nil { 289 | return err 290 | } 291 | 292 | cleanup = false 293 | return os.RemoveAll(d) 294 | } 295 | -------------------------------------------------------------------------------- /tempfile_linux_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package renameio 16 | 17 | import ( 18 | "io/ioutil" 19 | "os" 20 | "path/filepath" 21 | "syscall" 22 | "testing" 23 | ) 24 | 25 | func TestTempDir(t *testing.T) { 26 | if tmpdir, ok := os.LookupEnv("TMPDIR"); ok { 27 | defer os.Setenv("TMPDIR", tmpdir) // restore 28 | } else { 29 | defer os.Unsetenv("TMPDIR") // restore 30 | } 31 | 32 | mount1, err := ioutil.TempDir("", "tempdirtest") 33 | if err != nil { 34 | t.Fatal(err) 35 | } 36 | defer os.RemoveAll(mount1) 37 | 38 | mount2, err := ioutil.TempDir("", "tempdirtest") 39 | if err != nil { 40 | t.Fatal(err) 41 | } 42 | defer os.RemoveAll(mount2) 43 | 44 | if err := syscall.Mount("tmpfs", mount1, "tmpfs", 0, ""); err != nil { 45 | t.Skipf("cannot mount tmpfs on %s: %v", mount1, err) 46 | } 47 | defer syscall.Unmount(mount1, 0) 48 | 49 | if err := syscall.Mount("tmpfs", mount2, "tmpfs", 0, ""); err != nil { 50 | t.Skipf("cannot mount tmpfs on %s: %v", mount2, err) 51 | } 52 | defer syscall.Unmount(mount2, 0) 53 | 54 | tests := []struct { 55 | name string 56 | dir string 57 | path string 58 | TMPDIR string 59 | want string 60 | }{ 61 | { 62 | name: "implicit TMPDIR", 63 | path: filepath.Join(os.TempDir(), "foo.txt"), 64 | want: os.TempDir(), 65 | }, 66 | 67 | { 68 | name: "explicit TMPDIR", 69 | path: filepath.Join(mount1, "foo.txt"), 70 | TMPDIR: mount1, 71 | want: mount1, 72 | }, 73 | 74 | { 75 | name: "explicit unsuitable TMPDIR", 76 | path: filepath.Join(mount1, "foo.txt"), 77 | TMPDIR: mount2, 78 | want: mount1, 79 | }, 80 | 81 | { 82 | name: "nonexistant TMPDIR", 83 | path: filepath.Join(mount1, "foo.txt"), 84 | TMPDIR: "/nonexistant", 85 | want: mount1, 86 | }, 87 | 88 | { 89 | name: "caller-specified", 90 | dir: "/overridden", 91 | path: filepath.Join(mount1, "foo.txt"), 92 | TMPDIR: "/nonexistant", 93 | want: "/overridden", 94 | }, 95 | } 96 | 97 | for _, tt := range tests { 98 | t.Run(tt.name, func(t *testing.T) { 99 | if tt.TMPDIR == "" { 100 | os.Unsetenv("TMPDIR") 101 | } else { 102 | os.Setenv("TMPDIR", tt.TMPDIR) 103 | } 104 | if got := tempDir(tt.dir, tt.path); got != tt.want { 105 | t.Fatalf("tempDir(%q, %q): got %q, want %q", tt.dir, tt.path, got, tt.want) 106 | } 107 | }) 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /tempfile_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build !windows 16 | // +build !windows 17 | 18 | package renameio 19 | 20 | import ( 21 | "errors" 22 | "fmt" 23 | "io/ioutil" 24 | "os" 25 | "path/filepath" 26 | "syscall" 27 | "testing" 28 | ) 29 | 30 | func withUmask(t *testing.T, mask os.FileMode) { 31 | t.Helper() 32 | 33 | old := syscall.Umask(int(mask)) 34 | 35 | t.Cleanup(func() { 36 | syscall.Umask(old) 37 | }) 38 | } 39 | 40 | func withCustomRng(t *testing.T, fn func() int64) { 41 | t.Helper() 42 | 43 | orig := nextrandom 44 | 45 | t.Cleanup(func() { 46 | nextrandom = orig 47 | }) 48 | 49 | nextrandom = fn 50 | } 51 | 52 | func TestOpenTempFile(t *testing.T) { 53 | const count = 100 54 | 55 | // Install a deterministic random generator 56 | var next int64 = 12345 57 | withCustomRng(t, func() int64 { 58 | v := next 59 | next++ 60 | return v 61 | }) 62 | 63 | for _, umask := range []os.FileMode{0o000, 0o011, 0o007, 0o027, 0o077} { 64 | t.Run(fmt.Sprintf("0%o", umask), func(t *testing.T) { 65 | withUmask(t, umask) 66 | 67 | dir := t.TempDir() 68 | 69 | for i := 0; i < count; i++ { 70 | perm := [...]os.FileMode{0600, 0755, 0411}[i%3] 71 | maskedPerm := perm & ^umask 72 | 73 | got, err := openTempFile(dir, "test", perm) 74 | if err != nil { 75 | t.Errorf("openTempFile() failed: %v", err) 76 | } 77 | 78 | t.Cleanup(func() { 79 | if err := got.Close(); err != nil { 80 | t.Errorf("Close() failed: %v", err) 81 | } 82 | }) 83 | 84 | if fi, err := os.Stat(got.Name()); err != nil { 85 | t.Errorf("Stat(%q) failed: %v", got.Name(), err) 86 | } else if gotPerm := fi.Mode() & os.ModePerm; gotPerm != maskedPerm { 87 | t.Errorf("Got permissions 0%o, want 0%o", gotPerm, maskedPerm) 88 | } 89 | } 90 | 91 | if entries, err := ioutil.ReadDir(dir); err != nil { 92 | t.Errorf("ReadDir(%q) failed: %v", dir, err) 93 | } else if len(entries) < count { 94 | t.Errorf("Directory %q contains fewer than %d entries", dir, count) 95 | } 96 | }) 97 | } 98 | } 99 | 100 | func TestOpenTempFileConflict(t *testing.T) { 101 | withUmask(t, 0077) 102 | 103 | // https://xkcd.com/221/ 104 | withCustomRng(t, func() int64 { 105 | return 4 106 | }) 107 | 108 | dir := t.TempDir() 109 | 110 | if first, err := openTempFile(dir, "test", 0644); err != nil { 111 | t.Errorf("openTempFile() failed: %v", err) 112 | } else { 113 | first.Close() 114 | } 115 | 116 | if _, err := openTempFile(dir, "test", 0644); !errors.Is(err, os.ErrExist) { 117 | t.Errorf("openTempFile() did not fail with ErrExist: %v", err) 118 | } 119 | } 120 | 121 | func TestPendingFileCreation(t *testing.T) { 122 | withUmask(t, 0077) 123 | 124 | pathExisting := filepath.Join(t.TempDir(), "existing.txt") 125 | pathExistingWithPerm := filepath.Join(t.TempDir(), "perm.txt") 126 | 127 | for path, content := range map[string]string{ 128 | pathExisting: "content", 129 | pathExistingWithPerm: "", 130 | } { 131 | if err := ioutil.WriteFile(path, []byte(content), 0644); err != nil { 132 | t.Errorf("WriteFile(%q) failed: %v", path, err) 133 | } 134 | } 135 | 136 | for _, tc := range []struct { 137 | name string 138 | path string 139 | umask os.FileMode 140 | useTempFile bool 141 | options []Option 142 | want string 143 | wantPerm os.FileMode 144 | }{ 145 | { 146 | name: "tempfile new file", 147 | path: filepath.Join(t.TempDir(), "new.txt"), 148 | useTempFile: true, 149 | want: "replaced:tempfile new file", 150 | wantPerm: 0o600, 151 | }, 152 | { 153 | name: "tempfile existing", 154 | path: pathExisting, 155 | useTempFile: true, 156 | want: "replaced:tempfile existing", 157 | wantPerm: 0o600, 158 | }, 159 | { 160 | name: "tempfile umask", 161 | path: filepath.Join(t.TempDir(), "masked"), 162 | useTempFile: true, 163 | umask: 0o377, 164 | want: "replaced:tempfile umask", 165 | wantPerm: 0o600, 166 | }, 167 | { 168 | name: "defaults", 169 | path: filepath.Join(t.TempDir(), "npf defaults"), 170 | want: "replaced:defaults", 171 | wantPerm: 0o600, 172 | }, 173 | { 174 | name: "fixed perm", 175 | path: filepath.Join(t.TempDir(), "npf new perm"), 176 | options: []Option{WithStaticPermissions(0o654)}, 177 | want: "replaced:fixed perm", 178 | wantPerm: 0o654, 179 | }, 180 | { 181 | name: "umask perm 0644", 182 | path: filepath.Join(t.TempDir(), "npf umask perm"), 183 | options: []Option{WithPermissions(0o777)}, 184 | umask: 0o012, 185 | want: "replaced:umask perm 0644", 186 | wantPerm: 0o765, 187 | }, 188 | { 189 | name: "setup with perm", 190 | path: pathExistingWithPerm, 191 | options: []Option{WithStaticPermissions(0o754)}, 192 | want: "replaced:setup with perm", 193 | wantPerm: 0o754, 194 | }, 195 | { 196 | name: "overwrite existing with perm", 197 | path: pathExistingWithPerm, 198 | options: []Option{WithExistingPermissions()}, 199 | want: "replaced:overwrite existing with perm", 200 | wantPerm: 0o754, 201 | }, 202 | { 203 | name: "use permissions from non-existing with unset", 204 | path: filepath.Join(t.TempDir(), "never before"), 205 | options: []Option{WithExistingPermissions()}, 206 | want: "replaced:use permissions from non-existing with unset", 207 | wantPerm: 0o600, 208 | }, 209 | { 210 | name: "use permissions from non-existing with mode", 211 | path: filepath.Join(t.TempDir(), "never before"), 212 | options: []Option{WithPermissions(0o633), WithExistingPermissions()}, 213 | umask: 0o012, 214 | want: "replaced:use permissions from non-existing with mode", 215 | wantPerm: 0o621, 216 | }, 217 | { 218 | name: "use permissions from non-existing with fixed", 219 | path: filepath.Join(t.TempDir(), "never before"), 220 | options: []Option{WithExistingPermissions(), WithStaticPermissions(0o612)}, 221 | want: "replaced:use permissions from non-existing with fixed", 222 | wantPerm: 0o612, 223 | }, 224 | { 225 | name: "custom tempdir", 226 | path: filepath.Join(t.TempDir(), "foo"), 227 | options: []Option{WithTempDir(t.TempDir()), WithStaticPermissions(0o612)}, 228 | umask: 0o012, 229 | want: "replaced:custom tempdir", 230 | wantPerm: 0o612, 231 | }, 232 | { 233 | name: "ignore umask", 234 | path: filepath.Join(t.TempDir(), "ignore umask"), 235 | options: []Option{IgnoreUmask(), WithPermissions(0o644)}, 236 | want: "replaced:ignore umask", 237 | wantPerm: 0o644, 238 | }, 239 | { 240 | name: "ignore umask with static permissions", 241 | path: filepath.Join(t.TempDir(), "ignore umask"), 242 | options: []Option{IgnoreUmask(), WithStaticPermissions(0o632), WithPermissions(0o765)}, 243 | want: "replaced:ignore umask with static permissions", 244 | wantPerm: 0o632, 245 | }, 246 | } { 247 | t.Run(tc.name, func(t *testing.T) { 248 | if tc.umask != 0 { 249 | withUmask(t, tc.umask) 250 | } 251 | 252 | var err error 253 | var pf *PendingFile 254 | 255 | if tc.useTempFile { 256 | pf, err = TempFile("", tc.path) 257 | if err != nil { 258 | t.Errorf("TempFile(%q) failed: %v", tc.path, err) 259 | } 260 | } else { 261 | pf, err = NewPendingFile(tc.path, tc.options...) 262 | if err != nil { 263 | t.Errorf("NewPendingFile(%q, %+v) failed: %v", tc.path, tc.options, err) 264 | } 265 | } 266 | 267 | if _, err := pf.WriteString("replaced:" + tc.name); err != nil { 268 | t.Errorf("Write() failed: %v", err) 269 | } 270 | 271 | if err := pf.CloseAtomicallyReplace(); err != nil { 272 | t.Errorf("CloseAtomicallyReplace() failed: %v", err) 273 | } 274 | 275 | if _, err := pf.Write(nil); !errors.Is(err, os.ErrClosed) { 276 | t.Errorf("Write() after CloseAtomicallyReplace didn't fail with ErrClosed: %v", err) 277 | } 278 | 279 | if err := pf.Cleanup(); err != nil { 280 | t.Errorf("Cleanup() failed: %v", err) 281 | } 282 | 283 | if got, err := ioutil.ReadFile(tc.path); err != nil { 284 | t.Errorf("ReadFile(%q) failed: %v", tc.path, err) 285 | } else if string(got) != tc.want { 286 | t.Errorf("Read unexpected content %q from %q, want %q", string(got), tc.path, tc.want) 287 | } 288 | 289 | if fi, err := os.Stat(tc.path); err != nil { 290 | t.Errorf("Stat(%q) failed: %v", tc.path, err) 291 | } else if got := fi.Mode() & os.ModePerm; got != tc.wantPerm { 292 | t.Errorf("%q has permissions 0%o, want 0%o", tc.path, got, tc.wantPerm) 293 | } 294 | }) 295 | } 296 | } 297 | 298 | func TestPendingFileClosing(t *testing.T) { 299 | for _, tc := range []struct { 300 | name string 301 | path string 302 | options []Option 303 | wantMissing bool 304 | wantContent string 305 | }{ 306 | { 307 | name: "default: Close() closes underlying file", 308 | path: filepath.Join(t.TempDir(), "new.txt"), 309 | wantMissing: true, 310 | }, 311 | { 312 | name: "WithReplaceOnClose", 313 | path: filepath.Join(t.TempDir(), "new.txt"), 314 | options: []Option{WithReplaceOnClose()}, 315 | wantMissing: false, 316 | wantContent: "tempfile new file", 317 | }, 318 | } { 319 | t.Run(tc.name, func(t *testing.T) { 320 | pf, err := NewPendingFile(tc.path, tc.options...) 321 | if err != nil { 322 | t.Errorf("NewPendingFile(%q, %+v) failed: %v", tc.path, tc.options, err) 323 | } 324 | 325 | if _, err := pf.Write([]byte(tc.wantContent)); err != nil { 326 | t.Errorf("Write(%q) failed: %v", tc.path, err) 327 | } 328 | 329 | pf.Close() 330 | 331 | got, err := os.ReadFile(tc.path) 332 | if tc.wantMissing { 333 | if !errors.Is(err, os.ErrNotExist) { 334 | t.Errorf("Expected %q to be missing, got: %v", tc.path, err) 335 | } 336 | } else { 337 | if err != nil { 338 | t.Errorf("ReadFile(%q) failed: %v", tc.path, err) 339 | } else if string(got) != tc.wantContent { 340 | t.Errorf("Read unexpected content %q from %q, want %q", string(got), tc.path, tc.wantContent) 341 | } 342 | } 343 | }) 344 | } 345 | } 346 | 347 | func TestTempFileNoCommit(t *testing.T) { 348 | pathNew := filepath.Join(t.TempDir(), "new.txt") 349 | pathExisting := filepath.Join(t.TempDir(), "existing.txt") 350 | 351 | if err := ioutil.WriteFile(pathExisting, []byte("foobar"), 0644); err != nil { 352 | t.Errorf("WriteFile(%q) failed: %v", pathExisting, err) 353 | } 354 | 355 | for _, tc := range []struct { 356 | name string 357 | path string 358 | }{ 359 | { 360 | name: "new file", 361 | path: pathNew, 362 | }, 363 | { 364 | name: "existing", 365 | path: pathExisting, 366 | }, 367 | } { 368 | t.Run(tc.name, func(t *testing.T) { 369 | pf, err := TempFile("", tc.path) 370 | if err != nil { 371 | t.Errorf("TempFile(%q) failed: %v", tc.path, err) 372 | } 373 | 374 | for i := 0; i < 3; i++ { 375 | if err := pf.Cleanup(); err != nil { 376 | t.Errorf("Cleanup() failed: %v", err) 377 | } 378 | } 379 | }) 380 | } 381 | 382 | if _, err := os.Stat(pathNew); !os.IsNotExist(err) { 383 | t.Errorf("Stat(%q) didn't report that file doesn't exist: %v", pathNew, err) 384 | } 385 | 386 | if got, err := ioutil.ReadFile(pathExisting); err != nil { 387 | t.Errorf("ReadFile(%q) failed: %v", pathExisting, err) 388 | } else if want := "foobar"; string(got) != want { 389 | t.Errorf("Read unexpected content %q from %q, want %q", string(got), pathExisting, want) 390 | } 391 | } 392 | -------------------------------------------------------------------------------- /writefile.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build !windows 16 | // +build !windows 17 | 18 | package renameio 19 | 20 | import "os" 21 | 22 | // WriteFile mirrors ioutil.WriteFile, replacing an existing file with the same 23 | // name atomically. 24 | func WriteFile(filename string, data []byte, perm os.FileMode, opts ...Option) error { 25 | opts = append([]Option{ 26 | WithPermissions(perm), 27 | WithExistingPermissions(), 28 | }, opts...) 29 | 30 | t, err := NewPendingFile(filename, opts...) 31 | if err != nil { 32 | return err 33 | } 34 | defer t.Cleanup() 35 | 36 | if _, err := t.Write(data); err != nil { 37 | return err 38 | } 39 | 40 | return t.CloseAtomicallyReplace() 41 | } 42 | -------------------------------------------------------------------------------- /writefile_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build !windows 16 | // +build !windows 17 | 18 | package renameio 19 | 20 | import ( 21 | "bytes" 22 | "fmt" 23 | "io/ioutil" 24 | "os" 25 | "path/filepath" 26 | "testing" 27 | ) 28 | 29 | func TestWriteFile(t *testing.T) { 30 | for _, perm := range []os.FileMode{0o755, 0o644, 0o400, 0o765} { 31 | t.Run(fmt.Sprintf("perm%04o", perm), func(t *testing.T) { 32 | for _, umask := range []os.FileMode{0o000, 0o011, 0o007, 0o027, 0o077} { 33 | t.Run(fmt.Sprintf("umask%04o", umask), func(t *testing.T) { 34 | withUmask(t, umask) 35 | 36 | maskedPerm := perm & ^umask 37 | 38 | filename := filepath.Join(t.TempDir(), "hello.sh") 39 | 40 | wantData := []byte("#!/bin/sh\necho \"Hello World\"\n") 41 | if err := WriteFile(filename, wantData, perm); err != nil { 42 | t.Fatal(err) 43 | } 44 | 45 | gotData, err := ioutil.ReadFile(filename) 46 | if err != nil { 47 | t.Fatal(err) 48 | } 49 | if !bytes.Equal(gotData, wantData) { 50 | t.Errorf("got data %v, want data %v", gotData, wantData) 51 | } 52 | 53 | fi, err := os.Stat(filename) 54 | if err != nil { 55 | t.Fatal(err) 56 | } 57 | if gotPerm := fi.Mode() & os.ModePerm; gotPerm != maskedPerm { 58 | t.Errorf("got permissions %04o, want %04o", gotPerm, maskedPerm) 59 | } 60 | }) 61 | } 62 | }) 63 | } 64 | } 65 | 66 | func TestWriteFileIgnoreUmask(t *testing.T) { 67 | withUmask(t, 0o077) 68 | 69 | filename := filepath.Join(t.TempDir(), "file") 70 | 71 | const wantPerm os.FileMode = 0o765 72 | 73 | if err := WriteFile(filename, nil, wantPerm, IgnoreUmask()); err != nil { 74 | t.Fatal(err) 75 | } 76 | 77 | fi, err := os.Stat(filename) 78 | if err != nil { 79 | t.Fatal(err) 80 | } 81 | if gotPerm := fi.Mode() & os.ModePerm; gotPerm != wantPerm { 82 | t.Errorf("got permissions %04o, want %04o", gotPerm, wantPerm) 83 | } 84 | } 85 | 86 | func TestWriteFileEquivalence(t *testing.T) { 87 | type writeFunc func(string, []byte, os.FileMode, ...Option) error 88 | type test struct { 89 | name string 90 | fn writeFunc 91 | perm os.FileMode 92 | umask os.FileMode 93 | exists bool 94 | } 95 | 96 | var tests []test 97 | 98 | for _, wf := range []struct { 99 | name string 100 | fn writeFunc 101 | }{ 102 | { 103 | name: "WriteFile", 104 | fn: WriteFile, 105 | }, 106 | { 107 | name: "ioutil", 108 | fn: func(filename string, data []byte, perm os.FileMode, opts ...Option) error { 109 | return ioutil.WriteFile(filename, data, perm) 110 | }, 111 | }, 112 | } { 113 | for _, perm := range []os.FileMode{0o755, 0o644, 0o400, 0o765} { 114 | for _, umask := range []os.FileMode{0o000, 0o011, 0o007, 0o027, 0o077} { 115 | for _, exists := range []bool{false, true} { 116 | name := fmt.Sprintf("%s/perm%04o/umask%04o", wf.name, perm, umask) 117 | if exists { 118 | name += "/exists" 119 | } 120 | 121 | tests = append(tests, test{ 122 | name: name, 123 | fn: wf.fn, 124 | perm: perm, 125 | umask: umask, 126 | exists: exists, 127 | }) 128 | } 129 | } 130 | } 131 | } 132 | 133 | const existingPerm os.FileMode = 0o654 134 | 135 | for _, tc := range tests { 136 | t.Run(tc.name, func(t *testing.T) { 137 | withUmask(t, tc.umask) 138 | 139 | maskedPerm := tc.perm & ^tc.umask 140 | 141 | filename := filepath.Join(t.TempDir(), "test.txt") 142 | 143 | if tc.exists { 144 | // Create file in preparation for replacement 145 | fh, err := os.Create(filename) 146 | if err != nil { 147 | t.Errorf("Create(%q) failed: %v", filename, err) 148 | } 149 | 150 | if err := fh.Chmod(existingPerm); err != nil { 151 | t.Errorf("Chmod() failed: %v", err) 152 | } 153 | 154 | fh.Close() 155 | 156 | maskedPerm = existingPerm 157 | } 158 | 159 | wantData := []byte("content\n") 160 | 161 | if err := tc.fn(filename, wantData, tc.perm); err != nil { 162 | t.Fatal(err) 163 | } 164 | 165 | gotData, err := ioutil.ReadFile(filename) 166 | if err != nil { 167 | t.Fatal(err) 168 | } 169 | if !bytes.Equal(gotData, wantData) { 170 | t.Errorf("got data %v, want data %v", gotData, wantData) 171 | } 172 | 173 | fi, err := os.Stat(filename) 174 | if err != nil { 175 | t.Fatal(err) 176 | } 177 | if gotPerm := fi.Mode() & os.ModePerm; gotPerm != maskedPerm { 178 | t.Errorf("got permissions %04o, want %04o", gotPerm, maskedPerm) 179 | } 180 | }) 181 | } 182 | } 183 | --------------------------------------------------------------------------------