Golang ToSlash示例

说明

golang toslash示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: path/filepath

示例#1
文件: parseidl.go 项目: babelrpc/babel

// ParseIdl parses the idl in the given file with tests for the given
// language. The Idl object is returned unless an error occured.
func ParseIdl(fileName, lang string) (*idl.Idl, error) {
	f, err := os.Open(fileName)
	if err != nil {
		return nil, fmt.Errorf("Error opening input file: %s", err)
	}
	defer f.Close()

	var lexer IdlLex
	lexer.Init(f, f.Name())
	lexer.globals.pidl = new(idl.Idl)
	lexer.globals.pidl.Init()
	lexer.globals.pidl.Filename = filepath.ToSlash(fileName)
	lexer.globals.basedir = filepath.ToSlash(filepath.Dir(fileName))

	yyParse(&lexer)
	if len(lexer.Errors) > 0 {
		return nil, fmt.Errorf("%s\n%d parsing errors, exiting", strings.Join(lexer.Errors, "\n"), len(lexer.Errors))
	}

	err = lexer.globals.pidl.Validate(lang)
	if err != nil {
		return nil, fmt.Errorf("IDL does not validate: %s", err)
	}

	return lexer.globals.pidl, nil
}

示例#2
文件: setup-cuda-paths.go 项目: LStoleriu/hotspin

func main() {
	flag.Parse()

	CUDAINC := filepath.ToSlash(os.Getenv(CUDA_INC_PATH))
	CUDALIB := filepath.ToSlash(os.Getenv(CUDA_LIB_PATH))

	config.Include = strings.Split(CUDAINC, VARDELIM)
	config.Lib = strings.Split(CUDALIB, VARDELIM)

	fmt.Println(*dir)
	dirs, _ := ioutil.ReadDir(*dir)
	for i, _ := range dirs {
		if dirs[i].IsDir() {
			dirName := dirs[i].Name()
			currDir := *dir + "/" + dirName
			fmt.Println(currDir)
			tempPath := currDir + "/" + CONFIG_TEMP_FILE_NAME
			outPath := currDir + "/" + CONFIG_FILE_NAME

			t, error := template.ParseFiles(tempPath)
			if error != nil {
				fmt.Println("The folder has no template files")
				continue
			}
			file, err := os.OpenFile(outPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0666)
			if err != nil {
				panic(err)
			}
			t.Execute(file, config)
			file.Close()
		}
	}
}

示例#3
文件: fix.go 项目: ChloeTigre/golang-tools

// canUse reports whether the package in dir is usable from filename,
// respecting the Go "internal" and "vendor" visibility rules.
func canUse(filename, dir string) bool {
	// Fast path check, before any allocations. If it doesn't contain vendor
	// or internal, it's not tricky:
	// Note that this can false-negative on directories like "notinternal",
	// but we check it correctly below. This is just a fast path.
	if !strings.Contains(dir, "vendor") && !strings.Contains(dir, "internal") {
		return true
	}

	dirSlash := filepath.ToSlash(dir)
	if !strings.Contains(dirSlash, "/vendor/") && !strings.Contains(dirSlash, "/internal/") && !strings.HasSuffix(dirSlash, "/internal") {
		return true
	}
	// Vendor or internal directory only visible from children of parent.
	// That means the path from the current directory to the target directory
	// can contain ../vendor or ../internal but not ../foo/vendor or ../foo/internal
	// or bar/vendor or bar/internal.
	// After stripping all the leading ../, the only okay place to see vendor or internal
	// is at the very beginning of the path.
	abs, err := filepath.Abs(filename)
	if err != nil {
		return false
	}
	rel, err := filepath.Rel(abs, dir)
	if err != nil {
		return false
	}
	relSlash := filepath.ToSlash(rel)
	if i := strings.LastIndex(relSlash, "../"); i >= 0 {
		relSlash = relSlash[i+len("../"):]
	}
	return !strings.Contains(relSlash, "/vendor/") && !strings.Contains(relSlash, "/internal/") && !strings.HasSuffix(relSlash, "/internal")
}

示例#4
文件: util.go 项目: satyamkotakonda/rack

// NormalizePathURL is used to convert rawPath to a fqdn, using basePath as
// a reference in the filesystem, if necessary. basePath is assumed to contain
// either '.' when first used, or the file:// type fqdn of the parent resource.
// e.g. myFavScript.yaml => file://opt/lib/myFavScript.yaml
func NormalizePathURL(basePath, rawPath string) (string, error) {
	u, err := url.Parse(rawPath)
	if err != nil {
		return "", err
	}
	// if a scheme is defined, it must be a fqdn already
	if u.Scheme != "" {
		return u.String(), nil
	}
	// if basePath is a url, then child resources are assumed to be relative to it
	bu, err := url.Parse(basePath)
	if err != nil {
		return "", err
	}
	var basePathSys, absPathSys string
	if bu.Scheme != "" {
		basePathSys = filepath.FromSlash(bu.Path)
		absPathSys = filepath.Join(basePathSys, rawPath)
		bu.Path = filepath.ToSlash(absPathSys)
		return bu.String(), nil
	}

	absPathSys = filepath.Join(basePath, rawPath)
	u.Path = filepath.ToSlash(absPathSys)
	if err != nil {
		return "", err
	}
	u.Scheme = "file"
	return u.String(), nil

}

示例#5

// FindTree takes an import or filesystem path and returns the
// tree where the package source should be and the package import path.
func FindTree(path string) (tree *Tree, pkg string, err error) {
	if isLocalPath(path) {
		if path, err = filepath.Abs(path); err != nil {
			return
		}
		if path, err = filepath.EvalSymlinks(path); err != nil {
			return
		}
		for _, t := range Path {
			tpath := t.SrcDir() + string(filepath.Separator)
			if !filepath.HasPrefix(path, tpath) {
				continue
			}
			tree = t
			pkg = filepath.ToSlash(path[len(tpath):])
			return
		}
		err = fmt.Errorf("path %q not inside a GOPATH", path)
		return
	}
	tree = defaultTree
	pkg = filepath.ToSlash(path)
	for _, t := range Path {
		if t.HasSrc(pkg) {
			tree = t
			return
		}
	}
	if tree == nil {
		err = ErrTreeNotFound
	} else {
		err = ErrNotFound
	}
	return
}

示例#6
文件: fix.go 项目: Cl0udPhish/go-swagger

func canUse(filename, dir string) bool {
	dirSlash := filepath.ToSlash(dir)
	if !strings.Contains(dirSlash, "/vendor/") && !strings.Contains(dirSlash, "/internal/") && !strings.HasSuffix(dirSlash, "/internal") {
		return true
	}
	// Vendor or internal directory only visible from children of parent.
	// That means the path from the current directory to the target directory
	// can contain ../vendor or ../internal but not ../foo/vendor or ../foo/internal
	// or bar/vendor or bar/internal.
	// After stripping all the leading ../, the only okay place to see vendor or internal
	// is at the very beginning of the path.
	abs, err := filepath.Abs(filename)
	if err != nil {
		return false
	}
	rel, err := filepath.Rel(abs, dir)
	if err != nil {
		return false
	}
	relSlash := filepath.ToSlash(rel)
	if i := strings.LastIndex(relSlash, "../"); i >= 0 {
		relSlash = relSlash[i+len("../"):]
	}
	return !strings.Contains(relSlash, "/vendor/") && !strings.Contains(relSlash, "/internal/") && !strings.HasSuffix(relSlash, "/internal")
}

示例#7
文件: scripts.go 项目: egli/pipeline-cli-go

//Accepts several paths separated by separator and constructs the URLs
//relative to base path
func pathToUri(paths string, separator string, basePath string) (urls []url.URL, err error) {
	var urlBase *url.URL

	if basePath != "" {
		if string(basePath[0]) != "/" {
			//for windows path to build a proper url
			basePath = "/" + basePath
		}
		urlBase, err = url.Parse("file:" + basePath)
	}
	if err != nil {
		return nil, err
	}
	inputs := strings.Split(paths, ",")
	for _, input := range inputs {
		var urlInput *url.URL
		if basePath != "" {
			urlInput, err = url.Parse(filepath.ToSlash(input))
			if err != nil {
				return nil, err
			}
			urlInput = urlBase.ResolveReference(urlInput)
		} else {
			//TODO is opaque really apropriate?
			urlInput = &url.URL{
				Opaque: filepath.ToSlash(input),
			}
		}
		urls = append(urls, *urlInput)
	}
	//clean
	return
}

示例#8
文件: sketch_loader_test.go 项目: facchinm/arduino-builder

func TestLoadSketchFromFolder(t *testing.T) {
	ctx := &types.Context{
		SketchLocation: "sketch_with_subfolders",
	}

	commands := []types.Command{
		&builder.SketchLoader{},
	}

	for _, command := range commands {
		err := command.Run(ctx)
		NoError(t, err)
	}

	sketch := ctx.Sketch
	require.NotNil(t, sketch)

	require.Contains(t, sketch.MainFile.Name, "sketch_with_subfolders.ino")

	require.Equal(t, 0, len(sketch.OtherSketchFiles))

	require.Equal(t, 4, len(sketch.AdditionalFiles))
	require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[0].Name), "sketch_with_subfolders/src/subfolder/other.cpp")
	require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[1].Name), "sketch_with_subfolders/src/subfolder/other.h")
	require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[2].Name), "sketch_with_subfolders/subfolder/dont_load_me.cpp")
	require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[3].Name), "sketch_with_subfolders/subfolder/other.h")
}

示例#9
文件: serialfile.go 项目: andradeandrey/go-ipfs

func (f *serialFile) NextFile() (File, error) {
	// if a file was opened previously, close it
	err := f.Close()
	if err != nil {
		return nil, err
	}

	// if there aren't any files left in the root directory, we're done
	if len(f.files) == 0 {
		return nil, io.EOF
	}

	stat := f.files[0]
	f.files = f.files[1:]

	// open the next file
	fileName := filepath.ToSlash(filepath.Join(f.name, stat.Name()))
	filePath := filepath.ToSlash(filepath.Join(f.path, stat.Name()))

	// recursively call the constructor on the next file
	// if it's a regular file, we will open it as a ReaderFile
	// if it's a directory, files in it will be opened serially
	sf, err := NewSerialFile(fileName, filePath, stat)
	if err != nil {
		return nil, err
	}

	f.current = &sf

	return sf, nil
}

示例#10
文件: provisioner.go 项目: hnakamur/packer

func (p *Provisioner) executeAnsible(ui packer.Ui, comm packer.Communicator) error {
	playbook := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(p.config.PlaybookFile)))
	inventory := filepath.ToSlash(filepath.Join(p.config.StagingDir, filepath.Base(p.config.InventoryFile)))

	extraArgs := ""
	if len(p.config.ExtraArguments) > 0 {
		extraArgs = " " + strings.Join(p.config.ExtraArguments, " ")
	}

	command := fmt.Sprintf("cd %s && %s %s%s -c local -i %s",
		p.config.StagingDir, p.config.Command, playbook, extraArgs, inventory)
	ui.Message(fmt.Sprintf("Executing Ansible: %s", command))
	cmd := &packer.RemoteCmd{
		Command: command,
	}
	if err := cmd.StartWithUi(comm, ui); err != nil {
		return err
	}
	if cmd.ExitStatus != 0 {
		if cmd.ExitStatus == 127 {
			return fmt.Errorf("%s could not be found. Verify that it is available on the\n"+
				"PATH after connecting to the machine.",
				p.config.Command)
		}

		return fmt.Errorf("Non-zero exit status: %d", cmd.ExitStatus)
	}
	return nil
}

示例#11
文件: zglob_test.go 项目: moul/advanced-ssh-config

func TestZGlobAbs(t *testing.T) {
	tmpdir := setup(t)
	defer os.RemoveAll(tmpdir)

	curdir, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	err = os.Chdir(tmpdir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.Chdir(curdir)

	for _, test := range testZGlobs {
		test.pattern = filepath.ToSlash(filepath.Join(tmpdir, test.pattern))
		for i, expected := range test.expected {
			test.expected[i] = filepath.ToSlash(filepath.Join(tmpdir, expected))
		}
		got, err := Glob(test.pattern)
		if err != nil {
			if test.err != err {
				t.Error(err)
			}
			continue
		}
		if !check(test.expected, got) {
			t.Errorf(`zglob failed: pattern %q: expected %v but got %v`, test.pattern, test.expected, got)
		}
	}
}

示例#12
文件: mirror-main.go 项目: balamurugana/mc

// doMirror - Mirror an object to multiple destination. URLs status contains a copy of sURLs and error if any.
func (ms *mirrorSession) doMirror(sURLs URLs) URLs {
	isFake := ms.Header.CommandBoolFlags["fake"]

	if sURLs.Error != nil { // Errorneous sURLs passed.
		return sURLs.WithError(sURLs.Error.Trace())
	}

	//s For a fake mirror make sure we update respective progress bars
	// and accounting readers under relevant conditions.
	if isFake {
		ms.status.Add(sURLs.SourceContent.Size)
		return sURLs.WithError(nil)
	}

	sourceAlias := sURLs.SourceAlias
	sourceURL := sURLs.SourceContent.URL
	targetAlias := sURLs.TargetAlias
	targetURL := sURLs.TargetContent.URL
	length := sURLs.SourceContent.Size

	ms.status.SetCaption(sourceURL.String() + ": ")

	sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
	targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
	ms.status.PrintMsg(mirrorMessage{
		Source:     sourcePath,
		Target:     targetPath,
		Size:       length,
		TotalCount: sURLs.TotalCount,
		TotalSize:  sURLs.TotalSize,
	})
	return uploadSourceToTargetURL(sURLs, ms.status)
}

示例#13
文件: env_windows.go 项目: go-stay/stay

func setUserDir() {
	user_app_data := filepath.ToSlash(os.Getenv("LOCALAPPDATA"))
	if user_app_data == "" {
		user_app_data = filepath.Join(filepath.ToSlash(os.Getenv("HOMEDRIVE")+os.Getenv("HOMEPATH")), "AppData", "Local")
	}
	USER_DIR = filepath.ToSlash(user_app_data)
}

示例#14
文件: archive_test.go 项目: joegross/terraform

func TestArchive_gitSubdir(t *testing.T) {
	if !testHasGit {
		t.Log("git not found, skipping")
		t.Skip()
	}

	// Git doesn't allow nested ".git" directories so we do some hackiness
	// here to get around that...
	testDir := testFixture("archive-git")
	oldName := filepath.ToSlash(filepath.Join(testDir, "DOTgit"))
	newName := filepath.ToSlash(filepath.Join(testDir, ".git"))
	os.Remove(newName)
	if err := os.Rename(oldName, newName); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Rename(newName, oldName)

	// testDir with VCS set to true
	r, err := CreateArchive(filepath.Join(testDir, "subdir"), &ArchiveOpts{VCS: true})
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	expected := []string{
		"hello.txt",
	}

	entries := testArchive(t, r, false)
	if !reflect.DeepEqual(entries, expected) {
		t.Fatalf("bad: %#v", entries)
	}
}

示例#15
文件: grapher.go 项目: ildarisaev/srclib-python

func (c *GraphContext) transformRef(rawRef *RawRef) (*graph.Ref, error) {
	defUnit, err := c.inferSourceUnit(rawRef, c.Reqs)
	if err != nil {
		return nil, err
	}

	defPath := string(rawRef.DefPath)
	if defPath == "" {
		defPath = "."
	}

	return &graph.Ref{
		DefRepo:     defUnit.Repo,
		DefUnitType: defUnit.Type,
		DefUnit:     defUnit.Name,
		DefPath:     filepath.ToSlash(defPath),

		Repo:     c.Unit.Repo,
		Unit:     c.Unit.Name,
		UnitType: c.Unit.Type,

		File:  filepath.ToSlash(rawRef.File),
		Start: rawRef.Start,
		End:   rawRef.End,
		Def:   rawRef.Def,
	}, nil
}

示例#16
文件: env_windows.go 项目: go-stay/stay

func setGlobalDir() {
	programData := filepath.ToSlash(os.Getenv("ALLUSERSPROFILE"))
	if programData == "" {
		programData = filepath.ToSlash(os.Getenv("ProgramData"))
	}
	GLOBAL_DIRS = programData
}

示例#17
文件: main.go 项目: bmizerany/vexp

// disallowVendorVisibility checks that srcDir is allowed to import p.
// The rules are the same as for /internal/ except that a path ending in /vendor
// is not subject to the rules, only subdirectories of vendor.
// This allows people to have packages and commands named vendor,
// for maximal compatibility with existing source trees.
func disallowVendorVisibility(srcDir string, p *Package, stk *importStack) *Package {
	// The stack includes p.ImportPath.
	// If that's the only thing on the stack, we started
	// with a name given on the command line, not an
	// import. Anything listed on the command line is fine.
	if len(*stk) == 1 {
		return p
	}

	// Check for "vendor" element.
	i, ok := findVendor(p.ImportPath)
	if !ok {
		return p
	}

	// Vendor is present.
	// Map import path back to directory corresponding to parent of vendor.
	if i > 0 {
		i-- // rewind over slash in ".../vendor"
	}
	parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
	if hasPathPrefix(filepath.ToSlash(srcDir), filepath.ToSlash(parent)) {
		return p
	}

	// Vendor is present, and srcDir is outside parent's tree. Not allowed.
	perr := *p
	perr.Error = &PackageError{
		ImportStack: stk.copy(),
		Err:         "use of vendored package not allowed",
	}
	perr.Incomplete = true
	return &perr
}

示例#18
文件: util.go 项目: ColourboxDevelopment/aws-sdk-go

// ContainingPackage returns the package containing filename.
//
// If filename is not absolute, it is interpreted relative to working directory dir.
// All I/O is via the build context's file system interface, if any.
//
// The '...Files []string' fields of the resulting build.Package are not
// populated (build.FindOnly mode).
//
// TODO(adonovan): call this from oracle when the tree thaws.
//
func ContainingPackage(ctxt *build.Context, dir, filename string) (*build.Package, error) {
	if !IsAbsPath(ctxt, filename) {
		filename = JoinPath(ctxt, dir, filename)
	}

	// We must not assume the file tree uses
	// "/" always,
	// `\` always,
	// or os.PathSeparator (which varies by platform),
	// but to make any progress, we are forced to assume that
	// paths will not use `\` unless the PathSeparator
	// is also `\`, thus we can rely on filepath.ToSlash for some sanity.

	dirSlash := path.Dir(filepath.ToSlash(filename)) + "/"

	// We assume that no source root (GOPATH[i] or GOROOT) contains any other.
	for _, srcdir := range ctxt.SrcDirs() {
		srcdirSlash := filepath.ToSlash(srcdir) + "/"
		if dirHasPrefix(dirSlash, srcdirSlash) {
			importPath := dirSlash[len(srcdirSlash) : len(dirSlash)-len("/")]
			return ctxt.Import(importPath, dir, build.FindOnly)
		}
	}

	return nil, fmt.Errorf("can't find package containing %s", filename)
}

示例#19
文件: file.go 项目: evaluation-alex/gosync

func loadLocalFiles(path string) (map[string]string, error) {
	files := map[string]string{}

	regulatedPath := filepath.ToSlash(path)
	loadMd5Sums := func(filePath string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			p := relativePath(regulatedPath, filepath.ToSlash(filePath))

			buf, err := ioutil.ReadFile(filePath)
			if err != nil {
				return err
			}

			hasher := md5.New()
			hasher.Write(buf)
			md5sum := fmt.Sprintf("%x", hasher.Sum(nil))
			files[p] = md5sum
		}
		return nil
	}

	err := filepath.Walk(path, loadMd5Sums)
	if err != nil {
		return files, err
	}

	log.Debugf("Loaded '%d' files from '%s'.", len(files), path)
	log.Infof("Loading local files complete.")

	return files, nil
}

示例#20
文件: repo.go 项目: emil2k/go-vcs

// Makes system-dependent SSH wrapper
func gitSSHWrapper(keyFile string, otherOpt string) (sshWrapperFile string, tempDir string, err error) {
	// TODO(sqs): encrypt and store the key in the env so that
	// attackers can't decrypt if they have disk access after our
	// process dies

	var script string

	if runtime.GOOS == "windows" {
		script = `
	@echo off
	ssh -o ControlMaster=no -o ControlPath=none ` + otherOpt + ` -i ` + filepath.ToSlash(keyFile) + ` "%@"
`
	} else {
		script = `
	#!/bin/sh
	exec /usr/bin/ssh -o ControlMaster=no -o ControlPath=none ` + otherOpt + ` -i ` + filepath.ToSlash(keyFile) + ` "[email protected]"
`
	}

	sshWrapperName, tempDir, err := internal.ScriptFile("go-vcs-gitcmd")
	if err != nil {
		return sshWrapperName, tempDir, err
	}

	err = internal.WriteFileWithPermissions(sshWrapperName, []byte(script), 0500)
	return sshWrapperName, tempDir, err
}

示例#21
文件: main.go 项目: heimonsy/minify

func expandOutputs(output string, dirDst, usePipe bool, tasks *[]task) bool {
	if output != "" {
		output = path.Clean(filepath.ToSlash(output))
		if output[len(output)-1] != '/' {
			info, err := os.Stat(output)
			if err == nil && info.Mode().IsDir() {
				output += "/"
			}
		}
		if dirDst {
			if output[len(output)-1] != '/' {
				output += "/"
			}
			if err := os.MkdirAll(output, 0777); err != nil {
				fmt.Fprintln(os.Stderr, "ERROR: "+err.Error())
				os.Exit(1)
			}
		} else if output[len(output)-1] == '/' {
			output += "out"
		}
	}

	if verbose {
		if output == "" {
			if usePipe {
				fmt.Fprintln(os.Stderr, "INFO:  minify to stdout")
			} else {
				fmt.Fprintln(os.Stderr, "INFO:  minify to overwrite itself")
			}
		} else if output[len(output)-1] != '/' {
			fmt.Fprintf(os.Stderr, "INFO:  minify to output file %v\n", output)
		} else if output == "./" {
			fmt.Fprintf(os.Stderr, "INFO:  minify to current working directory\n")
		} else {
			fmt.Fprintf(os.Stderr, "INFO:  minify to output directory %v\n", output)
		}
	}

	ok := true
	for i, t := range *tasks {
		if !usePipe && output == "" {
			(*tasks)[i].dst = (*tasks)[i].src
		} else {
			(*tasks)[i].dst = output
		}
		if len(output) > 0 && output[len(output)-1] == '/' {
			rel, err := filepath.Rel(t.srcDir, t.src)
			if err != nil {
				fmt.Fprintln(os.Stderr, "ERROR: "+err.Error())
				ok = false
			}
			(*tasks)[i].dst = path.Clean(filepath.ToSlash(path.Join(output, rel)))
		}
	}

	if usePipe && len(*tasks) == 0 {
		*tasks = append(*tasks, task{"", "", output})
	}
	return ok
}

示例#22
文件: assets.go 项目: influx6/todo

// AssetTree provides a map tree of files across the given directory that match the filenames being used
func AssetTree(dir string, ext string) (AssetMap, error) {
	var stat os.FileInfo
	var err error

	//do the path exists
	if stat, err = os.Stat(dir); err != nil {
		return nil, err
	}

	var tree = make(AssetMap)

	//do we have a directory?
	if !stat.IsDir() {

		var fext string
		var rel = filepath.Base(dir)

		if strings.Index(rel, ".") != -1 {
			fext = filepath.Ext(rel)
		}

		if fext == ext {
			tree[rel] = filepath.ToSlash(dir)
		}

	} else {
		filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {

			//if info is nil or is a directory when we skip
			if info == nil || info.IsDir() {
				return nil
			}

			var rel string
			var rerr error

			//is this path relative to the current one, if not,return err
			if rel, rerr = filepath.Rel(dir, path); rerr != nil {
				return rerr
			}

			var fext string

			if strings.Index(rel, ".") != -1 {
				fext = filepath.Ext(rel)
			}

			if fext == ext {
				tree[rel] = filepath.ToSlash(path)
				// tree[strings.TrimSuffix(rel, ext)] = filepath.ToSlash(path)
			}

			return nil
		})

	}

	return tree, nil
}

示例#23
文件: filter_test.go 项目: shaunstanislaus/modd

func TestBaseDir(t *testing.T) {
	for i, tt := range BaseDirTests {
		ret := BaseDir(tt.pattern)
		if filepath.ToSlash(ret) != filepath.ToSlash(tt.expected) {
			t.Errorf("%d: %q - Expected %q, got %q", i, tt.pattern, tt.expected, ret)
		}
	}
}

示例#24
文件: wrap.go 项目: involucro/involucro

func preparePathForTarHeader(filename string, sourceDir, prefix string) string {
	prefixWithoutLeadingSlash := strings.TrimPrefix(prefix, "/")

	slashed := filepath.ToSlash(filename)
	sourceDir = filepath.ToSlash(sourceDir)

	return rebaseFilename(sourceDir, prefixWithoutLeadingSlash, slashed)
}

示例#25
文件: qml.go 项目: pmeido/Arianrhod

// Load loads a new component with the provided location and with the
// content read from r. The location informs the resource name for
// logged messages, and its path is used to locate any other resources
// referenced by the QML content.
//
// Once a component is loaded, component instances may be created from
// the resulting object via its Create and CreateWindow methods.
func (e *Engine) Load(location string, r io.Reader) (Object, error) {
	var cdata *C.char
	var cdatalen C.int

	qrc := strings.HasPrefix(location, "qrc:")
	if qrc {
		if r != nil {
			return nil, fmt.Errorf("cannot load qrc resource while providing data: %s", location)
		}
	} else {
		data, err := ioutil.ReadAll(r)
		if err != nil {
			return nil, err
		}
		if colon, slash := strings.Index(location, ":"), strings.Index(location, "/"); colon == -1 || slash <= colon {
			if filepath.IsAbs(location) {
				location = "file:///" + filepath.ToSlash(location)
			} else {
				dir, err := os.Getwd()
				if err != nil {
					return nil, fmt.Errorf("cannot obtain absolute path: %v", err)
				}
				location = "file:///" + filepath.ToSlash(filepath.Join(dir, location))
			}
		}

		// Workaround issue #84 (QTBUG-41193) by not refering to an existent file.
		if s := strings.TrimPrefix(location, "file:///"); s != location {
			if _, err := os.Stat(filepath.FromSlash(s)); err == nil {
				location = location + "."
			}
		}

		cdata, cdatalen = unsafeBytesData(data)
	}

	var err error
	cloc, cloclen := unsafeStringData(location)
	comp := &Common{engine: e}
	RunMain(func() {
		// TODO The component's parent should probably be the engine.
		comp.addr = C.newComponent(e.addr, nilPtr)
		if qrc {
			C.componentLoadURL(comp.addr, cloc, cloclen)
		} else {
			C.componentSetData(comp.addr, cdata, cdatalen, cloc, cloclen)
		}
		message := C.componentErrorString(comp.addr)
		if message != nilCharPtr {
			err = errors.New(strings.TrimRight(C.GoString(message), "\n"))
			C.free(unsafe.Pointer(message))
		}
	})
	if err != nil {
		return nil, err
	}
	return comp, nil
}

示例#26
文件: client.go 项目: jemkzheng/go-swagger

func (c *clientGenerator) Generate() error {
	app, err := c.makeCodegenApp()
	app.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ModelsPackage))}
	if err != nil {
		return err
	}

	if c.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(app), "", "  ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	for _, mod := range app.Models {
		mod.IncludeValidator = true // a.GenOpts.IncludeValidator
		gen := &definitionGenerator{
			Name:    mod.Name,
			SpecDoc: c.SpecDoc,
			Target:  filepath.Join(c.Target, c.ModelsPackage),
			Data:    &mod,
		}
		if err := gen.generateModel(); err != nil {
			return err
		}
	}

	for i := range app.OperationGroups {
		opGroup := app.OperationGroups[i]
		opGroup.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ModelsPackage))}
		opGroup.RootPackage = c.ClientPackage
		app.OperationGroups[i] = opGroup
		sort.Sort(opGroup.Operations)
		for _, op := range opGroup.Operations {
			if op.Package == "" {
				op.Package = c.Package
			}
			if err := c.generateParameters(&op); err != nil {
				return err
			}

			if err := c.generateResponses(&op); err != nil {
				return err
			}
		}
		app.DefaultImports = append(app.DefaultImports, filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ClientPackage, opGroup.Name)))
		if err := c.generateGroupClient(opGroup); err != nil {
			return err
		}
	}

	sort.Sort(app.OperationGroups)

	if err := c.generateFacade(&app); err != nil {
		return err
	}

	return nil
}

示例#27
文件: setup.go 项目: anthonybrown/caddy

func loadParams(c *caddy.Controller, mdc *Config) error {
	cfg := httpserver.GetConfig(c.Key)

	switch c.Val() {
	case "ext":
		for _, ext := range c.RemainingArgs() {
			mdc.Extensions[ext] = struct{}{}
		}
		return nil
	case "css":
		if !c.NextArg() {
			return c.ArgErr()
		}
		mdc.Styles = append(mdc.Styles, c.Val())
		return nil
	case "js":
		if !c.NextArg() {
			return c.ArgErr()
		}
		mdc.Scripts = append(mdc.Scripts, c.Val())
		return nil
	case "template":
		tArgs := c.RemainingArgs()
		switch len(tArgs) {
		default:
			return c.ArgErr()
		case 1:
			fpath := filepath.ToSlash(filepath.Clean(cfg.Root + string(filepath.Separator) + tArgs[0]))

			if err := SetTemplate(mdc.Template, "", fpath); err != nil {
				c.Errf("default template parse error: %v", err)
			}
			return nil
		case 2:
			fpath := filepath.ToSlash(filepath.Clean(cfg.Root + string(filepath.Separator) + tArgs[1]))

			if err := SetTemplate(mdc.Template, tArgs[0], fpath); err != nil {
				c.Errf("template parse error: %v", err)
			}
			return nil
		}
	case "templatedir":
		if !c.NextArg() {
			return c.ArgErr()
		}
		_, err := mdc.Template.ParseGlob(c.Val())
		if err != nil {
			c.Errf("template load error: %v", err)
		}
		if c.NextArg() {
			return c.ArgErr()
		}
		return nil
	default:
		return c.Err("Expected valid markdown configuration property")
	}
}

示例#28
文件: watch.go 项目: johnjohnsp1/modd

// isUnder takes two absolute paths, and returns true if child is under parent.
func isUnder(parent string, child string) bool {
	parent = filepath.ToSlash(parent)
	child = filepath.ToSlash(child)
	off := strings.Index(child, parent)
	if off == 0 && (len(child) == len(parent) || child[len(parent)] == '/') {
		return true
	}
	return false
}

示例#29
文件: tar.go 项目: wwitzel3/utils

// writeContents creates an entry for the given file
// or directory in the given tar archive.
func writeContents(fileName, strip string, tarw *tar.Writer) error {
	f, err := os.Open(fileName)
	if err != nil {
		return err
	}
	defer f.Close()
	fInfo, err := os.Lstat(fileName)
	if err != nil {
		return err
	}
	link := ""

	if fInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
		link, err = filepath.EvalSymlinks(fileName)

		if err != nil {
			return fmt.Errorf("cannnot dereference symlink: %v", err)
		}

		link = filepath.ToSlash(strings.TrimPrefix(link, strip))
	}
	h, err := tar.FileInfoHeader(fInfo, link)
	if err != nil {
		return fmt.Errorf("cannot create tar header for %q: %v", fileName, err)
	}
	h.Name = filepath.ToSlash(strings.TrimPrefix(fileName, strip))
	if err := tarw.WriteHeader(h); err != nil {
		return fmt.Errorf("cannot write header for %q: %v", fileName, err)
	}
	if fInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
		return nil
	}
	if !fInfo.IsDir() {
		if _, err := io.Copy(tarw, f); err != nil {
			return fmt.Errorf("failed to write %q: %v", fileName, err)
		}
		return nil
	}

	for {
		names, err := f.Readdirnames(100)
		// will return at most 100 names and if less than 100 remaining
		// next call will return io.EOF and no names
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return fmt.Errorf("error reading directory %q: %v", fileName, err)
		}
		for _, name := range names {
			if err := writeContents(filepath.Join(fileName, name), strip, tarw); err != nil {
				return err
			}
		}
	}

}

示例#30
文件: site.go 项目: lismore/hugo

// for non-pages in the site tree
func (s *SiteInfo) githubFileLink(ref string, currentPage *Page, relative bool) (string, error) {
	var refURL *url.URL
	var err error

	// TODO can I make this a param to `hugo --use-github-links=/docs`?
	// SVEN: add more tests - the prefix might be a real dir inside tho - add some pages that have it as a legitimate path
	repositoryPathPrefix := "/docs"

	refURL, err = url.Parse(strings.TrimPrefix(ref, repositoryPathPrefix))
	if err != nil {
		return "", err
	}

	if refURL.Scheme != "" {
		// TODO: consider looking for http(s?)://github.com/user/project/prefix and replacing it - tho this may be intentional, so idk
		//return "", fmt.Errorf("Not a plain filepath link (%s)", ref)
		// Treat this as not an error, as the link is used as-is
		return ref, nil
	}

	var target *source.File
	var link string

	if refURL.Path != "" {
		refPath := filepath.Clean(filepath.FromSlash(refURL.Path))

		if strings.IndexRune(refPath, os.PathSeparator) == 0 { // filepath.IsAbs fails to me.
			refPath = refPath[1:]
		} else {
			if currentPage != nil {
				refPath = filepath.Join(currentPage.Source.Dir(), refURL.Path)
			}
		}

		for _, file := range []*source.File(*s.Files) {
			if file.Path() == refPath {
				target = file
				break
			}
		}

		if target == nil {
			return "", fmt.Errorf("No file found for \"%s\" on page \"%s\".\n", ref, currentPage.Source.Path())
		}

		link = target.Path()
		// SVEN: look at filepath.Rel() it might help, got the rel/non-rel url's (dangerous tho)
		// SVEN: reconsider the fact I hardcoded the `relative` bool in both github resolvers
		if relative {
			return "./" + filepath.ToSlash(link), nil
		} else {
			return "/" + filepath.ToSlash(link), nil
		}
	}

	return "", fmt.Errorf("failed to find a file to match \"%s\" on page \"%s\"", ref, currentPage.Source.Path())
}

展开阅读全文