// Prepare prepares the source code and tar for build.
// NOTE: this func serves both the sti and onbuild strategies, as the OnBuild
// struct Build func leverages the STI struct Prepare func directly below.
349720
func (builder *Dockerfile) Prepare(config *api.Config) error {
	var err error

	if len(config.WorkingDir) == 0 {
		if config.WorkingDir, err = builder.fs.CreateWorkingDirectory(); err != nil {
			builder.setFailureReason(utilstatus.ReasonFSOperationFailed, utilstatus.ReasonMessageFSOperationFailed)
			return err
		}
	}

	builder.result.WorkingDir = config.WorkingDir

	// Setup working directories
	for _, v := range workingDirs {
		if err = builder.fs.MkdirAllWithPermissions(filepath.Join(config.WorkingDir, v), 0755); err != nil {
			builder.setFailureReason(utilstatus.ReasonFSOperationFailed, utilstatus.ReasonMessageFSOperationFailed)
			return err
		}
	}

	// Default - install scripts specified by image metadata.
	// Typically this will point to an image:// URL, and no scripts are downloaded.
	// However, this is not guaranteed.
	builder.installScripts(config.ImageScriptsURL, config)

	// Fetch sources, since their .s2i/bin might contain s2i scripts which override defaults.
	if config.Source != nil {
		downloader, err := scm.DownloaderForSource(builder.fs, config.Source, config.ForceCopy)
		if err != nil {
			builder.setFailureReason(utilstatus.ReasonFetchSourceFailed, utilstatus.ReasonMessageFetchSourceFailed)
			return err
		}
		if builder.sourceInfo, err = downloader.Download(config); err != nil {
			builder.setFailureReason(utilstatus.ReasonFetchSourceFailed, utilstatus.ReasonMessageFetchSourceFailed)
			switch err.(type) {
			case file.RecursiveCopyError:
				return fmt.Errorf("input source directory contains the target directory for the build, check that your Dockerfile output path does not reside within your input source path: %v", err)
			}
			return err
		}
		if config.SourceInfo != nil {
			builder.sourceInfo = config.SourceInfo
		}
	}

	// Install scripts provided by user, overriding all others.
	// This _could_ be an image:// URL, which would override any scripts above.
	urlScripts := builder.installScripts(config.ScriptsURL, config)
	// If a ScriptsURL was specified, but no scripts were downloaded from it, throw an error
	if len(config.ScriptsURL) > 0 {
		failedCount := 0
		for _, result := range urlScripts {
			if util.Includes(result.FailedSources, scripts.ScriptURLHandler) {
				failedCount++
			}
		}
		if failedCount == len(urlScripts) {
			builder.result.BuildInfo.FailureReason = utilstatus.NewFailureReason(
				utilstatus.ReasonScriptsFetchFailed,
				utilstatus.ReasonMessageScriptsFetchFailed,
			)
			return fmt.Errorf("could not download any scripts from URL %v", config.ScriptsURL)
		}
	}

	// Stage any injection(secrets) content into the working dir so the dockerfile can reference it.
	for i, injection := range config.Injections {
		// strip the C: from windows paths because it's not valid in the middle of a path
		// like upload/injections/C:/tempdir/injection1
		trimmedSrc := strings.TrimPrefix(injection.Source, filepath.VolumeName(injection.Source))
		dst := filepath.Join(config.WorkingDir, constants.Injections, trimmedSrc)
		glog.V(4).Infof("Copying injection content from %s to %s", injection.Source, dst)
		if err := builder.fs.CopyContents(injection.Source, dst); err != nil {
			builder.setFailureReason(utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed)
			return err
		}
		config.Injections[i].Source = trimmedSrc
	}

	// see if there is a .s2iignore file, and if so, read in the patterns and then
	// search and delete on them.
	err = builder.ignorer.Ignore(config)
	if err != nil {
		builder.setFailureReason(utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed)
		return err
	}
	return nil
}
1229180
func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error {
	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
	if parent == nil {
		return consensus.ErrUnknownAncestor
	}
	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
	return nil
}
773353
func (c *boltConn) Prepare(query string) (driver.Stmt, error) {
	return c.prepare(query)
}
786862
func (c *CrateDriver) Prepare(query string) (driver.Stmt, error) {
	stmt := &CrateStmt{
		stmt:   query,
		driver: c,
	}

	return stmt, nil
}
85606
func (c *PrlctlVersionConfig) Prepare(ctx *interpolate.Context) []error {
	if c.PrlctlVersionFile == "" {
		c.PrlctlVersionFile = ".prlctl_version"
	}

	return nil
}
980372
func (c *PrlctlConfig) Prepare(ctx *interpolate.Context) []error {
	if c.Prlctl == nil {
		c.Prlctl = make([][]string, 0)
	}

	return nil
}
487668
func (p *Provisioner) Prepare(raws ...interface{}) error {
	err := config.Decode(
		&p.config,
		&config.DecodeOpts{
			Interpolate:        true,
			InterpolateContext: &p.config.ctx,
			InterpolateFilter: &interpolate.RenderFilter{
				Exclude: []string{
					"execute_command",
					"bootstrap_command",
				},
			},
		},
		raws...,
	)
	if err != nil {
		return err
	}

	// require a single module
	if p.config.Module == "" {
		return errors.New("Converge requires a module to provision the system")
	}

	// set defaults
	if p.config.WorkingDirectory == "" {
		p.config.WorkingDirectory = "/tmp"
	}

	if p.config.ExecuteCommand == "" {
		p.config.ExecuteCommand = "cd {{.WorkingDirectory}} && {{if .Sudo}}sudo {{end}}converge apply --local --log-level=WARNING --paramsJSON '{{.ParamsJSON}}' {{.Module}}"
	}

	if p.config.BootstrapCommand == "" {
		p.config.BootstrapCommand = "curl -s https://get.converge.sh | {{if .Sudo}}sudo {{end}}sh {{if ne .Version \"\"}}-s -- -v {{.Version}}{{end}}"
	}

	// validate sources and destinations
	for i, dir := range p.config.ModuleDirs {
		if dir.Source == "" {
			return fmt.Errorf("Source (\"source\" key) is required in Converge module dir #%d", i)
		}
		if dir.Destination == "" {
			return fmt.Errorf("Destination (\"destination\" key) is required in Converge module dir #%d", i)
		}
	}

	return err
}
416286
func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) {
	return pf(r)
}
1330521
func (m *MySQLBackend) prepare(name, query string) error {
	stmt, err := m.client.Prepare(query)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err)
	}
	m.statements[name] = stmt
	return nil
}
623500
func (c *SourceMachineConfig) Prepare(ctx *interpolate.Context) []error {
	var errs []error

	if c.MachinePackage == "" {
		errs = append(errs, fmt.Errorf("A source_machine_package must be specified"))
	}

	if c.MachineImage != "" && c.MachineImageFilters.Name != "" {
		errs = append(errs, fmt.Errorf("You cannot specify a Machine Image and also Machine Name filter"))
	}

	if c.MachineNetworks == nil {
		c.MachineNetworks = []string{}
	}

	if c.MachineMetadata == nil {
		c.MachineMetadata = make(map[string]string)
	}

	if c.MachineTags == nil {
		c.MachineTags = make(map[string]string)
	}

	if len(errs) > 0 {
		return errs
	}

	return nil
}
565244
func Prepare(db *sql.DB) (err error) {
	for _, s := range preExecStmts {
		if _, err := db.Exec(s); err != nil {
			log.Println("    ", err)
		}
	}
	return nil
}
1189238
func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
	defer b.imageSources.Unmount()

	stages, metaArgs, err := instructions.Parse(dockerfile.AST)
	if err != nil {
		if instructions.IsUnknownInstruction(err) {
			buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
		}
		return nil, errdefs.InvalidParameter(err)
	}
	if b.options.Target != "" {
		targetIx, found := instructions.HasStage(stages, b.options.Target)
		if !found {
			buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc()
			return nil, errdefs.InvalidParameter(errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target))
		}
		stages = stages[:targetIx+1]
	}

	// Add 'LABEL' command specified by '--label' option to the last stage
	buildLabelOptions(b.options.Labels, stages)

	dockerfile.PrintWarnings(b.Stderr)
	dispatchState, err := b.dispatchDockerfileWithCancellation(stages, metaArgs, dockerfile.EscapeToken, source)
	if err != nil {
		return nil, err
	}
	if dispatchState.imageID == "" {
		buildsFailed.WithValues(metricsDockerfileEmptyError).Inc()
		return nil, errors.New("No image was generated. Is your Dockerfile empty?")
	}
	return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
}
716186
func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error {
	if err := os.MkdirAll(common.AppsInfoPath(dir), common.DefaultRegularDirPerm); err != nil {
		return errwrap.Wrap(errors.New("error creating apps info directory"), err)
	}
	debug("Preparing stage1")
	if err := prepareStage1Image(cfg, dir); err != nil {
		return errwrap.Wrap(errors.New("error preparing stage1"), err)
	}

	var pmb []byte
	var err error
	if len(cfg.PodManifest) > 0 {
		pmb, err = validatePodManifest(cfg, dir)
	} else {
		pmb, err = generatePodManifest(cfg, dir)
	}
	if err != nil {
		return err
	}

	cfg.CommonConfig.ManifestData = string(pmb)

	// create pod lock file for app add/rm operations.
	f, err := os.OpenFile(common.PodManifestLockPath(dir), os.O_CREATE|os.O_RDWR, 0600)
	if err != nil {
		return err
	}
	f.Close()

	debug("Writing pod manifest")
	fn := common.PodManifestPath(dir)
	if err := ioutil.WriteFile(fn, pmb, common.DefaultRegularFilePerm); err != nil {
		return errwrap.Wrap(errors.New("error writing pod manifest"), err)
	}

	f, err = os.OpenFile(common.PodCreatedPath(dir), os.O_CREATE|os.O_RDWR, common.DefaultRegularFilePerm)
	if err != nil {
		return err
	}
	f.Close()

	if cfg.UseOverlay {
		// mark the pod as prepared with overlay
		f, err := os.Create(filepath.Join(dir, common.OverlayPreparedFilename))
		if err != nil {
			return errwrap.Wrap(errors.New("error writing overlay marker file"), err)
		}
		defer f.Close()
	}

	if cfg.PrivateUsers.Shift > 0 {
		// mark the pod as prepared for user namespaces
		uidrangeBytes := cfg.PrivateUsers.Serialize()

		if err := ioutil.WriteFile(filepath.Join(dir, common.PrivateUsersPreparedFilename), uidrangeBytes, common.DefaultRegularFilePerm); err != nil {
			return errwrap.Wrap(errors.New("error writing userns marker file"), err)
		}
	}

	return nil
}
1277594
func (h *HTTPTester) Prepare(stmt string, bSz int, tx bool) error {
	s := make([]string, bSz)
	for i := 0; i < len(s); i++ {
		s[i] = stmt
	}

	b, err := json.Marshal(s)
	if err != nil {
		return err
	}
	h.br = bytes.NewReader(b)

	if tx {
		h.url = h.url + "?transaction"
	}

	return nil
}
128186
func (s *BlockingSender) Prepare(ctx context.Context, plaintext chat1.MessagePlaintext,
	membersType chat1.ConversationMembersType, conv *chat1.Conversation, inopts *chat1.SenderPrepareOptions) (res types.SenderPrepareResult, err error) {
	if plaintext.ClientHeader.MessageType == chat1.MessageType_NONE {
		return res, fmt.Errorf("cannot send message without type")
	}
	// set default options unless some are given to us
	var opts chat1.SenderPrepareOptions
	if inopts != nil {
		opts = *inopts
	}

	msg, uid, err := s.addSenderToMessage(plaintext)
	if err != nil {
		return res, err
	}

	// Make sure our delete message gets everything it should
	var pendingAssetDeletes []chat1.Asset
	if conv != nil {
		convID := (*conv).GetConvID()
		msg.ClientHeader.Conv = conv.Metadata.IdTriple
		s.Debug(ctx, "Prepare: performing convID based checks")

		// Check for outboxID based edits
		if err = s.resolveOutboxIDEdit(ctx, uid, convID, &msg); err != nil {
			s.Debug(ctx, "Prepare: error resolving outboxID edit: %s", err)
			return res, err
		}

		// Add and check prev pointers
		msg, err = s.addPrevPointersAndCheckConvID(ctx, msg, *conv)
		if err != nil {
			s.Debug(ctx, "Prepare: error adding prev pointers: %s", err)
			return res, err
		}

		// First process the reactionMessage in case we convert it to a delete
		header, body, err := s.processReactionMessage(ctx, uid, convID, msg)
		if err != nil {
			s.Debug(ctx, "Prepare: error processing reactions: %s", err)
			return res, err
		}
		msg.ClientHeader = header
		msg.MessageBody = body

		// Handle reply to
		msg = s.handleReplyTo(ctx, msg, opts.ReplyTo)

		// Be careful not to shadow (msg, pendingAssetDeletes) with this assignment.
		msg, pendingAssetDeletes, err = s.getAllDeletedEdits(ctx, uid, convID, msg)
		if err != nil {
			s.Debug(ctx, "Prepare: error getting deleted edits: %s", err)
			return res, err
		}

		// If no ephemeral data set, then let's double check to make sure no exploding policy
		// or Gregor state should set it
		if msg.EphemeralMetadata() == nil && chat1.IsEphemeralNonSupersederType(msg.ClientHeader.MessageType) {
			s.Debug(ctx, "Prepare: attempting to set ephemeral policy from conversation")
			elf, err := utils.EphemeralLifetimeFromConv(ctx, s.G(), *conv)
			if err != nil {
				s.Debug(ctx, "Prepare: failed to get ephemeral lifetime from conv: %s", err)
				elf = nil
			}
			if elf != nil {
				s.Debug(ctx, "Prepare: setting ephemeral lifetime from conv: %v", *elf)
				msg.ClientHeader.EphemeralMetadata = &chat1.MsgEphemeralMetadata{
					Lifetime: *elf,
				}
			}
		}

		metadata, err := s.getSupersederEphemeralMetadata(ctx, uid, convID, msg)
		if err != nil {
			s.Debug(ctx, "Prepare: error getting superseder ephemeral metadata: %s", err)
			return res, err
		}
		msg.ClientHeader.EphemeralMetadata = metadata
	}

	// Make sure it is a proper length
	if err := msgchecker.CheckMessagePlaintext(msg); err != nil {
		return res, err
	}

	// Get topic name state if this is a METADATA message, so that we avoid any races to the
	// server
	var topicNameState *chat1.TopicNameState
	if !opts.SkipTopicNameState {
		if topicNameState, err = s.checkTopicNameAndGetState(ctx, msg, membersType); err != nil {
			s.Debug(ctx, "Prepare: error checking topic name state: %s", err)
			return res, err
		}
	}

	// encrypt the message
	skp, err := s.getSigningKeyPair(ctx)
	if err != nil {
		s.Debug(ctx, "Prepare: error getting signing key pair: %s", err)
		return res, err
	}

	// Function to check that the header and body types match.
	// Call this before accessing the body.
	// Do not call this for TLFNAME which has no body.
	checkHeaderBodyTypeMatch := func() error {
		bodyType, err := plaintext.MessageBody.MessageType()
		if err != nil {
			return err
		}
		if plaintext.ClientHeader.MessageType != bodyType {
			return fmt.Errorf("cannot send message with mismatched header/body types: %v != %v",
				plaintext.ClientHeader.MessageType, bodyType)
		}
		return nil
	}

	// find @ mentions
	var atMentions []gregor1.UID
	chanMention := chat1.ChannelMention_NONE
	if msg.ClientHeader.Conv.TopicType == chat1.TopicType_CHAT {
		switch plaintext.ClientHeader.MessageType {
		case chat1.MessageType_TEXT:
			if err = checkHeaderBodyTypeMatch(); err != nil {
				return res, err
			}
			atMentions, _, chanMention = utils.GetTextAtMentionedItems(ctx, s.G(),
				plaintext.MessageBody.Text(), &s.DebugLabeler)
		case chat1.MessageType_FLIP:
			if err = checkHeaderBodyTypeMatch(); err != nil {
				return res, err
			}
			atMentions, _, chanMention = utils.ParseAtMentionedItems(ctx, s.G(),
				plaintext.MessageBody.Flip().Text)
		case chat1.MessageType_EDIT:
			if err = checkHeaderBodyTypeMatch(); err != nil {
				return res, err
			}
			atMentions, _, chanMention = utils.ParseAtMentionedItems(ctx, s.G(),
				plaintext.MessageBody.Edit().Body)
		case chat1.MessageType_SYSTEM:
			if err = checkHeaderBodyTypeMatch(); err != nil {
				return res, err
			}
			atMentions, chanMention = utils.SystemMessageMentions(ctx, plaintext.MessageBody.System(),
				s.G().GetUPAKLoader())
		}
	}

	// If we are sending a message, and we think the conversation is a KBFS conversation, then set a label
	// on the client header in case this conversation gets upgrade to impteam.
	msg.ClientHeader.KbfsCryptKeysUsed = new(bool)
	if membersType == chat1.ConversationMembersType_KBFS {
		s.Debug(ctx, "setting KBFS crypt keys used flag")
		*msg.ClientHeader.KbfsCryptKeysUsed = true
	} else {
		*msg.ClientHeader.KbfsCryptKeysUsed = false
	}

	encInfo, err := s.boxer.GetEncryptionInfo(ctx, &msg, membersType, skp)
	if err != nil {
		return res, err
	}
	boxed, err := s.boxer.BoxMessage(ctx, msg, membersType, skp, &encInfo)
	if err != nil {
		return res, err
	}
	return types.SenderPrepareResult{
		Boxed:               boxed,
		EncryptionInfo:      encInfo,
		PendingAssetDeletes: pendingAssetDeletes,
		AtMentions:          atMentions,
		ChannelMention:      chanMention,
		TopicNameState:      topicNameState,
	}, nil
}
1219012
func (ctx *HookContext) Prepare() error {
	if ctx.actionData != nil {
		err := ctx.state.ActionBegin(ctx.actionData.Tag)
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}
1116349
func (w *writer) prepare() error {
	if w.prepared {
		return nil
	}
	req, err := http.NewRequest("POST", w.o.url("?uploads"), nil)
	if err != nil {
		return err
	}

	// detect mime type
	ext := filepath.Ext(w.o.key)
	contentType := "application/octet-stream"
	if v, ok := mimeTypes[ext]; ok {
		contentType = v
	}
	req.Header.Set(`Content-Type`, contentType)

	// sign and send
	w.o.s3.signRequest(req)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if c := resp.StatusCode; c != 200 {
		return newS3Error(resp, "could not create multipart upload: %d", c)
	}

	var result struct {
		UploadId string
	}
	err = xml.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return err
	}

	w.uploadId = result.UploadId
	w.prepared = true

	return nil
}