// WriteFileAtomic creates a temporary file with data and provided perm and
// swaps it atomically with filename if successful.
770563
func WriteFileAtomic(filename string, data []byte, perm os.FileMode) (err error) {
	// This implementation is inspired by the golang stdlibs method of creating
	// tempfiles. Notable differences are that we use different flags, a 64 bit LCG
	// and handle negatives differently.
	// The core reason we can't use golang's TempFile is that we must write
	// to the file synchronously, as we need this to persist to disk.
	// We also open it in write-only mode, to avoid concerns that arise with read.
	var (
		dir = filepath.Dir(filename)
		f   *os.File
	)

	nconflict := 0
	// Limit the number of attempts to create a file. Something is seriously
	// wrong if it didn't get created after 1000 attempts, and we don't want
	// an infinite loop
	i := 0
	for ; i < atomicWriteFileMaxNumWriteAttempts; i++ {
		name := filepath.Join(dir, atomicWriteFilePrefix+randWriteFileSuffix())
		f, err = os.OpenFile(name, atomicWriteFileFlag, perm)
		// If the file already exists, try a new file
		if os.IsExist(err) {
			// If the files exists too many times, start reseeding as we've
			// likely hit another instances seed.
			if nconflict++; nconflict > atomicWriteFileMaxNumConflicts {
				atomicWriteFileRandMu.Lock()
				atomicWriteFileRand = writeFileRandReseed()
				atomicWriteFileRandMu.Unlock()
			}
			continue
		} else if err != nil {
			return err
		}
		break
	}
	if i == atomicWriteFileMaxNumWriteAttempts {
		return fmt.Errorf("Could not create atomic write file after %d attempts", i)
	}

	// Clean up in any case. Defer stacking order is last-in-first-out.
	defer os.Remove(f.Name())
	defer f.Close()

	if n, err := f.Write(data); err != nil {
		return err
	} else if n < len(data) {
		return io.ErrShortWrite
	}
	// Close the file before renaming it, otherwise it will cause "The process
	// cannot access the file because it is being used by another process." on windows.
	f.Close()

	return os.Rename(f.Name(), filename)
}
160017
func (b *MemFile) Write(p []byte) (n int, err error) {
	b.mutex.Lock()
	n, err = b.Buffer.Write(p)
	b.mutex.Unlock()
	return
}
1261054
func safeWriteToFile(t SafeWriter, mode os.FileMode, log Log) error {
	filename := t.GetFilename()
	if filename == "" {
		return fmt.Errorf("No filename")
	}
	log.Debugf("Writing to %s", filename)
	tempFilename, tempFile, err := openTempFile(filename+"-", "", mode)
	log.Debugf("Temporary file generated: %s", tempFilename)
	if err != nil {
		return err
	}
	_, err = t.WriteTo(tempFile)
	if err != nil {
		log.Errorf("Error writing temporary file %s: %s", tempFilename, err)
		_ = tempFile.Close()
		_ = os.Remove(tempFilename)
		return err
	}
	err = tempFile.Close()
	if err != nil {
		log.Errorf("Error closing temporary file %s: %s", tempFilename, err)
		_ = os.Remove(tempFilename)
		return err
	}
	err = os.Rename(tempFilename, filename)
	if err != nil {
		log.Errorf("Error renaming temporary file %s to %s: %s", tempFilename, filename, err)
		_ = os.Remove(tempFilename)
		return err
	}
	log.Debugf("Wrote to %s", filename)
	return nil
}
475009
func (file *fakeFile) Write(b []byte) (n int, err error) {
	return file.file.Write(b)
}
344798
func (fsh *Handler) WriteFile(file string, data []byte) error {
	fileObj, err := os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, os.ModePerm)
	if err != nil {
		return fmt.Errorf("failed to open status file %s for writing: %v", file, err)
	}
	defer fileObj.Close()
	if _, err := fileObj.Write(data); err != nil {
		return fmt.Errorf("failed to write status file %s for writing: %v", file, err)
	}
	return nil
}
1152865
func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error {
	f, err := ioutil.TempFile(filepath.Dir(filename), ".tmp-"+filepath.Base(filename))
	if err != nil {
		return err
	}
	err = os.Chmod(f.Name(), perm)
	if err != nil {
		f.Close()
		return err
	}
	n, err := f.Write(data)
	if err == nil && n < len(data) {
		f.Close()
		return io.ErrShortWrite
	}
	if err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), filename)
}
207844
func (w *writerOnce) writeToMem(p []byte) int {
	left := w.o.memBytes - w.total
	if left <= 0 {
		return 0
	}
	bufLen := len(p)
	if int64(bufLen) < left {
		return bufLen
	}
	return int(left)
}
34245
func WriteFailureSummary(outputRoot, filename string) {
	outfile, err := os.Create(filepath.Join(outputRoot, filename))
	failureSummaries := make([]string, 0)
	if err != nil {
		panic(err)
	}
	err = filepath.Walk(outputRoot, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() {
			return nil
		}

		if strings.Contains(path, "summary") {
			return nil
		}
		defer os.Remove(path)
		allFailures, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		failures := strings.Split(string(allFailures), "\n")
		failureSummaries = append(failureSummaries, failures...)
		return nil
	})
	if err != nil {
		panic(err)
	}
	sort.Strings(failureSummaries)
	anyFailures := false
	var previousLine string
	for _, line := range failureSummaries {
		if line != "" && line != previousLine {
			anyFailures = true
			previousLine = line
			fmt.Fprintln(outfile, line)
		}
	}
	if !anyFailures {
		err = os.Remove(filepath.Join(outputRoot, filename))
	}
	if err != nil {
		panic(err)
	}
}
1162229
func WriteTmpFile(fs utilfs.Filesystem, path string, data []byte) (tmpPath string, retErr error) {
	dir := filepath.Dir(path)
	prefix := tmptag + filepath.Base(path)

	// create the tmp file
	tmpFile, err := fs.TempFile(dir, prefix)
	if err != nil {
		return "", err
	}
	defer func() {
		// close the file, return the close error only if there haven't been any other errors
		if err := tmpFile.Close(); retErr == nil {
			retErr = err
		}
		// if there was an error writing, syncing, or closing, delete the temporary file and return the error
		if retErr != nil {
			if err := fs.Remove(tmpPath); err != nil {
				retErr = fmt.Errorf("attempted to remove temporary file %q after error %v, but failed due to error: %v", tmpPath, retErr, err)
			}
			tmpPath = ""
		}
	}()

	// Name() will be an absolute path when using utilfs.DefaultFS, because ioutil.TempFile passes
	// an absolute path to os.Open, and we ensure similar behavior in utilfs.FakeFS for testing.
	tmpPath = tmpFile.Name()

	// write data
	if _, err := tmpFile.Write(data); err != nil {
		return tmpPath, err
	}
	// sync file, to ensure it's written in case a hard reset happens
	return tmpPath, tmpFile.Sync()
}
874257
func WriteTempFile(prefix string, data []byte, mode os.FileMode) (string, error) {
	path := TempPath("", prefix)
	if err := ioutil.WriteFile(path, data, mode); err != nil {
		return "", err
	}
	return path, nil
}
13911
func SafeWriteToFile(g SafeWriteLogger, t SafeWriter, mode os.FileMode) error {
	return safeWriteToFileOnce(g, t, mode)
}
917922
func (ws *AtomicWriteSet) FileWriter(name string, flag int, perm os.FileMode) (io.WriteCloser, error) {
	f, err := os.OpenFile(filepath.Join(ws.root, name), flag, perm)
	if err != nil {
		return nil, err
	}
	return syncFileCloser{f}, nil
}
939216
func (f *FileRotator) Write(p []byte) (n int, err error) {
	n = 0
	var forceRotate bool

	for n < len(p) {
		// Check if we still have space in the current file, otherwise close and
		// open the next file
		if forceRotate || f.currentWr >= f.FileSize {
			forceRotate = false
			f.flushBuffer()
			f.currentFile.Close()
			if err := f.nextFile(); err != nil {
				f.logger.Error("error creating next file", "err", err)
				return 0, err
			}
		}
		// Calculate the remaining size on this file and how much we have left
		// to write
		remainingSpace := f.FileSize - f.currentWr
		remainingToWrite := int64(len(p[n:]))

		// Check if we are near the end of the file. If we are we attempt to
		// avoid a log line being split between two files.
		var nw int
		if (remainingSpace - lineScanLimit) < remainingToWrite {
			// Scan for new line and if the data up to new line fits in current
			// file, write to buffer
			idx := bytes.IndexByte(p[n:], newLineDelimiter)
			if idx >= 0 && (remainingSpace-int64(idx)-1) >= 0 {
				// We have space so write it to buffer
				nw, err = f.writeToBuffer(p[n : n+idx+1])
			} else if idx >= 0 {
				// We found a new line but don't have space so just force rotate
				forceRotate = true
			} else if remainingToWrite > f.FileSize || f.FileSize-lineScanLimit < 0 {
				// There is no new line remaining but there is no point in
				// rotating since the remaining data will not even fit in the
				// next file either so just fill this one up.
				li := int64(n) + remainingSpace
				if remainingSpace > remainingToWrite {
					li = int64(n) + remainingToWrite
				}
				nw, err = f.writeToBuffer(p[n:li])
			} else {
				// There is no new line in the data remaining for us to write
				// and it will fit in the next file so rotate.
				forceRotate = true
			}
		} else {
			// Write all the bytes in the current file
			nw, err = f.writeToBuffer(p[n:])
		}

		// Increment the number of bytes written so far in this method
		// invocation
		n += nw

		// Increment the total number of bytes in the file
		f.currentWr += int64(n)
		if err != nil {
			f.logger.Error("error writing to file", "err", err)

			// As bufio writer does not automatically recover in case of any
			// io error, we need to recover from it manually resetting the
			// writter.
			f.createOrResetBuffer()

			return
		}
	}
	return
}
48626
func (f *FileWriter) Write(p []byte) (int, error) {
	f.mu.Lock()
	n, err := f.f.Write(p)
	f.mu.Unlock()
	return n, err
}
569246
func (f DumFile) Write(p []byte) (n int, err error) {
	return 0, f.err
}
1114715
func (r *RepoFile) WriteFile(path string, perm os.FileMode) error {
	data, err := yaml.Marshal(r)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(path, data, perm)
}
970527
func (file *File) Write(b []byte) (n int, err error) {
	if file.closed {
		err = errors.New("write on closed file")
		return
	}
	if file.aborted {
		err = errors.New("write on aborted file")
		return
	}

	defer func() {
		if err != nil {
			os.Remove(file.tmpfile.Name())
			file.aborted = true
		}
	}()

	n, err = file.tmpfile.Write(b)
	return
}