当前位置: 首页>>代码示例>>Golang>>正文


Golang filepath.Ext函数代码示例

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


在下文中一共展示了Ext函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Run

// Run waits for watcher events sent by fsnotify
// and triggers the restart process if required
func (w *watch) Run() {
	t := time.Now()
	for {
		select {
		case event := <-w.Events:
			if time.Since(t) < threshold || event.Name == "" {
				break
			}

			t = time.Now()
			f, err := os.Stat(event.Name)

			if err != nil {
				log.Println("error watching ", err)
				break
			}
			if filepath.Ext(event.Name) == ".go" || filepath.Ext(event.Name) == ".tmpl" || f.IsDir() {
				Describe(event)
				w.HandleEvent(event)
				log.Println("restarting...")

				// Lock w to ensure that restart is an atomic operation
				w.mu.Lock()
				w.KillProcess()
				go w.StartNewProcess()
			}

		case err := <-w.Errors:
			if err != nil {
				log.Println("error:", err)
			}
		}
	}
}
开发者ID:Revanth47,项目名称:gomon,代码行数:36,代码来源:gomon.go

示例2: suffixOf

func suffixOf(filename string) string {
	suffix := filepath.Ext(filename)
	if suffix == ".gz" {
		suffix = filepath.Ext(filename[:len(filename)-3])
	}
	return suffix
}
开发者ID:pawelropa,项目名称:programmingingo,代码行数:7,代码来源:invoicedata.go

示例3: GenDepsForFile

// Generates a dependency Makefile (.d) for the specified source C file.
//
// @param file                  The name of the source file.
func (c *Compiler) GenDepsForFile(file string) error {
	if util.NodeNotExist(c.dstDir) {
		os.MkdirAll(c.dstDir, 0755)
	}

	depFile := c.dstDir + "/" +
		strings.TrimSuffix(file, filepath.Ext(file)) + ".d"
	depFile = filepath.ToSlash(depFile)

	var cmd string
	var err error

	cmd = c.ccPath + " " + c.cflagsString() + " " + c.includesString() +
		" -MM -MG " + file + " > " + depFile
	o, err := util.ShellCommand(cmd)
	if err != nil {
		return util.NewNewtError(string(o))
	}

	// Append the extra dependencies (.yml files) to the .d file.
	f, err := os.OpenFile(depFile, os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer f.Close()

	objFile := strings.TrimSuffix(file, filepath.Ext(file)) + ".o"
	if _, err := f.WriteString(objFile + ": " + c.depsString()); err != nil {
		return util.NewNewtError(err.Error())
	}

	return nil
}
开发者ID:apache,项目名称:incubator-mynewt-newt,代码行数:36,代码来源:compiler.go

示例4: readEvent

func (w *Watcher) readEvent() {
	var (
		buf   [syscall.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events
		n     int                                     // Number of bytes read with read()
		errno error                                   // Syscall errno
	)

	for {

		select {
		case <-w.done:
			syscall.Close(w.fd)
			close(w.acceptEvent)
			close(w.Error)
			return
		default:
		}

		n, errno = syscall.Read(w.fd, buf[0:])

		if n == 0 {
			syscall.Close(w.fd)
			close(w.acceptEvent)
			close(w.Error)
			return
		}

		if n < syscall.SizeofInotifyEvent {
			log.Fatal("size of InotifyEvent error", errno)
		}

		var offset uint32 = 0

		for offset <= uint32(n-syscall.SizeofInotifyEvent) {
			raw := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset]))
			event := new(FileEvent)
			event.wd = raw.Wd
			event.nameLen = raw.Len
			event.mask = raw.Mask
			event.cookie = raw.Cookie
			path := w.wm.paths[int(raw.Wd)]
			if raw.Len > 0 {
				// Point "bytes" at the first byte of the filename
				bytes := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent]))
				// The filename is padded with NUL bytes. TrimRight() gets rid of those.
				event.fileName = path + "/" + strings.TrimRight(string(bytes[0:raw.Len]), "\000")
			}

			if _, found := w.skipExt[filepath.Ext(event.fileName)]; !found {
				fmt.Println("--->", w.skipExt, "--->", filepath.Ext(event.fileName), "--->", found)
				//发送事件acceptEvent通道
				w.acceptEvent <- event
			} else {
				fmt.Println("过滤文件:", event.fileName)
			}

			offset += syscall.SizeofInotifyEvent + raw.Len
		}
	}
}
开发者ID:nopsky,项目名称:sfserver,代码行数:60,代码来源:notify.go

示例5: replaceForEach

// %f - whole filepath
// %d - dirname of path
// %b - basename of file
// %B - basename without extension
// %e - extension of file
func replaceForEach(name, arg string) (string, bool) {
	li := -1
	found := false
	for i := 0; i > li; {
		li = i
		if i = strings.Index(arg, "%"); i > -1 {
			ext := filepath.Ext(name)
			if len(ext) > 1 {
				ext = ext[1:] // strip
			}
			base := filepath.Base(name)
			m := map[rune]string{
				'f': name,
				'd': filepath.Dir(name),
				'b': base,
				'B': strings.TrimSuffix(base, filepath.Ext(name)),
				'e': ext,
			}
			i++
			r := rune(arg[i])
			insert, ok := m[r]
			if ok {
				found = true
				arg = strings.Replace(arg, "%"+string(r), insert, -1)
				// println(arg, insert, strings.TrimSuffix("dir/a.a", filepath.Ext("dir/a.a")))
			}
		} else {
			break
		}
	}
	return arg, found
}
开发者ID:ronbu,项目名称:made,代码行数:37,代码来源:main.go

示例6: readAslFiles

// Creates a list of all ASL files to compile.
func readAslFiles(path string) {
	dir, err := ioutil.ReadDir(path)

	if err != nil {
		fmt.Println("Error reading in directory!")
		return
	}

	for i := 0; i < len(dir); i++ {
		name := dir[i].Name()

		if dir[i].IsDir() && recursive {
			readAslFiles(filepath.FromSlash(path + PathSeparator + name))
			continue
		}

		if !dir[i].IsDir() && strings.ToLower(filepath.Ext(name)) == extension {
			in := filepath.FromSlash(path + PathSeparator + dir[i].Name())
			out := filepath.FromSlash("./" + path[len(inDir):len(path)])
			newname := name[:len(name)-len(filepath.Ext(name))]

			file := ASLFile{in, out, newname}
			aslFiles = append(aslFiles, file)
		}
	}
}
开发者ID:DeKugelschieber,项目名称:asl,代码行数:27,代码来源:asl.go

示例7: runBenchmark

func runBenchmark(fileInfoName, pathToPagesets, pathToPyFiles, localOutputDir, chromiumBuildName, chromiumBinary, runID, browserExtraArgs string) error {
	pagesetBaseName := filepath.Base(fileInfoName)
	if pagesetBaseName == util.TIMESTAMP_FILE_NAME || filepath.Ext(pagesetBaseName) == ".pyc" {
		// Ignore timestamp files and .pyc files.
		return nil
	}

	// Convert the filename into a format consumable by the run_benchmarks
	// binary.
	pagesetName := strings.TrimSuffix(pagesetBaseName, filepath.Ext(pagesetBaseName))
	pagesetPath := filepath.Join(pathToPagesets, fileInfoName)

	glog.Infof("===== Processing %s for %s =====", pagesetPath, runID)

	skutil.LogErr(os.Chdir(pathToPyFiles))
	args := []string{
		util.BINARY_RUN_BENCHMARK,
		fmt.Sprintf("%s.%s", *benchmarkName, util.BenchmarksToPagesetName[*benchmarkName]),
		"--page-set-name=" + pagesetName,
		"--page-set-base-dir=" + pathToPagesets,
		"--also-run-disabled-tests",
	}

	// Need to capture output for all benchmarks.
	outputDirArgValue := filepath.Join(localOutputDir, pagesetName)
	args = append(args, "--output-dir="+outputDirArgValue)
	// Figure out which browser should be used.
	if *targetPlatform == util.PLATFORM_ANDROID {
		if err := installChromeAPK(chromiumBuildName); err != nil {
			return fmt.Errorf("Error while installing APK: %s", err)
		}
		args = append(args, "--browser=android-chrome-shell")
	} else {
		args = append(args, "--browser=exact", "--browser-executable="+chromiumBinary)
	}
	// Split benchmark args if not empty and append to args.
	if *benchmarkExtraArgs != "" {
		for _, benchmarkArg := range strings.Split(*benchmarkExtraArgs, " ") {
			args = append(args, benchmarkArg)
		}
	}
	// Add the number of times to repeat.
	args = append(args, fmt.Sprintf("--page-repeat=%d", *repeatBenchmark))
	// Add browserArgs if not empty to args.
	if browserExtraArgs != "" {
		args = append(args, "--extra-browser-args="+browserExtraArgs)
	}
	// Set the PYTHONPATH to the pagesets and the telemetry dirs.
	env := []string{
		fmt.Sprintf("PYTHONPATH=%s:%s:%s:$PYTHONPATH", pathToPagesets, util.TelemetryBinariesDir, util.TelemetrySrcDir),
		"DISPLAY=:0",
	}
	timeoutSecs := util.PagesetTypeToInfo[*pagesetType].RunChromiumPerfTimeoutSecs
	if err := util.ExecuteCmd("python", args, env, time.Duration(timeoutSecs)*time.Second, nil, nil); err != nil {
		glog.Errorf("Run benchmark command failed with: %s", err)
		glog.Errorf("Killing all running chrome processes in case there is a non-recoverable error.")
		skutil.LogErr(util.ExecuteCmd("pkill", []string{"-9", "chrome"}, []string{}, 5*time.Minute, nil, nil))
	}
	return nil
}
开发者ID:kleopatra999,项目名称:skia-buildbot,代码行数:60,代码来源:main.go

示例8: NewPlistHandler

func NewPlistHandler(rootDir string) macaron.Handler {
	return func(r *http.Request, w http.ResponseWriter, ctx *macaron.Context) {
		relpath := ctx.Params("*")
		if filepath.Ext(relpath) == ".plist" {
			relpath = relpath[0:len(relpath)-6] + ".ipa"
		}
		abspath := filepath.Join(rootDir, relpath)

		plinfo, err := parseIPA(abspath)
		if err != nil {
			log.Println(err)
			ctx.Error(500, err.Error())
			return
		}
		filepath.Ext(relpath)
		ipaURL := url.URL{
			Scheme: "https",
			Host:   r.Host,
			Path:   relpath,
		}
		imgURL := url.URL{
			Scheme: "https",
			Host:   r.Host,
			Path:   filepath.Join("/$ipaicon", relpath),
		}
		data, err := generateDownloadPlist(ipaURL.String(), imgURL.String(), plinfo)
		if err != nil {
			ctx.Error(500, err.Error())
			return
		}
		w.Header().Set("Content-Type", "text/xml")
		w.Write(data)
	}
}
开发者ID:raceli,项目名称:gohttp,代码行数:34,代码来源:ipa.go

示例9: Prepare

func (dc *DocController) Prepare() {
	dc.BaseController.Prepare()

	// get correct file in doc directory
	p := dc.Ctx.Request.URL.Path
	p = strings.Replace(p, "/docs", "beedoc/"+dc.Lang, -1)
	p = strings.TrimRight(p, "/")
	if filepath.Ext(p) == "" {
		p += ".md"
	}
	dc.docFile = p

	// serve static file
	if filepath.Ext(p) != ".md" {
		http.ServeFile(dc.Ctx.ResponseWriter, dc.Ctx.Request, p)
		dc.StopRun()
	}

	// render md doc file
	if err := dc.renderDoc(); err != nil {
		dc.CustomAbort(503, err.Error())
		return
	}

}
开发者ID:yuzhouisme,项目名称:website,代码行数:25,代码来源:doc.go

示例10: generateThumb

// this converts pngs and jpgs to smaller jpgs, and writes them out to the http connection, this thing EATS ALL THE MEMORY
func generateThumb(w http.ResponseWriter, path string) {
	file, err := os.Open(path)
	if err != nil {
		fmt.Print("Error opening image:", err)
	}
	var img image.Image = nil
	if filepath.Ext(path) == ".png" {
		img, err = png.Decode(file)
		if err != nil {
			fmt.Print("Error decoding image:", err)
			return
		}
		file.Close()
	} else if filepath.Ext(path) == ".jpg" {
		img, err = jpeg.Decode(file)
		if err != nil {
			fmt.Print("Error decoding image:", err)
			return
		}
		file.Close()
	} else {
		return
	}
	// resize to height 200
	err = jpeg.Encode(w, resize.Resize(0, 200, img, resize.NearestNeighbor), nil)
	if err != nil {
		fmt.Print("Error encoding thumb:", err)
	}
}
开发者ID:Nixes,项目名称:GoMediaServer,代码行数:30,代码来源:gomediaserver.go

示例11: walkpath

func walkpath(path string, f os.FileInfo, err error, outfile *os.File, fchan chan FileDesc) error {

	filetype := "FILE"
	if f.IsDir() {
		filetype = "DIR"
	}
	outfile.WriteString(filetype)
	outfile.WriteString(",\t\"")
	outfile.WriteString(f.Name())
	outfile.WriteString("\",\t")
	outfile.WriteString(filepath.Ext(path))
	outfile.WriteString(",\t\"")
	outfile.WriteString(filepath.Dir(path))
	outfile.WriteString("\",\t\"")
	outfile.WriteString(f.ModTime().String())
	outfile.WriteString("\",\t")
	outfile.WriteString(strconv.Itoa(int(f.Size())))
	outfile.WriteString(",\t\"")
	outfile.WriteString(path)
	outfile.WriteString("\"\r\n")

	fdesc := FileDesc{"0000", filetype, f.Name(), filepath.Ext(path), filepath.Dir(path), path, strconv.Itoa(int(f.Size())), f.ModTime().String()}
	fchan <- fdesc

	return nil
}
开发者ID:huuzkee-foundation,项目名称:winsvc,代码行数:26,代码来源:service.go

示例12: MakeMediaFileName

// 트윗에 붙은 이미지가 여러개인 경우와 한개인 경우를 구분
func MakeMediaFileName(tweet *anaconda.Tweet, media anaconda.EntityMedia) string {
	mediaCount := len(tweet.ExtendedEntities.Media)
	if mediaCount <= 1 {
		url := FindMediaURL(media)
		ext := filepath.Ext(url)
		return fmt.Sprintf("%s%s", tweet.IdStr, ext)
	}

	found := -1
	for i := 0; i < mediaCount; i++ {
		m := tweet.ExtendedEntities.Media[i]
		if m.Media_url == media.Media_url {
			found = i
			break
		}
	}

	if found < 0 {
		// not found
		return ""
	}

	num := found + 1
	url := FindMediaURL(media)
	ext := filepath.Ext(url)
	return fmt.Sprintf("%s_%d%s", tweet.IdStr, num, ext)
}
开发者ID:if1live,项目名称:makina,代码行数:28,代码来源:media.go

示例13: Open

// Open returns an in-memory VFS initialized with the contents
// of the given filename, which must have one of the following
// extensions:
//
//  - .zip
//  - .tar
//  - .tar.gz
//  - .tar.bz2
func Open(filename string) (VFS, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	base := filepath.Base(filename)
	ext := strings.ToLower(filepath.Ext(base))
	nonExt := filename[:len(filename)-len(ext)]
	if strings.ToLower(filepath.Ext(nonExt)) == ".tar" {
		ext = ".tar" + ext
	}
	switch ext {
	case ".zip":
		st, err := f.Stat()
		if err != nil {
			return nil, err
		}
		return Zip(f, st.Size())
	case ".tar":
		return Tar(f)
	case ".tar.gz":
		return TarGzip(f)
	case ".tar.bz2":
		return TarBzip2(f)
	}
	return nil, fmt.Errorf("can't open a VFS from a %s file", ext)
}
开发者ID:knutsel,项目名称:httpcache,代码行数:36,代码来源:open.go

示例14: loadBaseTemplates

// loadTemplates walks sourceDir and loads all base templates into t.  These
// are files that have a '.tmpl' extensions and a leading underscore.  The
// template name is the filename with those stripped.
func loadBaseTemplates(t *template.Template) error {
	return filepath.Walk(*sourceDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}

		basename := filepath.Base(path)
		// Only handle files that start with _
		if !strings.HasPrefix(basename, "_") {
			return nil
		}

		// Only handle files with ".tmpl" extension
		ext := filepath.Ext(basename)
		if ext != ".tmpl" {
			return nil
		}

		fmt.Printf("Loading template file: %v\n", path)

		// Strip off "_" and ".tmpl"
		name := strings.TrimPrefix(strings.TrimSuffix(basename, filepath.Ext(basename)), "_")
		data, err := ioutil.ReadFile(path)
		_, err = t.New(name).Parse(string(data))
		if err != nil {
			return err
		}
		return nil
	})
}
开发者ID:jbeda,项目名称:stegosaurus,代码行数:36,代码来源:stegosaurus.go

示例15: externalCommand

func (g *goemon) externalCommand(command, file string) bool {
	var cmd *exec.Cmd
	command = os.Expand(command, func(s string) string {
		switch s {
		case "GOEMON_TARGET_FILE":
			return file
		case "GOEMON_TARGET_BASE":
			return filepath.Base(file)
		case "GOEMON_TARGET_DIR":
			return filepath.ToSlash(filepath.Dir(file))
		case "GOEMON_TARGET_EXT":
			return filepath.Ext(file)
		case "GOEMON_TARGET_NAME":
			fn := filepath.Base(file)
			ext := filepath.Ext(file)
			return fn[:len(fn)-len(ext)]
		}
		return os.Getenv(s)
	})
	if runtime.GOOS == "windows" {
		cmd = exec.Command("cmd", "/c", command)
	} else {
		cmd = exec.Command("sh", "-c", command)
	}
	g.Logger.Println("executing", command)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		g.Logger.Println(err)
		return false
	}
	return true
}
开发者ID:todashuta,项目名称:goemon,代码行数:34,代码来源:command.go


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