예제 #1
0
func StartWatch(dir string, fileIndex *fileindex.SafeFileList) {
	var err error
	watcher, err = fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	fileList := BuildFileIndex(dir)
	fileIndex.Copy(fileList)

	mutex := new(sync.Mutex)
	lock := sync.NewCond(mutex)
	go func() {
		for {
			mutex.Lock()
			lock.Wait()
			fileIndex.UpdateHash()
			log.Println("Updated hash")
			time.Sleep(1 * time.Second)
			mutex.Unlock()
		}
	}()

	go func() {
		defer watcher.Close() //This loop should run as long as the program is running
		for event := range watcher.Event {
			name, err := filepath.Rel(SandwichPath, event.Name)
			fullName := filepath.Join(SandwichPath, name)
			if err != nil {
				log.Fatal(err)
			}
			switch {
			case event.IsCreate():
				info, err := os.Stat(fullName)
				if err == nil && info.IsDir() {
					fileList := BuildFileList("", fullName)
					fileIndex.Concat(fileList)
					log.Println(fullName + " was added to the manifest.")
				} else if err == nil {
					fileItem, err := GetFileItemName(fullName)
					if err == nil { //Otherwise the file was deleted before we could create it
						if utf8.ValidString(fileItem.FileName) {
							fileList.Add(fileItem)
						} else {
							log.Println("Hey bra, you cannot have non-utf8 encoded file names")
						}
					}
				}
			case event.IsDelete():
				fileIndex.Remove(name)
				log.Println(name + " was removed from the manifest.")
			case event.IsModify():
				fileIndex.Remove(name)
				fileItem, err := GetFileItemName(fullName)
				if err == nil { //Otherwise the file was deleted before we could create it
					if utf8.ValidString(fileItem.FileName) {
						fileList.Add(fileItem)
						log.Println(fullName + " was added to the manifest.")
					} else {
						log.Println("Hey bra, you cannot have non-utf8 encoded file names")
					}
				}
			case event.IsRename():
				fileIndex.Remove(name)
				log.Println(name + " was removed from the manifest.")
			}
			lock.Signal()
		}
		log.Println("Watch loop exited")
	}()
}
예제 #2
0
func MakePeerItem(ip net.IP, fileIndex *fileindex.SafeFileList) *addresslist.PeerItem {
	return &addresslist.PeerItem{ip, fileIndex.IndexHash(), time.Now()}
}