// ArchiveFile compresses a file/directory to a file
//
// See Archive() doc
429417
func ArchiveFile(inFilePath string, outFilePath string, progress ProgressFunc) error {
	outFile, err := os.Create(outFilePath)
	if err != nil {
		return err
	}
	defer func() {
		_ = outFile.Close()
	}()

	return Archive(inFilePath, outFile, progress)
}
30344
func (d Dir) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
	if name = d.resolve(name); name == "" {
		return nil, os.ErrNotExist
	}
	f, err := os.OpenFile(name, flag, perm)
	if err != nil {
		return nil, err
	}
	return f, nil
}
180438
func (l *Ledis) DumpFile(path string) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()

	return l.Dump(f)
}
227975
func (s *EventService) ArchiveEvents(p *ArchiveEventsParams) (*ArchiveEventsResponse, error) {
	resp, err := s.cs.newRequest("archiveEvents", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ArchiveEventsResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
868780
func (v Simple) Archive(filePath string) error {
	err := archiveFile(v.folderFs, v.versionsFs, filePath, TagFilename)
	if err != nil {
		return err
	}

	file := filepath.Base(filePath)
	dir := filepath.Dir(filePath)

	// Glob according to the new file~timestamp.ext pattern.
	pattern := filepath.Join(dir, TagFilename(file, TimeGlob))
	newVersions, err := v.versionsFs.Glob(pattern)
	if err != nil {
		l.Warnln("globbing:", err, "for", pattern)
		return nil
	}

	// Also according to the old file.ext~timestamp pattern.
	pattern = filepath.Join(dir, file+"~"+TimeGlob)
	oldVersions, err := v.versionsFs.Glob(pattern)
	if err != nil {
		l.Warnln("globbing:", err, "for", pattern)
		return nil
	}

	// Use all the found filenames. "~" sorts after "." so all old pattern
	// files will be deleted before any new, which is as it should be.
	versions := util.UniqueStrings(append(oldVersions, newVersions...))

	if len(versions) > v.keep {
		for _, toRemove := range versions[:len(versions)-v.keep] {
			l.Debugln("cleaning out", toRemove)
			err = v.versionsFs.Remove(toRemove)
			if err != nil {
				l.Warnln("removing old version:", err)
			}
		}
	}

	return nil
}
634543
func (filebox *Filebox) AccessFile(filePath string, roles ...string) *File {
	file := &File{FilePath: filepath.Join(filebox.BaseDir, filePath), Roles: roles, Filebox: filebox}
	file.Dir = filebox.AccessDir(filepath.Dir(filePath), roles...)
	return file
}
1349313
func CopyFile(source string, destination string) error {
	reader, err := os.Open(source)

	if err != nil {
		return errFileOpen.Format(err.Error())
	}

	defer reader.Close()

	writer, err := os.Create(destination)
	if err != nil {
		return errFileCreate.Format(err.Error())
	}

	defer writer.Close()

	_, err = io.Copy(writer, reader)
	if err != nil {
		return errFileCopy.Format(err.Error())
	}

	err = writer.Sync()
	if err != nil {
		return errFileCopy.Format(err.Error())
	}

	return nil
}
30938
func CloseFile(err error, f io.Closer) error {
	if lerr := f.Close(); lerr != nil && err == nil {
		err = lerr
	}
	return err
}
637386
func LoadFile(filename string) (File, error) {
	file := make(File)
	err := file.LoadFile(filename)
	return file, err
}
586614
func (m *UnpartitionedMemoryIdx) UpdateArchive(archive idx.Archive) {
	m.Lock()
	defer m.Unlock()
	if _, ok := m.defById[archive.Id]; !ok {
		return
	}
	*(m.defById[archive.Id]) = archive
}
827624
func openArchive(u string) (Archive, error) {
	var (
		r      io.Reader
		closer io.Closer
	)

	if strings.HasPrefix(u, "https://") || strings.HasPrefix(u, "http://") {
		resp, err := http.Get(u)
		if err != nil {
			return nil, err
		}
		if resp.StatusCode < 200 || resp.StatusCode >= 300 {
			b, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1024))
			resp.Body.Close()
			if err != nil {
				return nil, err
			}
			return nil, &url.Error{
				Op:  "Get",
				URL: u,
				Err: fmt.Errorf("%s: %s", resp.Status, string(b)),
			}
		}
		closer = resp.Body
		r = resp.Body
		if resp.Header.Get("Content-Type") == "application/x-gzip" {
			r, err = gzip.NewReader(r)
			if err != nil {
				resp.Body.Close()
				return nil, err
			}
		}
	} else if u == "-" {
		r = os.Stdin
	} else {
		f, err := os.Open(u)
		if err != nil {
			return nil, err
		}
		closer = f
		r = f
	}

	return &tarArchive{
		tr:     tar.NewReader(r),
		closer: closer,
	}, nil
}
363337
func (c Consolidator) Archive() schema.Method {
	switch c {
	case None:
		panic("cannot get an archive for no consolidation")
	case Avg:
		panic("avg consolidator has no matching Archive(). you need sum and cnt")
	case Cnt:
		return schema.Cnt
	case Lst:
		return schema.Lst
	case Min:
		return schema.Min
	case Max:
		return schema.Max
	case Sum:
		return schema.Sum
	}
	panic(fmt.Sprintf("Consolidator.Archive(): unknown consolidator %q", c))
}
534395
func (fc FileCompressor) DecompressFile(source, destination string) error {
	if fc.Decompressor == nil {
		return fmt.Errorf("no decompressor specified")
	}
	if !fc.OverwriteExisting && fileExists(destination) {
		return fmt.Errorf("file exists: %s", destination)
	}

	in, err := os.Open(source)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(destination)
	if err != nil {
		return err
	}
	defer out.Close()

	return fc.Decompress(in, out)
}
867686
func (v External) Archive(filePath string) error {
	info, err := v.filesystem.Lstat(filePath)
	if fs.IsNotExist(err) {
		l.Debugln("not archiving nonexistent file", filePath)
		return nil
	} else if err != nil {
		return err
	}
	if info.IsSymlink() {
		panic("bug: attempting to version a symlink")
	}

	l.Debugln("archiving", filePath)

	if v.command == "" {
		return errors.New("Versioner: command is empty, please enter a valid command")
	}

	words, err := shellquote.Split(v.command)
	if err != nil {
		return errors.New("Versioner: command is invalid: " + err.Error())
	}

	context := map[string]string{
		"%FOLDER_FILESYSTEM%": v.filesystem.Type().String(),
		"%FOLDER_PATH%":       v.filesystem.URI(),
		"%FILE_PATH%":         filePath,
	}

	for i, word := range words {
		if replacement, ok := context[word]; ok {
			words[i] = replacement
		}
	}

	cmd := exec.Command(words[0], words[1:]...)
	env := os.Environ()
	// filter STGUIAUTH and STGUIAPIKEY from environment variables
	filteredEnv := []string{}
	for _, x := range env {
		if !strings.HasPrefix(x, "STGUIAUTH=") && !strings.HasPrefix(x, "STGUIAPIKEY=") {
			filteredEnv = append(filteredEnv, x)
		}
	}
	cmd.Env = filteredEnv
	combinedOutput, err := cmd.CombinedOutput()
	l.Debugln("external command output:", string(combinedOutput))
	if err != nil {
		return err
	}

	// return error if the file was not removed
	if _, err = v.filesystem.Lstat(filePath); fs.IsNotExist(err) {
		return nil
	}
	return errors.New("Versioner: file was not removed by external script")
}
515169
func (z *ZipArchive) extractFile(f *File) error {
	if !z.isHasWriter {
		for _, zf := range z.ReadCloser.File {
			if f.Name == zf.Name {
				return extractFile(zf, path.Dir(f.tmpPath))
			}
		}
	}
	return cae.Copy(f.tmpPath, f.absPath)
}
373733
func (repo *Repository) Archive(revision string, w io.Writer, files ...string) (int64, error) {
	if err := repo.Init(); err != nil {
		return 0, err
	}
	args := append([]string{"archive", "--format=tar.gz", revision}, files...)
	cmd := repo.createGitCommand(args...)
	stderr := &bytes.Buffer{}
	cmd.Stderr = stderr
	cnt := &counter{}
	cmd.Stdout = io.MultiWriter(w, cnt)
	if err := cmd.Run(); err != nil {
		return 0, fmt.Errorf("%s: %s", err, stderr.String())
	}
	return cnt.cnt, nil
}
491849
func (i IndexFile) WriteFile(dest string, mode os.FileMode) error {
	b, err := yaml.Marshal(i)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(dest, b, mode)
}