// Writes process as template to the filesystem. Errors are logged but not returned
761433
func (p *Plugin) writeAsTemplate(pr *Process) {
	tmp, err := p.processToTemplate(pr)
	if err != nil {
		p.Log.Errorf("cannot create a template from process: %v", err)
		return
	}
	if p.tReader == nil {
		p.Log.Warnf("process %s should write a new template, but reader (template path) is not defined",
			pr.name)
		return
	}
	if err = p.tReader.WriteTemplate(tmp, template.DefaultMode); err != nil {
		p.Log.Warnf("failed to write template %s: %v", tmp.Name, err)
		return
	}
}
309518
func (f *FileStore) Write(key string, data []byte) error {
	if err := ValidateKey(key); err != nil {
		return err
	}
	if err := ensureDirectory(f.filesystem, f.directoryPath); err != nil {
		return err
	}

	return writeFile(f.filesystem, f.getPathByKey(key), data)
}
818509
func (lw *LazyFile) Write(p []byte) (int, error) {
	if lw.file == nil {
		err := os.MkdirAll(path.Dir(lw.FileName), 0755)
		if err != nil {
			return 0, err
		}
		lw.file, err = os.Create(lw.FileName)
		if err != nil {
			return 0, err
		}
	}
	return lw.file.Write(p)
}
640322
func RenderTemplateToStream(output io.Writer, srcPath []string, data interface{}) (err error) {
	tmpl, err := template.ParseFiles(srcPath...)
	if err != nil {
		return NewBuildIfError(err, "Failed to parse template "+srcPath[0])
	}

	err = tmpl.Execute(output, data)
	if err != nil {
		return NewBuildIfError(err, "Failed to render template "+srcPath[0])
	}
	return
}
391071
func (w *BackupFileWriter) Write(b []byte) (int, error) {
	var bytesWritten uint32
	err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx)
	if err != nil {
		return 0, &os.PathError{"BackupWrite", w.f.Name(), err}
	}
	runtime.KeepAlive(w.f)
	if int(bytesWritten) != len(b) {
		return int(bytesWritten), errors.New("not all bytes could be written")
	}
	return len(b), nil
}
552767
func writeTemplate(fileName string, tmpl *template.Template, data interface{}) {
	buf := &bytes.Buffer{}
	err := tmpl.Execute(buf, data)
	if err != nil {
		log.Fatal(err)
	}

	formatted, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}

	fd, err := os.Create(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer fd.Close()

	fd.Write(formatted)
}
153268
func (p *parallelWriter) Write(ctx context.Context, blocks [][]byte) error {
	var wg sync.WaitGroup

	for i := range p.writers {
		if p.writers[i] == nil {
			p.errs[i] = errDiskNotFound
			continue
		}

		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			_, p.errs[i] = p.writers[i].Write(blocks[i])
			if p.errs[i] != nil {
				p.writers[i] = nil
			}
		}(i)
	}
	wg.Wait()

	// If nilCount >= p.writeQuorum, we return nil. This is because HealFile() uses
	// CreateFile with p.writeQuorum=1 to accommodate healing of single disk.
	// i.e if we do no return here in such a case, reduceWriteQuorumErrs() would
	// return a quorum error to HealFile().
	nilCount := 0
	for _, err := range p.errs {
		if err == nil {
			nilCount++
		}
	}
	if nilCount >= p.writeQuorum {
		return nil
	}
	return reduceWriteQuorumErrs(ctx, p.errs, objectOpIgnoredErrs, p.writeQuorum)
}
633535
func (g *GenOpts) write(t *TemplateOpts, data interface{}) error {
	dir, fname, err := g.location(t, data)
	if err != nil {
		return fmt.Errorf("failed to resolve template location for template %s: %v", t.Name, err)
	}

	if t.SkipExists && fileExists(dir, fname) {
		debugLog("skipping generation of %s because it already exists and skip_exist directive is set for %s",
			filepath.Join(dir, fname), t.Name)
		return nil
	}

	log.Printf("creating generated file %q in %q as %s", fname, dir, t.Name)
	content, err := g.render(t, data)
	if err != nil {
		return fmt.Errorf("failed rendering template data for %s: %v", t.Name, err)
	}

	if dir != "" {
		_, exists := os.Stat(dir)
		if os.IsNotExist(exists) {
			debugLog("creating directory %q for \"%s\"", dir, t.Name)
			// Directory settings consistent with file privileges.
			// Environment's umask may alter this setup
			if e := os.MkdirAll(dir, 0755); e != nil {
				return e
			}
		}
	}

	// Conditionally format the code, unless the user wants to skip
	formatted := content
	var writeerr error

	if !t.SkipFormat {
		formatted, err = g.LanguageOpts.FormatContent(fname, content)
		if err != nil {
			log.Printf("source formatting failed on template-generated source (%q for %s). Check that your template produces valid code", filepath.Join(dir, fname), t.Name)
			writeerr = ioutil.WriteFile(filepath.Join(dir, fname), content, 0644)
			if writeerr != nil {
				return fmt.Errorf("failed to write (unformatted) file %q in %q: %v", fname, dir, writeerr)
			}
			log.Printf("unformatted generated source %q has been dumped for template debugging purposes. DO NOT build on this source!", fname)
			return fmt.Errorf("source formatting on generated source %q failed: %v", t.Name, err)
		}
	}

	writeerr = ioutil.WriteFile(filepath.Join(dir, fname), formatted, 0644)
	if writeerr != nil {
		return fmt.Errorf("failed to write file %q in %q: %v", fname, dir, writeerr)
	}
	return err
}
708971
func FormatWrite(ctx formatter.Context, configs []swarm.Config) error {
	render := func(format func(subContext formatter.SubContext) error) error {
		for _, config := range configs {
			configCtx := &configContext{c: config}
			if err := format(configCtx); err != nil {
				return err
			}
		}
		return nil
	}
	return ctx.Write(newConfigContext(), render)
}
547631
func processArgs(args *internal.ArgType) error {
	var err error

	// get working directory
	cwd, err := os.Getwd()
	if err != nil {
		return err
	}

	// determine out path
	if args.Out == "" {
		args.Path = cwd
	} else {
		// determine what to do with Out
		fi, err := os.Stat(args.Out)
		if err == nil && fi.IsDir() {
			// out is directory
			args.Path = args.Out
		} else if err == nil && !fi.IsDir() {
			// file exists (will truncate later)
			args.Path = path.Dir(args.Out)
			args.Filename = path.Base(args.Out)

			// error if not split was set, but destination is not a directory
			if !args.SingleFile {
				return errors.New("output path is not directory")
			}
		} else if _, ok := err.(*os.PathError); ok {
			// path error (ie, file doesn't exist yet)
			args.Path = path.Dir(args.Out)
			args.Filename = path.Base(args.Out)

			// error if split was set, but dest doesn't exist
			if !args.SingleFile {
				return errors.New("output path must be a directory and already exist when not writing to a single file")
			}
		} else {
			return err
		}
	}

	// check user template path
	if args.TemplatePath != "" {
		fi, err := os.Stat(args.TemplatePath)
		if err == nil && !fi.IsDir() {
			return errors.New("template path is not directory")
		} else if err != nil {
			return errors.New("template path must exist")
		}
	}

	// fix path
	if args.Path == "." {
		args.Path = cwd
	}

	// determine package name
	if args.Package == "" {
		args.Package = path.Base(args.Path)
	}

	// determine filename if not previously set
	if args.Filename == "" {
		args.Filename = args.Package + args.Suffix
	}

	// if query mode toggled, but no query, read Stdin.
	if args.QueryMode && args.Query == "" {
		buf, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			return err
		}
		args.Query = string(buf)
	}

	// query mode parsing
	if args.Query != "" {
		args.QueryMode = true
	}

	// check that query type was specified
	if args.QueryMode && args.QueryType == "" {
		return errors.New("query type must be supplied for query parsing mode")
	}

	// query trim
	if args.QueryMode && args.QueryTrim {
		args.Query = strings.TrimSpace(args.Query)
	}

	// escape all
	if args.EscapeAll {
		args.EscapeSchemaName = true
		args.EscapeTableNames = true
		args.EscapeColumnNames = true
	}

	// if verbose
	if args.Verbose {
		models.XOLog = func(s string, p ...interface{}) {
			fmt.Printf("SQL:\n%s\nPARAMS:\n%v\n\n", s, p)
		}
	}

	return nil
}
1039987
func Write(out io.Writer, node ast.Node, options Options) (err error) {
	defer errRecover(&err)

	if options.Formatter == nil {
		options.Formatter = &ES5Formatter{}
	}

	var (
		tmpOut     = &bytes.Buffer{}
		importsBuf = &bytes.Buffer{}
		s          = &state{
			wr:          tmpOut,
			options:     options,
			funcsCalled: map[string]string{},
			funcsInFile: map[string]bool{},
		}
	)

	s.scope.push()
	s.walk(node)

	if len(s.funcsCalled) > 0 {
		for _, f := range difference(s.funcsCalled, s.funcsInFile) {
			importsBuf.WriteString(s.funcsCalled[f])
			importsBuf.WriteRune('\n')
		}
		importsBuf.WriteRune('\n')
	}

	out.Write(importsBuf.Bytes())
	out.Write(tmpOut.Bytes())

	return nil
}
716617
func (t *Templates) Execute(w io.Writer, n string, attrs ...Attrs) {
	data := Attrs{}
	data.Merge(t.locals)
	for _, attr := range attrs {
		data.Merge(attr)
	}
	if err := t.parsed.ExecuteTemplate(w, n, data); err != nil {
		panic(fmt.Sprintf("templates: could execute template %s: %s", n, err))
	}
}
604176
func (d *StateDir) Write(hi hook.Info) (err error) {
	defer errors.DeferredAnnotatef(&err, "failed to write %q hook info for %q on state directory", hi.Kind, hi.RemoteUnit)
	if hi.Kind == hooks.RelationBroken {
		return d.Remove()
	}
	name := strings.Replace(hi.RemoteUnit, "/", "-", 1)
	path := filepath.Join(d.path, name)
	if hi.Kind == hooks.RelationDeparted {
		if err = os.Remove(path); err != nil && !os.IsNotExist(err) {
			return err
		}
		// If atomic delete succeeded, update own state.
		delete(d.state.Members, hi.RemoteUnit)
		return nil
	}
	di := diskInfo{&hi.ChangeVersion, hi.Kind == hooks.RelationJoined}
	if err := utils.WriteYaml(path, &di); err != nil {
		return err
	}
	// If write was successful, update own state.
	d.state.Members[hi.RemoteUnit] = hi.ChangeVersion
	if hi.Kind == hooks.RelationJoined {
		d.state.ChangedPending = hi.RemoteUnit
	} else {
		d.state.ChangedPending = ""
	}
	return nil
}
794326
func (w *stdWriter) Write(p []byte) (n int, err error) {
	if w == nil || w.Writer == nil {
		return 0, errors.New("Writer not instantiated")
	}
	if p == nil {
		return 0, nil
	}

	header := [stdWriterPrefixLen]byte{stdWriterFdIndex: w.prefix}
	binary.BigEndian.PutUint32(header[stdWriterSizeIndex:], uint32(len(p)))
	buf := bufPool.Get().(*bytes.Buffer)
	buf.Write(header[:])
	buf.Write(p)

	n, err = w.Writer.Write(buf.Bytes())
	n -= stdWriterPrefixLen
	if n < 0 {
		n = 0
	}

	buf.Reset()
	bufPool.Put(buf)
	return
}
459443
func (f *PrefetchFile) Write(ctx context.Context, req *fuse.WriteRequest,
	resp *fuse.WriteResponse) (err error) {
	f.fs.log.CDebugf(ctx, "PrefetchFile (enable: %t) Write", f.enable)
	defer func() { err = f.fs.processError(ctx, libkbfs.WriteMode, err) }()
	if len(req.Data) == 0 {
		return nil
	}

	f.fs.config.BlockOps().TogglePrefetcher(f.enable)

	resp.Size = len(req.Data)
	return nil
}
687369
func (w *BatchedFileWriter) Write(p []byte) (n int, err error) {
	return w.file.Write(p)
}
1056178
func WriteData(pkg string, outFilePath string, tmpl *template.Template, data interface{}) (retErr error) {
	buffer := bytes.NewBuffer(nil)
	metadata := getMetadata(pkg, data)
	if err := tmpl.Execute(buffer, metadata); err != nil {
		return err
	}
	formatted, err := format.Source(buffer.Bytes())
	if err != nil {
		return err
	}
	file, err := os.Create(outFilePath)
	if err != nil {
		return err
	}
	defer func() {
		if err := file.Close(); err != nil && retErr == nil {
			retErr = err
		}
	}()
	if _, err := io.Copy(file, bytes.NewReader(formatted)); err != nil {
		return err
	}
	return nil
}