// writeControllerFiles generates controller files
764271
func writeControllerFiles(tables []*Table, cPath string, pkgPath string) {
	w := colors.NewColorWriter(os.Stdout)

	for _, tb := range tables {
		if tb.Pk == "" {
			continue
		}
		filename := getFileName(tb.Name)
		fpath := path.Join(cPath, filename+".go")
		var f *os.File
		var err error
		if utils.IsExist(fpath) {
			beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath)
			if utils.AskForConfirmation() {
				f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666)
				if err != nil {
					beeLogger.Log.Warnf("%s", err)
					continue
				}
			} else {
				beeLogger.Log.Warnf("Skipped create file '%s'", fpath)
				continue
			}
		} else {
			f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666)
			if err != nil {
				beeLogger.Log.Warnf("%s", err)
				continue
			}
		}
		fileStr := strings.Replace(CtrlTPL, "{{ctrlName}}", utils.CamelCase(tb.Name), -1)
		fileStr = strings.Replace(fileStr, "{{pkgPath}}", pkgPath, -1)
		if _, err := f.WriteString(fileStr); err != nil {
			beeLogger.Log.Fatalf("Could not write controller file to '%s': %s", fpath, err)
		}
		utils.CloseFile(f)
		fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m")
		utils.FormatSourceCode(fpath)
	}
}
918791
func (f *SyncFromServerFile) WriteFile(ctx context.Context, fi *dokan.FileInfo, bs []byte, offset int64) (n int, err error) {
	f.folder.fs.logEnter(ctx, "SyncFromServerFile Write")
	defer func() { f.folder.reportErr(ctx, libkbfs.WriteMode, err) }()
	if len(bs) == 0 {
		return 0, nil
	}
	folderBranch := f.folder.getFolderBranch()
	if folderBranch == (data.FolderBranch{}) {
		// Nothing to do.
		return len(bs), nil
	}
	err = f.folder.fs.config.KBFSOps().SyncFromServer(
		ctx, folderBranch, nil)
	if err != nil {
		return 0, err
	}
	f.folder.fs.NotificationGroupWait()
	return len(bs), nil
}
768406
func (m *MockSystemdServiceManager) WriteServiceFiles() error {
	ret := m.ctrl.Call(m, "WriteServiceFiles")
	ret0, _ := ret[0].(error)
	return ret0
}
822539
func (e *environ) ControllerInstances(ctx context.ProviderCallContext, controllerUUID string) ([]instance.Id, error) {
	return e.client.getControllerIds()
}
598620
func writeFile(path string, data []byte, mode os.FileMode) error {
	// Ensure that the parent directory is user-writable, since this is a
	// requirement in order to make modifications to that directory.
	parentDir := filepath.Dir(path)
	if err := filesystem.MakePathUserWritable(parentDir, nil); err != nil {
		return errors.Annotate(err, "failed to mark parent directory user-writable").
			InternalReason("path(%q)", parentDir).Err()
	}

	// Ensure that the target path doesn't already exist. Use filesystem.RemoveAll
	// in case it exists, but is not user-writable.
	if err := filesystem.RemoveAll(path); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path, data, mode); err != nil {
		return errors.Annotate(err, "could not write file contents").InternalReason("path(%q)", path).Err()
	}
	return nil
}
839965
func GenerateController(force, regen bool, appPkg, outDir, pkg, name string, r *design.ResourceDefinition) (filename string, err error) {
	filename = filepath.Join(outDir, codegen.SnakeCase(name)+".go")
	var (
		actionImpls      map[string]string
		extractedImports []*ast.ImportSpec
	)
	if regen {
		actionImpls, extractedImports, err = extractControllerBody(filename)
		if err != nil {
			return "", err
		}
		os.Remove(filename)
	}
	if force {
		os.Remove(filename)
	}
	if _, e := os.Stat(filename); e == nil {
		return "", nil
	}
	if err = os.MkdirAll(outDir, 0755); err != nil {
		return "", err
	}

	var file *codegen.SourceFile
	file, err = codegen.SourceFileFor(filename)
	if err != nil {
		return "", err
	}
	defer func() {
		file.Close()
		if err == nil {
			err = file.FormatCode()
		}
	}()

	elems := strings.Split(appPkg, "/")
	pkgName := elems[len(elems)-1]
	var imp string
	if _, err := codegen.PackageSourcePath(appPkg); err == nil {
		imp = appPkg
	} else {
		imp, err = codegen.PackagePath(outDir)
		if err != nil {
			return "", err
		}
		imp = path.Join(filepath.ToSlash(imp), appPkg)
	}

	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("io"),
		codegen.SimpleImport("github.com/goadesign/goa"),
		codegen.SimpleImport(imp),
		codegen.SimpleImport("golang.org/x/net/websocket"),
	}
	for _, imp := range extractedImports {
		// This may introduce duplicate imports of the defaults, but
		// that'll get worked out by Format later.
		var cgimp *codegen.ImportSpec
		path := strings.Trim(imp.Path.Value, `"`)
		if imp.Name != nil {
			cgimp = codegen.NewImport(imp.Name.Name, path)
		} else {
			cgimp = codegen.SimpleImport(path)
		}
		imports = append(imports, cgimp)
	}

	funcs := funcMap(pkgName, actionImpls)
	if err = file.WriteHeader("", pkg, imports); err != nil {
		return "", err
	}
	if err = file.ExecuteTemplate("controller", ctrlT, funcs, r); err != nil {
		return "", err
	}
	err = r.IterateActions(func(a *design.ActionDefinition) error {
		if a.WebSocket() {
			return file.ExecuteTemplate("actionWS", actionWST, funcs, a)
		}
		return file.ExecuteTemplate("action", actionT, funcs, a)
	})
	if err != nil {
		return "", err
	}
	return
}
393199
func WriteIgnores(filesystem fs.Filesystem, path string, content []string) error {
	fd, err := osutil.CreateAtomicFilesystem(filesystem, path)
	if err != nil {
		return err
	}

	for _, line := range content {
		fmt.Fprintln(fd, line)
	}

	if err := fd.Close(); err != nil {
		return err
	}
	filesystem.Hide(path)

	return nil
}
731665
func (s *store) AllControllers() (map[string]ControllerDetails, error) {
	releaser, err := s.acquireLock()
	if err != nil {
		return nil, errors.Annotate(err,
			"cannot acquire lock file to read all the controllers",
		)
	}
	defer releaser.Release()
	controllers, err := ReadControllersFile(JujuControllersPath())
	if err != nil {
		return nil, errors.Trace(err)
	}
	return controllers.Controllers, nil
}
1035236
func (r *Router) TemplateFiles(filenames ...string) {
	r.Lock()
	defer r.Unlock()
	r.views = template.Must(template.ParseFiles(filenames...))
}
1212913
func (g *Generator) generateControllers() (err error) {
	var (
		ctlFile string
		ctlWr   *ControllersWriter
	)
	{
		ctlFile = filepath.Join(g.OutDir, "controllers.go")
		ctlWr, err = NewControllersWriter(ctlFile)
		if err != nil {
			return
		}
	}
	defer func() {
		ctlWr.Close()
		if err == nil {
			err = ctlWr.FormatCode()
		}
	}()
	title := fmt.Sprintf("%s: Application Controllers", g.API.Context())
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("net/http"),
		codegen.SimpleImport("fmt"),
		codegen.SimpleImport("context"),
		codegen.SimpleImport("github.com/goadesign/goa"),
		codegen.SimpleImport("github.com/goadesign/goa/cors"),
		codegen.SimpleImport("regexp"),
		codegen.SimpleImport("strconv"),
		codegen.SimpleImport("time"),
		codegen.NewImport("uuid", "github.com/gofrs/uuid"),
	}
	encoders, err := BuildEncoders(g.API.Produces, true)
	if err != nil {
		return err
	}
	decoders, err := BuildEncoders(g.API.Consumes, false)
	if err != nil {
		return err
	}
	encoderImports := make(map[string]bool)
	for _, data := range encoders {
		encoderImports[data.PackagePath] = true
	}
	for _, data := range decoders {
		encoderImports[data.PackagePath] = true
	}
	var packagePaths []string
	for packagePath := range encoderImports {
		if packagePath != "github.com/goadesign/goa" {
			packagePaths = append(packagePaths, packagePath)
		}
	}
	sort.Strings(packagePaths)
	for _, packagePath := range packagePaths {
		imports = append(imports, codegen.SimpleImport(packagePath))
	}
	if err = ctlWr.WriteHeader(title, g.Target, imports); err != nil {
		return err
	}
	if err = ctlWr.WriteInitService(encoders, decoders); err != nil {
		return err
	}

	g.genfiles = append(g.genfiles, ctlFile)
	var controllersData []*ControllerTemplateData
	g.API.IterateResources(func(r *design.ResourceDefinition) error {
		// Create file servers for all directory file servers that serve index.html.
		fileServers := r.FileServers
		for _, fs := range r.FileServers {
			if fs.IsDir() {
				rpath := design.WildcardRegex.ReplaceAllLiteralString(fs.RequestPath, "")
				rpath += "/"
				fileServers = append(fileServers, &design.FileServerDefinition{
					Parent:      fs.Parent,
					Description: fs.Description,
					Docs:        fs.Docs,
					FilePath:    filepath.Join(fs.FilePath, "index.html"),
					RequestPath: rpath,
					Metadata:    fs.Metadata,
					Security:    fs.Security,
				})
			}
		}
		data := &ControllerTemplateData{
			API:            g.API,
			Resource:       codegen.Goify(r.Name, true),
			PreflightPaths: r.PreflightPaths(),
			FileServers:    fileServers,
		}
		r.IterateActions(func(a *design.ActionDefinition) error {
			context := fmt.Sprintf("%s%sContext", codegen.Goify(a.Name, true), codegen.Goify(r.Name, true))
			unmarshal := fmt.Sprintf("unmarshal%s%sPayload", codegen.Goify(a.Name, true), codegen.Goify(r.Name, true))
			action := map[string]interface{}{
				"Name":             codegen.Goify(a.Name, true),
				"DesignName":       a.Name,
				"Routes":           a.Routes,
				"Context":          context,
				"Unmarshal":        unmarshal,
				"Payload":          a.Payload,
				"PayloadOptional":  a.PayloadOptional,
				"PayloadMultipart": a.PayloadMultipart,
				"Security":         a.Security,
			}
			data.Actions = append(data.Actions, action)
			return nil
		})
		if len(data.Actions) > 0 || len(data.FileServers) > 0 {
			data.Encoders = encoders
			data.Decoders = decoders
			data.Origins = r.AllOrigins()
			controllersData = append(controllersData, data)
		}
		return nil
	})
	err = ctlWr.Execute(controllersData)
	return
}
736367
func ParseControllerConfig(bytes []byte) ([]string, error) {
	var controllerConfig Config
	if err := json.Unmarshal(bytes, &controllerConfig); err != nil {
		return []string{}, err
	}

	if controllerConfig.Values == nil {
		return []string{""}, nil
	}

	retVal := []string{}
	for k, v := range controllerConfig.Values {
		retVal = append(retVal, fmt.Sprintf(" -e %s=\"%v\"", k, v))
	}
	return retVal, nil
}
139480
func writeTaskData(ctl task.Controller, td *taskData) (err error) {
	if ctl.State().TaskData, err = json.Marshal(td); err != nil {
		return errors.Annotate(err, "could not serialize TaskData").Err()
	}
	return nil
}
1152525
func (m *Module) AddController(ct *ControllerType) {
	m.ControllerTypeList = append(m.ControllerTypeList, ct)
}
1169062
func (f *SyncControlFile) WriteFile(ctx context.Context,
	fi *dokan.FileInfo, bs []byte, offset int64) (n int, err error) {
	f.folder.fs.logEnter(ctx,
		fmt.Sprintf("SyncControlFile (f.action=%s) Write", f.action))
	defer func() { f.folder.reportErr(ctx, libkbfs.WriteMode, err) }()
	if len(bs) == 0 {
		return 0, nil
	}

	err = f.action.Execute(
		ctx, f.folder.fs.config, f.folder.getFolderBranch(), f.folder.h)
	if err != nil {
		return 0, err
	}

	return len(bs), nil
}
679155
func writeRouterFile(tables []*Table, rPath string, pkgPath string) {
	w := colors.NewColorWriter(os.Stdout)

	var nameSpaces []string
	for _, tb := range tables {
		if tb.Pk == "" {
			continue
		}
		// Add namespaces
		nameSpace := strings.Replace(NamespaceTPL, "{{nameSpace}}", tb.Name, -1)
		nameSpace = strings.Replace(nameSpace, "{{ctrlName}}", utils.CamelCase(tb.Name), -1)
		nameSpaces = append(nameSpaces, nameSpace)
	}
	// Add export controller
	fpath := filepath.Join(rPath, "router.go")
	routerStr := strings.Replace(RouterTPL, "{{nameSpaces}}", strings.Join(nameSpaces, ""), 1)
	routerStr = strings.Replace(routerStr, "{{pkgPath}}", pkgPath, 1)
	var f *os.File
	var err error
	if utils.IsExist(fpath) {
		beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath)
		if utils.AskForConfirmation() {
			f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666)
			if err != nil {
				beeLogger.Log.Warnf("%s", err)
				return
			}
		} else {
			beeLogger.Log.Warnf("Skipped create file '%s'", fpath)
			return
		}
	} else {
		f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666)
		if err != nil {
			beeLogger.Log.Warnf("%s", err)
			return
		}
	}
	if _, err := f.WriteString(routerStr); err != nil {
		beeLogger.Log.Fatalf("Could not write router file to '%s': %s", fpath, err)
	}
	utils.CloseFile(f)
	fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m")
	utils.FormatSourceCode(fpath)
}
165848
func (e *environ) DestroyController(ctx context.ProviderCallContext, controllerUUID string) error {
	// In case any hosted environment hasn't been cleaned up yet,
	// we also attempt to delete their resources when the controller
	// environment is destroyed.
	if err := e.destroyControllerManagedEnvirons(ctx, controllerUUID); err != nil {
		return errors.Annotate(err, "destroying managed environs")
	}
	return e.Destroy(ctx)
}
706758
func (c *Client) ControllerInfo() (*ControllerInfo, error) {
	var results params.ControllerAPIInfoResults
	if err := c.facade.FacadeCall("ControllerInfo", nil, &results); err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != 1 {
		return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
	}
	if err := results.Results[0].Error; err != nil {
		return nil, errors.Trace(err)
	}
	info := results.Results[0]
	return &ControllerInfo{
		Addrs:  info.Addresses,
		CACert: info.CACert,
	}, nil
}