github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/file/file.go (about)

     1  /* For license and copyright information please see LEGAL file in repository */
     2  
     3  package file
     4  
     5  import (
     6  	"hash/crc32"
     7  	"strconv"
     8  	"strings"
     9  
    10  	"../protocol"
    11  )
    12  
    13  func FindByRelativeFrom(file protocol.File, relativePath string) (desireFile protocol.File) {
    14  	var locPart = strings.Split(relativePath, "/")
    15  	if len(locPart) < 2 {
    16  		return
    17  	}
    18  	var desireDir = file.ParentDirectory()
    19  	for i := 0; i < len(locPart)-1; i++ { // -1 due have file name at end of locPart
    20  		switch locPart[i] {
    21  		case ".":
    22  			// noting to do!
    23  		case "..":
    24  			desireDir = desireDir.ParentDirectory()
    25  		default:
    26  			desireDir, _ = desireDir.Directory(locPart[i])
    27  			if desireDir == nil {
    28  				// err =
    29  				return
    30  			}
    31  		}
    32  	}
    33  
    34  	var fileName = locPart[len(locPart)-1]
    35  	desireFile, _ = desireDir.File(fileName)
    36  	return
    37  }
    38  
    39  func AddHashToFileName(file protocol.File) {
    40  	var nameWithoutExtension = file.MetaData().URI().NameWithoutExtension()
    41  	var fileExt = file.MetaData().URI().Extension()
    42  
    43  	// Just want to differ two same file, So crc32 is more enough!
    44  	// var md5Hasher = md5.New()
    45  	// md5Hasher.Write(f.data)
    46  	// hash = hex.EncodeToString(md5Hasher.Sum(nil))
    47  	// md5Hasher.Reset()
    48  	var hashOfFileData = strconv.FormatUint(uint64(crc32.ChecksumIEEE(file.Data().Marshal())), 10)
    49  
    50  	file.Rename(nameWithoutExtension + "-" + hashOfFileData + "." + fileExt)
    51  }