Exemplo n.º 1
0
// TestMetaItemGenerate
func TestMetaItemGenerate(t *testing.T) {
	_, path, _, _ := runtime.Caller(0)
	dir := filepath.Join(filepath.Dir(path), "testdata")

	testContentFile := filepath.Join(dir, "hello.txt")
	testHashFile := filepath.Join(dir, "hello.hash")
	contentByte, _ := ioutil.ReadFile(testContentFile)
	hashByte, _ := ioutil.ReadFile(testHashFile)
	metaItem := utils.GenerateMetaItem("hello.txt", contentByte)
	assert.Equal(t, metaItem.GetHash(), strings.TrimSpace(string(hashByte)), "Fail to get correct hash value")
}
Exemplo n.º 2
0
// TestMetaTime
func TestMetaTime(t *testing.T) {
	test1 := "test1"
	test1Byte := []byte("test1 byte")
	metaItem1 := utils.GenerateMetaItem(test1, test1Byte)
	metaItem2 := metaItem1
	assert.Equal(t, metaItem1, metaItem2, "Fail to compare metaItem, should be the same")

	metaItem2.SetCreated(metaItem2.GetCreated().Add(time.Hour * 1))
	cmp := metaItem1.Compare(metaItem2)
	assert.Equal(t, cmp < 0, true, "Fail to compare metaItem, should be smaller")

	assert.Equal(t, metaItem2.IsExpired(), false, "Fail to get expired information")
	metaItem2.SetExpired(time.Now().Add(time.Hour * (-1)))
	assert.Equal(t, metaItem2.IsExpired(), true, "Fail to get expired information")
}
Exemplo n.º 3
0
// Put adds an application to a repository
func (r LocalRepo) Put(name string, content []byte, method utils.EncryptMethod) (string, error) {
	topDir := r.GetTopDir()
	if !utils.IsDirExist(topDir) {
		if err := os.MkdirAll(topDir, 0777); err != nil {
			return "", err
		}
	}

	var meta utils.Meta
	metaFile := r.GetMetaFile()
	if utils.IsFileExist(metaFile) {
		data, err := ioutil.ReadFile(metaFile)
		if err != nil {
			return "", err
		}

		err = json.Unmarshal(data, &meta)
		if err != nil {
			//This may happend in migration, meta struct changes.
			os.Remove(metaFile)
		}

	}

	encryptContent, err := r.encrypt(method, content)
	if err != nil {
		return "", err
	}

	item := utils.GenerateMetaItem(name, encryptContent)
	item.SetEncryption(method)

	// Using the 'hash' value to rename the original file
	dataFileName := item.GetHash()
	dataFile := filepath.Join(topDir, defaultTargetDir, dataFileName)
	if !utils.IsDirExist(filepath.Dir(dataFile)) {
		if err := os.MkdirAll(filepath.Dir(dataFile), 0777); err != nil {
			return "", err
		}
	}

	// write data
	if err := ioutil.WriteFile(dataFile, encryptContent, 0644); err != nil {
		return "", err
	}

	// get meta content
	exist := false
	for i := range meta.Items {
		if meta.Items[i].Name == name {
			meta.Items[i] = item
			exist = true
		}
	}
	if !exist {
		meta.Items = append(meta.Items, item)
	}

	// write meta data
	err = r.saveMeta(meta)
	if err != nil {
		os.Remove(dataFile)
		return "", err
	}

	return dataFile, nil
}