// CreateFile creates a File, associating an upload with a task.
354720
func (c oauthClient) CreateFile(uploadID uint, taskID uint) (wl.File, error) {
	if uploadID == 0 {
		return wl.File{}, errors.New("uploadID must be > 0")
	}

	if taskID == 0 {
		return wl.File{}, errors.New("taskID must be > 0")
	}

	body := []byte(fmt.Sprintf(`{"upload_id":%d,"task_id":%d}`, uploadID, taskID))

	url := fmt.Sprintf("%s/files", c.apiURL)

	req, err := c.newPostRequest(url, body)
	if err != nil {
		return wl.File{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.File{}, err
	}
	if err != nil {
		return wl.File{}, err
	}

	if resp.StatusCode != http.StatusCreated {
		return wl.File{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusCreated)
	}

	file := wl.File{}
	err = json.NewDecoder(resp.Body).Decode(&file)
	if err != nil {
		return wl.File{}, err
	}
	return file, nil
}
304265
func (self *HttpClient) UploadFile(method, path, fileParam, filePath string, payload []byte, params map[string]string, headers map[string]string) (*HttpResponse, error) {
	var reader io.Reader

	if payload == nil {
		file, err := os.Open(filePath)
		if err != nil {
			return nil, err
		}
		defer file.Close()
		reader = file
	} else {
		reader = bytes.NewReader(payload)
	}

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(fileParam, filepath.Base(filePath))
	if err == nil {
		_, err = io.Copy(part, reader)
	}
	if err == nil {
		for key, val := range params {
			writer.WriteField(key, val)
		}
		err = writer.Close()
	}
	if err != nil {
		return nil, err
	}

	if headers == nil {
		headers = map[string]string{}
	}

	headers["Content-Type"] = writer.FormDataContentType()
	headers["Content-Length"] = strconv.Itoa(body.Len())
	req := self.Request(method, path, body, headers)

	return self.Do(req)
}
153727
func (api *ImagesAPI) CreateFromFile(imagePath string, options *ImageCreateOptions) (task *Task, err error) {
	params := imageCreateOptionsToMap(options)
	res, err := api.client.restClient.MultipartUploadFile(api.client.Endpoint+imageUrl, imagePath, params, api.client.options.TokenOptions)
	if err != nil {
		return
	}
	defer res.Body.Close()
	result, err := getTask(getError(res))
	return result, err
}
797469
func (u *ConcurrentUploader) UploadFile(item *Item, ps *isolatedclient.PushState, done func()) {
	u.wg.Add(1)
	go u.upload(item.RelPath, fileSource(item.Path), ps, done)
}
1098585
func OpenFile(path string) error {
	path, err := filepath.Abs(path)
	if err != nil {
		return err
	}
	return OpenURL("file://" + path)
}
149841
func (c *Files) CreateFolder(in *CreateFolderInput) (out *CreateFolderOutput, err error) {
	body, err := c.call("/files/create_folder", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}
1072361
func (dir *Dir) WriteFile(fileName string, reader io.Reader) (file *File, err error) {
	if err = dir.createIfNoExist(); err == nil {
		relativeDir := strings.TrimPrefix(dir.DirPath, dir.Filebox.BaseDir)
		file = dir.Filebox.AccessFile(filepath.Join(relativeDir, fileName), dir.Roles...)
		err = file.Write(reader)
	}
	return
}
648532
func SumFile(filename string) ([Size]byte, error) {
	imo := New()
	return imo.SumFile(filename)
}
138382
func (c *Compiler) AddFile(file *os.File, namespace string) (err error) {
	if c.cptr.errors != 0 {
		return errors.New("Compiler cannot be used after parse error")
	}
	var ns *C.char
	if namespace != "" {
		ns = C.CString(namespace)
		defer C.free(unsafe.Pointer(ns))
	}
	filename := C.CString(file.Name())
	defer C.free(unsafe.Pointer(filename))
	id := callbackData.Put(c)
	defer callbackData.Delete(id)
	C.yr_compiler_set_callback(c.cptr, C.YR_COMPILER_CALLBACK_FUNC(C.compilerCallback), id)
	numErrors := int(C.yr_compiler_add_fd(c.cptr, (C.YR_FILE_DESCRIPTOR)(file.Fd()), ns, filename))
	if numErrors > 0 {
		var buf [1024]C.char
		msg := C.GoString(C.yr_compiler_get_error_message(
			c.cptr, (*C.char)(unsafe.Pointer(&buf[0])), 1024))
		err = errors.New(msg)
	}
	keepAlive(c)
	return
}
779101
func (c *Client) OpenFile(path string, f int) (*File, error) {
	return c.open(path, flags(f))
}
1274850
func (si *SegmentInfo) AddFile(file string) {
	si.checkFileNames(map[string]bool{file: true})
	si.files[file] = true
}
860777
func (c *Client) CreateEmptyFile(name string) error {
	f, err := c.Create(name)
	if err != nil {
		return err
	}

	return f.Close()
}
1107327
func createUploadStep(packagePath string) workflowStep {
	return func(ctx *workflowContext) (workflowStep, error) {
		defer recordDuration(time.Now(), "Uploading code", ctx)

		var uploadTasks []*workTask
		if len(ctx.userdata.lambdaAWSInfos) != 0 {
			// We always upload the primary binary...
			uploadBinaryTask := func() workResult {
				logFilesize("Lambda code archive size", packagePath, ctx.logger)

				// Create the S3 key...
				zipS3URL, zipS3URLErr := uploadLocalFileToS3(packagePath, "", ctx)
				if nil != zipS3URLErr {
					return newTaskResult(nil, zipS3URLErr)
				}
				ctx.context.s3CodeZipURL = newS3UploadURL(zipS3URL)
				return newTaskResult(ctx.context.s3CodeZipURL, nil)
			}
			uploadTasks = append(uploadTasks, newWorkTask(uploadBinaryTask))
		} else {
			ctx.logger.Info("Bypassing S3 upload as no Lambda functions were provided")
		}

		// We might need to upload some other things...
		if nil != ctx.userdata.s3SiteContext.s3Site {
			uploadSiteTask := func() workResult {
				tempName := fmt.Sprintf("%s-S3Site.zip", ctx.userdata.serviceName)
				tmpFile, err := system.TemporaryFile(ScratchDirectory, tempName)
				if err != nil {
					return newTaskResult(nil,
						errors.Wrapf(err, "Failed to create temporary S3 site archive file"))
				}

				// Add the contents to the Zip file
				zipArchive := zip.NewWriter(tmpFile)
				absResourcePath, err := filepath.Abs(ctx.userdata.s3SiteContext.s3Site.resources)
				if nil != err {
					return newTaskResult(nil, errors.Wrapf(err, "Failed to get absolute filepath"))
				}
				// Ensure that the directory exists...
				_, existsErr := os.Stat(ctx.userdata.s3SiteContext.s3Site.resources)
				if existsErr != nil && os.IsNotExist(existsErr) {
					return newTaskResult(nil,
						errors.Wrapf(existsErr,
							"TheS3 Site resources directory (%s) does not exist",
							ctx.userdata.s3SiteContext.s3Site.resources))
				}

				ctx.logger.WithFields(logrus.Fields{
					"S3Key":      path.Base(tmpFile.Name()),
					"SourcePath": absResourcePath,
				}).Info("Creating S3Site archive")

				err = spartaZip.AddToZip(zipArchive, absResourcePath, absResourcePath, ctx.logger)
				if nil != err {
					return newTaskResult(nil, err)
				}
				errClose := zipArchive.Close()
				if errClose != nil {
					return newTaskResult(nil, errClose)
				}

				// Upload it & save the key
				s3SiteLambdaZipURL, s3SiteLambdaZipURLErr := uploadLocalFileToS3(tmpFile.Name(), "", ctx)
				if s3SiteLambdaZipURLErr != nil {
					return newTaskResult(nil,
						errors.Wrapf(s3SiteLambdaZipURLErr, "Failed to upload local file to S3"))
				}
				ctx.userdata.s3SiteContext.s3UploadURL = newS3UploadURL(s3SiteLambdaZipURL)
				return newTaskResult(ctx.userdata.s3SiteContext.s3UploadURL, nil)
			}
			uploadTasks = append(uploadTasks, newWorkTask(uploadSiteTask))

		}

		// Run it and figure out what happened
		p := newWorkerPool(uploadTasks, len(uploadTasks))
		_, uploadErrors := p.Run()

		if len(uploadErrors) > 0 {
			return nil, errors.Errorf("Encountered multiple errors during upload: %#v", uploadErrors)
		}
		return validateSpartaPostconditions(), nil
	}
}
1355806
func touchFile(p string) error {
	_, err := os.Create(p)
	return err
}
130597
func (d *Driver) createImage(task *drivers.TaskConfig, driverConfig *TaskConfig, client *docker.Client) (string, error) {
	image := driverConfig.Image
	repo, tag := parseDockerImage(image)

	callerID := fmt.Sprintf("%s-%s", task.ID, task.Name)

	// We're going to check whether the image is already downloaded. If the tag
	// is "latest", or ForcePull is set, we have to check for a new version every time so we don't
	// bother to check and cache the id here. We'll download first, then cache.
	if driverConfig.ForcePull {
		d.logger.Debug("force pulling image instead of inspecting local", "image_ref", dockerImageRef(repo, tag))
	} else if tag != "latest" {
		if dockerImage, _ := client.InspectImage(image); dockerImage != nil {
			// Image exists so just increment its reference count
			d.coordinator.IncrementImageReference(dockerImage.ID, image, callerID)
			return dockerImage.ID, nil
		}
	}

	// Load the image if specified
	if driverConfig.LoadImage != "" {
		return d.loadImage(task, driverConfig, client)
	}

	// Download the image
	return d.pullImage(task, driverConfig, client, repo, tag)
}
1206791
func NewUploadTaskFile(ctx *middleware.Context, handler UploadTaskFileHandler) *UploadTaskFile {
	return &UploadTaskFile{Context: ctx, Handler: handler}
}
239338
func addFormFile(writer *multipart.Writer, name, path string) error {
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()
	part, err := writer.CreateFormFile(name, filepath.Base(path))
	if err != nil {
		return err
	}

	_, err = io.Copy(part, file)

	return err
}