示例#1
0
文件: targz.go 项目: jeromer/haiconf
func createTar(source string) ([]byte, error) {
	buff := new(bytes.Buffer)
	nilBuff := []byte(nil)
	var err error

	tarWriter := tar.NewWriter(buff)

	// texas ranger :D
	walker := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		fi, err := os.Lstat(path)
		if err != nil {
			return err
		}

		mode := fi.Mode()

		link := ""
		if mode&os.ModeSymlink != 0 {
			link, err = os.Readlink(path)
			if err != nil {
				return err
			}
		}

		hdr, err := tar.FileInfoHeader(fi, link)
		if err != nil {
			return err
		}
		hdr.Name = path

		err = tarWriter.WriteHeader(hdr)
		if err != nil {
			return err
		}

		if !mode.IsRegular() {
			return nil
		}

		f, err := os.Open(path)
		if err != nil {
			return err
		}

		fbuff, err := ioutil.ReadAll(f)
		if err != nil {
			return err
		}
		f.Close()

		_, err = tarWriter.Write(fbuff)
		if err != nil {
			return err
		}

		return nil
	}

	err = filepath.Walk(source, walker)
	if err != nil {
		return nilBuff, err
	}

	err = tarWriter.Close()
	if err != nil {
		return nilBuff, err
	}

	return buff.Bytes(), nil
}
示例#2
0
func (ts *TarSum) Read(buf []byte) (int, error) {
	if ts.gz == nil {
		ts.bufTar = bytes.NewBuffer([]byte{})
		ts.bufGz = bytes.NewBuffer([]byte{})
		ts.tarR = tar.NewReader(ts.Reader)
		ts.tarW = tar.NewWriter(ts.bufTar)
		ts.gz = gzip.NewWriter(ts.bufGz)
		ts.h = sha256.New()
		//		ts.h = verboseHash{sha256.New()}
		ts.h.Reset()
		ts.first = true
	}

	if ts.finished {
		return ts.bufGz.Read(buf)
	}
	buf2 := make([]byte, len(buf), cap(buf))

	n, err := ts.tarR.Read(buf2)
	if err != nil {
		if err == io.EOF {
			if _, err := ts.h.Write(buf2[:n]); err != nil {
				return 0, err
			}
			if !ts.first {
				ts.sums = append(ts.sums, hex.EncodeToString(ts.h.Sum(nil)))
				ts.h.Reset()
			} else {
				ts.first = false
			}

			currentHeader, err := ts.tarR.Next()
			if err != nil {
				if err == io.EOF {
					if err := ts.gz.Close(); err != nil {
						return 0, err
					}
					ts.finished = true
					return n, nil
				}
				return n, err
			}
			if err := ts.encodeHeader(currentHeader); err != nil {
				return 0, err
			}
			if err := ts.tarW.WriteHeader(currentHeader); err != nil {
				return 0, err
			}
			if _, err := ts.tarW.Write(buf2[:n]); err != nil {
				return 0, err
			}
			ts.tarW.Flush()
			if _, err := io.Copy(ts.gz, ts.bufTar); err != nil {
				return 0, err
			}
			ts.gz.Flush()

			return ts.bufGz.Read(buf)
		}
		return n, err
	}

	// Filling the hash buffer
	if _, err = ts.h.Write(buf2[:n]); err != nil {
		return 0, err
	}

	// Filling the tar writter
	if _, err = ts.tarW.Write(buf2[:n]); err != nil {
		return 0, err
	}
	ts.tarW.Flush()

	// Filling the gz writter
	if _, err = io.Copy(ts.gz, ts.bufTar); err != nil {
		return 0, err
	}
	ts.gz.Flush()

	return ts.bufGz.Read(buf)
}