當前位置: 首頁>>代碼示例>>Golang>>正文


Golang notify.Watch函數代碼示例

本文整理匯總了Golang中github.com/rjeczalik/notify.Watch函數的典型用法代碼示例。如果您正苦於以下問題:Golang Watch函數的具體用法?Golang Watch怎麽用?Golang Watch使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Watch函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: ExampleWatch_darwinDirFileSymlink

// This example shows how to work with EventInfo's underlying FSEvent struct.
// Investigating notify.(*FSEvent).Flags field we are able to say whether
// the event's path is a file or a directory and many more.
func ExampleWatch_darwinDirFileSymlink() {
	var must = func(err error) {
		if err != nil {
			log.Fatal(err)
		}
	}
	var stop = func(c ...chan<- notify.EventInfo) {
		for _, c := range c {
			notify.Stop(c)
		}
	}

	// Make the channels buffered to ensure no event is dropped. Notify will drop
	// an event if the receiver is not able to keep up the sending pace.
	dir := make(chan notify.EventInfo, 1)
	file := make(chan notify.EventInfo, 1)
	symlink := make(chan notify.EventInfo, 1)
	all := make(chan notify.EventInfo, 1)

	// Set up a single watchpoint listening for FSEvents-specific events on
	// multiple user-provided channels.
	must(notify.Watch(".", dir, notify.FSEventsIsDir))
	must(notify.Watch(".", file, notify.FSEventsIsFile))
	must(notify.Watch(".", symlink, notify.FSEventsIsSymlink))
	must(notify.Watch(".", all, notify.All))
	defer stop(dir, file, symlink, all)

	// Block until an event is received.
	select {
	case ei := <-dir:
		log.Println("The directory", ei.Path(), "has changed")
	case ei := <-file:
		log.Println("The file", ei.Path(), "has changed")
	case ei := <-symlink:
		log.Println("The symlink", ei.Path(), "has changed")
	case ei := <-all:
		var kind string

		// Investigate underlying *notify.FSEvent struct to access more
		// information about the event.
		switch flags := ei.Sys().(*notify.FSEvent).Flags; {
		case flags&notify.FSEventsIsFile != 0:
			kind = "file"
		case flags&notify.FSEventsIsDir != 0:
			kind = "dir"
		case flags&notify.FSEventsIsSymlink != 0:
			kind = "symlink"
		}

		log.Printf("The %s under path %s has been %sd\n", kind, ei.Path(), ei.Event())
	}
}
開發者ID:kaocs,項目名稱:notify,代碼行數:55,代碼來源:example_fsevents_test.go

示例2: newWatcher

func newWatcher(path string, include, exclude *regexp.Regexp) (*watcher, error) {
	events := make(chan notify.EventInfo, 10)
	ops := make(chan Operation, 10)

	if err := notify.Watch(path+"/...", events, notify.All); err != nil {
		return nil, err
	}

	go func() {
		for ev := range events {
			if include.MatchString(ev.Path()) == false {
				debug(fmt.Sprintf("Skipping: does not match include path: %s", ev.Path()))
				continue
			}

			if exclude.MatchString(ev.Path()) == true {
				debug(fmt.Sprintf("Skipping: does match exclude path: %s", ev.Path()))
				continue
			}

			ops <- Operation{
				Path:      ev.Path(),
				EventInfo: ev,
			}
		}
	}()

	return &watcher{ops: ops, events: events}, nil
}
開發者ID:getapp,項目名稱:golisten,代碼行數:29,代碼來源:main.go

示例3: ExampleStop

// This example shows why it is important to not create leaks by stoping
// a channel when it's no longer being used.
func ExampleStop() {
	waitfor := func(path string, e notify.Event, timeout time.Duration) bool {
		dir, file := filepath.Split(path)
		c := make(chan notify.EventInfo, 1)

		if err := notify.Watch(dir, c, e); err != nil {
			log.Fatal(err)
		}
		// Clean up watchpoint associated with c. If Stop was not called upon
		// return the channel would be leaked as notify holds the only reference
		// to it and does not release it on its own.
		defer notify.Stop(c)

		t := time.After(timeout)

		for {
			select {
			case ei := <-c:
				if filepath.Base(ei.Path()) == file {
					return true
				}
			case <-t:
				return false
			}
		}
	}

	if waitfor("index.lock", notify.Create, 5*time.Second) {
		log.Println("The git repository was locked")
	}

	if waitfor("index.lock", notify.Remove, 5*time.Second) {
		log.Println("The git repository was unlocked")
	}
}
開發者ID:kaocs,項目名稱:notify,代碼行數:37,代碼來源:example_test.go

示例4: Watch

// Watch watches a set of paths. Mod structs representing a changeset are sent
// on the channel ch.
//
// Watch applies heuristics to cope with transient files and unreliable event
// notifications. Modifications are batched up until there is a a lull in the
// stream of changes of duration lullTime. This lets us represent processes
// that progressively affect multiple files, like rendering, as a single
// changeset.
func Watch(paths []string, lullTime time.Duration, ch chan *Mod) (*Watcher, error) {
	evtch := make(chan notify.EventInfo, 4096)
	for _, p := range paths {
		stat, err := os.Stat(p)
		if err != nil {
			return nil, err
		}
		if stat.IsDir() {
			p = path.Join(p, "...")
		}
		err = notify.Watch(p, evtch, notify.All)
		if err != nil {
			return nil, err
		}
	}
	go func() {
		for {
			b := batch(lullTime, MaxLullWait, statExistenceChecker{}, evtch)
			if b != nil && !b.Empty() {
				ret, err := b.normPaths(paths)
				if err != nil {
					Logger.Shout("Error normalising paths: %s", err)
				}
				ch <- ret
			}
		}
	}()
	return &Watcher{evtch}, nil
}
開發者ID:mattn,項目名稱:modd,代碼行數:37,代碼來源:watch.go

示例5: Watch

func (w *Watcher) Watch() error {
	notifyCh := make(chan notify.EventInfo, 10)

	if err := notify.Watch(w.Dir+"/...", notifyCh, notifyEvents...); err != nil {
		return err
	}

	go func() {
		for ei := range notifyCh {
			if !w.Matcher.Match(ei.Path()) {
				continue
			}

			ev := FileEvent{
				Path: ei.Path(),
				Type: convertNotifyType(ei.Event()),
				Time: time.Now().UnixNano(),
			}

			log.Println(ev)
			w.Events <- ev
		}
	}()

	return nil
}
開發者ID:lox,項目名稱:binarystar,代碼行數:26,代碼來源:watch.go

示例6: main

func main() {
	// Make the channel buffered to ensure no event is dropped. Notify will drop
	// an event if the receiver is not able to keep up the sending pace.
	c := make(chan notify.EventInfo, 1)

	// Set up a watchpoint listening for inotify-specific events within a
	// current working directory. Dispatch each InCloseWrite and InMovedTo
	// events separately to c.
	if err := notify.Watch(".", c, notify.FSEventsModified, notify.FSEventsRemoved); err != nil {
		log.Fatal(err)
	}
	defer notify.Stop(c)

	// Block until an event is received.
	switch ei := <-c; ei.Event() {
	case notify.FSEventsChangeOwner:
		log.Println("The owner of", ei.Path(), "has changed.")
	case notify.FSEventsMount:
		log.Println("The path", ei.Path(), "has been mounted.")
	}
	// switch ei := <-c; ei.Event() {
	// case notify.FSEventsModified:
	// 	log.Println("Editing of", ei.Path(), "file is done.")
	// case notify.FSEventsRemoved:
	// 	log.Println("File", ei.Path(), "was swapped/moved into the watched directory.")
	// }
}
開發者ID:zchee,項目名稱:go-sandbox,代碼行數:27,代碼來源:watch_fsevents.go

示例7: Watch

// Watch watches a path p, batching events with duration batchTime. A list of
// strings are written to chan, representing all files changed, added or
// removed. We apply heuristics to cope with things like transient files and
// unreliable event notifications.
func Watch(p string, batchTime time.Duration, ch chan []string) error {
	stat, err := os.Stat(p)
	if err != nil {
		return err
	}
	if stat.IsDir() {
		p = path.Join(p, "...")
	}
	evtch := make(chan notify.EventInfo)
	err = notify.Watch(p, evtch, notify.All)
	if err == nil {
		go func() {
			for {
				ret := batch(batchTime, statChecker{}, evtch)
				if len(ret) > 0 {
					for i := range ret {
						norm, _ := normPath(p, ret[i])
						ret[i] = norm
					}
					ch <- ret
				}
			}
		}()
	}
	return err
}
開發者ID:rawbite,項目名稱:devd,代碼行數:30,代碼來源:modd.go

示例8: ExampleWatch_darwinCoalesce

// FSEvents may report multiple filesystem actions with one, coalesced event.
// Notify unscoalesces such event and dispatches series of single events
// back to the user.
//
// This example shows how to coalesce events by investigating notify.(*FSEvent).ID
// field, for the science.
func ExampleWatch_darwinCoalesce() {
	// Make the channels buffered to ensure no event is dropped. Notify will drop
	// an event if the receiver is not able to keep up the sending pace.
	c := make(chan notify.EventInfo, 4)

	// Set up a watchpoint listetning for events within current working directory.
	// Dispatch all platform-independent separately to c.
	if err := notify.Watch(".", c, notify.All); err != nil {
		log.Fatal(err)
	}
	defer notify.Stop(c)

	var id uint64
	var coalesced []notify.EventInfo

	for ei := range c {
		switch n := ei.Sys().(*notify.FSEvent).ID; {
		case id == 0:
			id = n
			coalesced = []notify.EventInfo{ei}
		case id == n:
			coalesced = append(coalesced, ei)
		default:
			log.Printf("FSEvents reported a filesystem action with the following"+
				" coalesced events %v groupped by %d ID\n", coalesced, id)
			return
		}
	}
}
開發者ID:kaocs,項目名稱:notify,代碼行數:35,代碼來源:example_fsevents_test.go

示例9: setUpFolderListener

func setUpFolderListener(path string, stop <-chan bool) {
	os.RemoveAll(path)
	os.Mkdir(path, os.ModePerm)

	replacer := replacer.NewMakerRegistry(path)

	for _, format := range allFormats() {
		for _, class := range allClasses() {
			replacer.Add(format, class)
		}
	}

	c := make(chan notify.EventInfo, 1000)
	if err := notify.Watch(path, c, notify.Rename, notify.Remove); err != nil {
		log.Fatal(err)
	}
	defer notify.Stop(c)
	go func() {
		for {
			select {
			case event := <-c:
				replacer.Replace(event.Path())
			}
		}
	}()

	<-stop
}
開發者ID:neil-ca-moore,項目名稱:language-tool,代碼行數:28,代碼來源:main.go

示例10: stalk

func stalk(c chan notify.EventInfo) {
	pathTree := filepath.Join(*path, "...")

	err := notify.Watch(pathTree, c, notify.All)

	if err != nil {
		fmt.Printf("cannot watch %s, %s\n", *path, err.Error())
		os.Exit(1)
	} else {
		log.Printf("Stalking path %s", *path)
	}

	for {
		ei := <-c

		if f := filterFiles(ei); f {
			log.Printf("%s\n", ei)
			execute(*cmd)
		}

		if *wait != 0 {
			time.Sleep(time.Duration(*wait) * time.Second)
		}
	}
}
開發者ID:unbalancedparentheses,項目名稱:stalk,代碼行數:25,代碼來源:main.go

示例11: ExampleWatch_windows

// This example shows how to watch directory-name changes in the working directory subtree.
func ExampleWatch_windows() {
	// Make the channel buffered to ensure no event is dropped. Notify will drop
	// an event if the receiver is not able to keep up the sending pace.
	c := make(chan notify.EventInfo, 4)

	// Since notify package behaves exactly like ReadDirectoryChangesW function,
	// we must register notify.FileNotifyChangeDirName filter and wait for one
	// of FileAction* events.
	if err := notify.Watch("./...", c, notify.FileNotifyChangeDirName); err != nil {
		log.Fatal(err)
	}
	defer notify.Stop(c)

	// Wait for actions.
	for ei := range c {
		switch ei.Event() {
		case notify.FileActionAdded, notify.FileActionRenamedNewName:
			log.Println("Created:", ei.Path())
		case notify.FileActionRemoved, notify.FileActionRenamedOldName:
			log.Println("Removed:", ei.Path())
		case notify.FileActionModified:
			panic("notify: unexpected action")
		}
	}
}
開發者ID:kaocs,項目名稱:notify,代碼行數:26,代碼來源:example_readdcw_test.go

示例12: watch

func (d *Dispatcher) watch() {
	for _, path := range d.Paths {
		recursivePath := filepath.Join(path.Name, "...")
		if err := notify.Watch(recursivePath, d.watcher, flags...); err != nil {
			d.log.Error(err)
		} else {
			d.log.WithFields(logrus.Fields{"path": path.Name}).Info("Watching recursively")
		}
	}
}
開發者ID:martinp,項目名稱:gounpack,代碼行數:10,代碼來源:dispatcher.go

示例13: watch

func watch(p string, ch chan notify.EventInfo) error {
	stat, err := os.Stat(p)
	if err != nil {
		return err
	}
	if stat.IsDir() {
		p = path.Join(p, "...")
	}
	return notify.Watch(p, ch, notify.All)
}
開發者ID:skyfree02,項目名稱:devd,代碼行數:10,代碼來源:watch.go

示例14: loop

func (w *watcher) loop() {
	defer func() {
		w.ac.mu.Lock()
		w.running = false
		w.starting = false
		w.ac.mu.Unlock()
	}()

	err := notify.Watch(w.ac.keydir, w.ev, notify.All)
	if err != nil {
		glog.V(logger.Detail).Infof("can't watch %s: %v", w.ac.keydir, err)
		return
	}
	defer notify.Stop(w.ev)
	glog.V(logger.Detail).Infof("now watching %s", w.ac.keydir)
	defer glog.V(logger.Detail).Infof("no longer watching %s", w.ac.keydir)

	w.ac.mu.Lock()
	w.running = true
	w.ac.mu.Unlock()

	// Wait for file system events and reload.
	// When an event occurs, the reload call is delayed a bit so that
	// multiple events arriving quickly only cause a single reload.
	var (
		debounce          = time.NewTimer(0)
		debounceDuration  = 500 * time.Millisecond
		inCycle, hadEvent bool
	)
	defer debounce.Stop()
	for {
		select {
		case <-w.quit:
			return
		case <-w.ev:
			if !inCycle {
				debounce.Reset(debounceDuration)
				inCycle = true
			} else {
				hadEvent = true
			}
		case <-debounce.C:
			w.ac.mu.Lock()
			w.ac.reload()
			w.ac.mu.Unlock()
			if hadEvent {
				debounce.Reset(debounceDuration)
				inCycle, hadEvent = true, false
			} else {
				inCycle, hadEvent = false, false
			}
		}
	}
}
開發者ID:expanse-project,項目名稱:go-expanse,代碼行數:54,代碼來源:watch.go

示例15: Listen

// Listen registers for events within the given root directories (recursively).
func (w *Watcher) Listen(listener Listener, roots ...string) {
	eventCh := make(chan notify.EventInfo, 100)

	// Walk through all files / directories under the root, adding each to watcher.
	for _, p := range roots {
		// is the directory / file a symlink?
		f, err := os.Lstat(p)
		if err == nil && f.Mode()&os.ModeSymlink == os.ModeSymlink {
			realPath, err := filepath.EvalSymlinks(p)
			if err != nil {
				panic(err)
			}
			p = realPath
		}

		fi, err := os.Stat(p)
		if err != nil {
			glog.Errorln("Failed to stat watched path", p, ":", err)
			continue
		}

		if fi.IsDir() {
			err = notify.Watch(p+string(filepath.Separator)+"...", eventCh, notify.All)
		} else {
			err = notify.Watch(p, eventCh, notify.All)
		}
		if err != nil {
			glog.Errorln("Failed to watch", p, ":", err)
		}
	}

	if w.eagerRebuildEnabled() {
		// Create goroutine to notify file changes in real time
		go w.NotifyWhenUpdated(listener, eventCh)
	}

	w.events = append(w.events, eventCh)
	w.listeners = append(w.listeners, listener)
}
開發者ID:hongrich,項目名稱:revel,代碼行數:40,代碼來源:watcher.go


注:本文中的github.com/rjeczalik/notify.Watch函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。