• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang notify.Watch函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/rjeczalik/notify.Watch函数的典型用法代码示例。如果您正苦于以下问题:Golang Watch函数的具体用法?Golang Watch怎么用?Golang Watch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Watch函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: watchFile

func watchFile() {
	c := make(chan notify.EventInfo, 1)
	if err := notify.Watch("./users.txt", c, 0x04000); err != nil {
		fmt.Println("error watching users file", err)
	}
	defer notify.Stop(c)

	// Block until an event is received.
	ei := <-c
	fmt.Println("Users - watchFile - users file has been changed", ei.Event())
	parseAndSetUsers()
	go watchFile()
}
开发者ID:LicaSterian,项目名称:unsub,代码行数:13,代码来源:Users.go


示例17: 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 on events within current working directory.
	// Dispatch each create and remove events separately to c.
	if err := notify.Watch(".", c, notify.Create, notify.Remove); err != nil {
		log.Fatal(err)
	}
	defer notify.Stop(c)

	// Block until an event is received.
	ei := <-c
	log.Println("Got event:", ei)
}
开发者ID:zchee,项目名称:go-sandbox,代码行数:16,代码来源:eventwatch.go


示例18: ExampleWatch_recursive

// This example shows how to set up a recursive watchpoint.
func ExampleWatch_recursive() {
	// 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 events within a directory tree rooted
	// at current working directory. Dispatch remove events to c.
	if err := notify.Watch("./...", c, notify.Remove); err != nil {
		log.Fatal(err)
	}
	defer notify.Stop(c)

	// Block until an event is received.
	ei := <-c
	log.Println("Got event:", ei)
}
开发者ID:kaocs,项目名称:notify,代码行数:17,代码来源:example_test.go


示例19: main

func main() {

	repotmp := "/repo/PKGBUILD/"
	currentuser, _ := user.Current()
	homedirs, _ := getHomes("/home/*")
	logFile := StartLog("/var/log/pkgbuild.log", currentuser)
	defer logFile.Close()
	Info.Println("\n\n\t\tI don't know who you are\n\t\tI don't know what you are syncing\n\t\tIf you are syncing via rsync, I can tell you \n\t\tI don't have the condition to pick it\n\t\tBut what I do have are a very particular set of channels\n\t\tChannels that pick up debs and push it to the repo\n\t\tI will look for debs in", homedirs, ", \n\t\tI will find it, and I will add it to repo . . .\n")
	fmt.Println("\n\n\t\tI don't know who you are\n\t\tI don't know what you are syncing\n\t\tIf you are syncing via rsync, I can tell you \n\t\tI don't have the condition to pick it\n\t\tBut what I do have are a very particular set of channels\n\t\tChannels that pick up debs and push it to the repo\n\t\tI will look for debs in", homedirs, ", \n\t\tI will find it, and I will add it to repo . . .\n")
	Info.Println("Starting taken . . .\nUse scp to copy deb files.")
	fmt.Println("Starting taken . . .\nUse scp to copy deb files.")
	Info.Println("Deb files will be moved to ", repotmp, "before pushing to repo")

	c := make(chan notify.EventInfo, 20)

	for _, i := range homedirs {
		if err := notify.Watch(i, c, notify.InCloseWrite, notify.Create); err != nil {
			log.Fatal(err)
		}
	}
	/*if err := notify.Watch("/home/girishg/", c, notify.InCloseWrite, notify.All); err != nil {
		log.Fatal(err)
	}
	if err := notify.Watch("/home/anotheruser/", c, notify.InCloseWrite, notify.All); err != nil {
		log.Fatal(err)
	}*/
	defer notify.Stop(c)

	for ei := range c {

		switch ei.Event() {
		case notify.Create:
			Info.Println(ei.Event(), ei.Path())
		case notify.InCloseWrite:
			Info.Println(ei.Event(), ei.Path())
			if ValidateDeb(ei.Path()) {
				debfile := moveDebs(ei.Path(), repotmp)
				CallAptlyAdd(debfile)
				CallAptlyShow()
				CallAptlyPublish()
			}

		}

	}

}
开发者ID:nohupped,项目名称:taken,代码行数:47,代码来源:taken.go


示例20: New

// New - Creates a new watcher which flushes caches.
func New(path string, cache CacheFlusher) (*Watcher, error) {
	events := make(chan notify.EventInfo, 1)
	path, err := filepath.Abs(path)
	if err != nil {
		return nil, err
	}
	path = filepath.Dir(path)
	path = filepath.Join(path, "...")
	err = notify.Watch(path, events, notify.All)
	if err != nil {
		return nil, fmt.Errorf("watching on %q: %v", path, err)
	}
	return &Watcher{
		events:  events,
		flusher: cache,
	}, nil
}
开发者ID:crackcomm,项目名称:renderer,代码行数:18,代码来源:watcher.go



注:本文中的github.com/rjeczalik/notify.Watch函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang testhelpers.AssertString函数代码示例发布时间:2022-05-28
下一篇:
Golang notify.Stop函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap