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


Golang compiler.WriteProgramCode函数代码示例

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


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

示例1: Compile

func Compile(ctx context.Context, source []byte, mapping bool) ([]byte, error) {
	vos := vosctx.FromContext(ctx)

	options := &build.Options{
		GOROOT:        vos.Getenv("GOROOT"),
		GOPATH:        vos.Getenv("GOPATH"),
		CreateMapFile: mapping,
	}
	s := build.NewSession(options)

	packages := make(map[string]*compiler.Archive)
	importContext := &compiler.ImportContext{
		Packages: s.Types,
		Import:   s.BuildImportPath,
	}

	fileSet := token.NewFileSet()

	file, err := parser.ParseFile(fileSet, "prog.go", source, parser.ParseComments)
	if err != nil {
		return nil, kerr.Wrap("NCYFEKGCWX", err)
	}

	mainPkg, err := compiler.Compile("main", []*ast.File{file}, fileSet, importContext, false)
	if err != nil {
		return nil, kerr.Wrap("KPHUKOLTBX", err)
	}
	packages["main"] = mainPkg

	bufCode := bytes.NewBuffer(nil)
	filter := &compiler.SourceMapFilter{Writer: bufCode}
	allPkgs, err := compiler.ImportDependencies(mainPkg, importContext.Import)
	if err != nil {
		return nil, kerr.Wrap("TIMQHFQTWL", err)
	}

	if mapping {
		bufMap := bytes.NewBuffer(nil)
		smap := &sourcemap.Map{File: "script.js"}
		filter.MappingCallback = build.NewMappingCallback(smap, options.GOROOT, options.GOPATH, false)
		if err := compiler.WriteProgramCode(allPkgs, filter); err != nil {
			return nil, kerr.Wrap("YKQEKRKBPL", err)
		}
		if err := smap.WriteTo(bufMap); err != nil {
			return nil, kerr.Wrap("VYQGYAAADG", err)
		}
		return bufMap.Bytes(), nil
	}

	if err := compiler.WriteProgramCode(allPkgs, filter); err != nil {
		return nil, kerr.Wrap("DPPVHCOTBQ", err)
	}
	if _, err := bufCode.WriteString("//# sourceMappingURL=script.js.map\n"); err != nil {
		return nil, kerr.Wrap("CXXKWQVGUI", err)
	}
	return bufCode.Bytes(), nil
}
开发者ID:kego,项目名称:ke,代码行数:57,代码来源:compiler.go

示例2: Build

// Build creates a build and returns the first error happening. All errors are typed.
func (b *builder) Build() error {
	if b.target == nil {
		return ErrorMissingTarget{}
	}
	fileSet := token.NewFileSet()

	files := []*ast.File{}

	for name, reader := range b.files {
		if reader == nil {
			return ErrorParsing{name, "reader must not be nil"}
		}
		f, err := parser.ParseFile(fileSet, name, reader, 0)
		if err != nil {
			return ErrorParsing{name, err.Error()}
		}
		files = append(files, f)
	}

	s := build.NewSession(b.options)

	archive, err := compiler.Compile(b.pkgName, files, fileSet, s.ImportContext, b.options.Minify)
	if err != nil {
		return ErrorCompiling(err.Error())
	}

	deps, err := compiler.ImportDependencies(archive, s.ImportContext.Import)
	if err != nil {
		return ErrorImportingDependencies(err.Error())
	}

	return compiler.WriteProgramCode(deps, &compiler.SourceMapFilter{Writer: b.target})
}
开发者ID:rexposadas,项目名称:gx,代码行数:34,代码来源:gopherjslib.go

示例3: BuildJSDir

// BuildJSDir builds the js file and returns the content.
// goPkgPath must be a package path eg. github.com/influx6/haiku-examples/app
func BuildJSDir(jsession *JSSession, dir, importpath, name string, js, jsmap *bytes.Buffer) error {

	session, options := jsession.Session, jsession.Option

	buildpkg, err := build.NewBuildContext(session.InstallSuffix(), options.BuildTags).ImportDir(dir, 0)

	if err != nil {
		return err
	}

	pkg := &build.PackageData{Package: buildpkg}
	pkg.ImportPath = importpath

	//build the package using the sessios
	if err = session.BuildPackage(pkg); err != nil {
		return err
	}

	//build up the source map also
	smfilter := &compiler.SourceMapFilter{Writer: js}
	smsrc := &sourcemap.Map{File: name + ".js"}
	smfilter.MappingCallback = build.NewMappingCallback(smsrc, options.GOROOT, options.GOPATH)
	deps, err := compiler.ImportDependencies(pkg.Archive, session.ImportContext.Import)

	if err != nil {
		return err
	}

	err = compiler.WriteProgramCode(deps, smfilter)

	smsrc.WriteTo(jsmap)
	js.WriteString("//# sourceMappingURL=" + name + ".map.js\n")

	return nil
}
开发者ID:influx6,项目名称:reactors,代码行数:37,代码来源:js.go

示例4: WriteCommandPackage

func (s *Session) WriteCommandPackage(pkg *PackageData, pkgObj string) error {
	if !pkg.IsCommand() || pkg.UpToDate {
		return nil
	}

	if err := os.MkdirAll(filepath.Dir(pkgObj), 0777); err != nil {
		return err
	}
	codeFile, err := os.Create(pkgObj)
	if err != nil {
		return err
	}
	defer codeFile.Close()

	sourceMapFilter := &compiler.SourceMapFilter{Writer: codeFile}
	if s.options.CreateMapFile {
		m := sourcemap.Map{File: filepath.Base(pkgObj)}
		mapFile, err := os.Create(pkgObj + ".map")
		if err != nil {
			return err
		}

		defer func() {
			m.WriteTo(mapFile)
			mapFile.Close()
			fmt.Fprintf(codeFile, "//# sourceMappingURL=%s.map\n", filepath.Base(pkgObj))
		}()

		sourceMapFilter.MappingCallback = func(generatedLine, generatedColumn int, fileSet *token.FileSet, originalPos token.Pos) {
			if !originalPos.IsValid() {
				m.AddMapping(&sourcemap.Mapping{GeneratedLine: generatedLine, GeneratedColumn: generatedColumn})
				return
			}
			pos := fileSet.Position(originalPos)
			file := pos.Filename
			switch {
			case strings.HasPrefix(file, s.options.GOPATH):
				file = filepath.ToSlash(filepath.Join("/gopath", file[len(s.options.GOPATH):]))
			case strings.HasPrefix(file, s.options.GOROOT):
				file = filepath.ToSlash(filepath.Join("/goroot", file[len(s.options.GOROOT):]))
			default:
				file = filepath.Base(file)
			}
			m.AddMapping(&sourcemap.Mapping{GeneratedLine: generatedLine, GeneratedColumn: generatedColumn, OriginalFile: file, OriginalLine: pos.Line, OriginalColumn: pos.Column})
		}
	}

	deps, err := s.ImportDependencies(pkg.Archive)
	if err != nil {
		return err
	}
	compiler.WriteProgramCode(deps, s.ImportContext, sourceMapFilter)

	return nil
}
开发者ID:phaikawl,项目名称:gopherjs,代码行数:55,代码来源:build.go

示例5: BuildJS

// BuildJS builds the js file and returns the content.
// goPkgPath must be a package path eg. github.com/influx6/haiku-examples/app
func BuildJS(jsession *JSSession, goPkgPath, name string, js, jsmap *bytes.Buffer) error {

	session, options := jsession.Session, jsession.Option

	//get the build path
	buildpkg, err := build.Import(goPkgPath, 0, session.InstallSuffix(), options.BuildTags)

	if err != nil {
		return err
	}

	if buildpkg.Name != "main" {
		return ErrNotMain
	}

	//build the package data for building
	// pkg := &build.PackageData{Package: buildpkg}

	//build the package using the sessios
	if err = session.BuildPackage(buildpkg); err != nil {
		return err
	}

	//build up the source map also
	smfilter := &compiler.SourceMapFilter{Writer: js}
	smsrc := &sourcemap.Map{File: name + ".js"}
	smfilter.MappingCallback = build.NewMappingCallback(smsrc, options.GOROOT, options.GOPATH)
	deps, err := compiler.ImportDependencies(buildpkg.Archive, session.ImportContext.Import)

	if err != nil {
		return err
	}

	err = compiler.WriteProgramCode(deps, smfilter)

	smsrc.WriteTo(jsmap)
	js.WriteString("//# sourceMappingURL=" + name + ".map.js\n")

	return nil
}
开发者ID:influx6,项目名称:reactors,代码行数:42,代码来源:js.go

示例6: WriteCommandPackage

func (s *Session) WriteCommandPackage(archive *compiler.Archive, pkgObj string) error {
	if err := os.MkdirAll(filepath.Dir(pkgObj), 0777); err != nil {
		return err
	}
	codeFile, err := os.Create(pkgObj)
	if err != nil {
		return err
	}
	defer codeFile.Close()

	sourceMapFilter := &compiler.SourceMapFilter{Writer: codeFile}
	if s.options.CreateMapFile {
		m := &sourcemap.Map{File: filepath.Base(pkgObj)}
		mapFile, err := os.Create(pkgObj + ".map")
		if err != nil {
			return err
		}

		defer func() {
			m.WriteTo(mapFile)
			mapFile.Close()
			fmt.Fprintf(codeFile, "//# sourceMappingURL=%s.map\n", filepath.Base(pkgObj))
		}()

		sourceMapFilter.MappingCallback = NewMappingCallback(m, s.options.GOROOT, s.options.GOPATH)
	}

	deps, err := compiler.ImportDependencies(archive, func(path string) (*compiler.Archive, error) {
		if archive, ok := s.Archives[path]; ok {
			return archive, nil
		}
		_, archive, err := s.buildImportPathWithSrcDir(path, "")
		return archive, err
	})
	if err != nil {
		return err
	}
	return compiler.WriteProgramCode(deps, sourceMapFilter)
}
开发者ID:moul,项目名称:advanced-ssh-config,代码行数:39,代码来源:build.go

示例7: WriteCommandPackage

func (s *Session) WriteCommandPackage(pkg *PackageData, pkgObj string) error {
	if !pkg.IsCommand() || pkg.UpToDate {
		return nil
	}

	if err := os.MkdirAll(filepath.Dir(pkgObj), 0777); err != nil {
		return err
	}
	codeFile, err := os.Create(pkgObj)
	if err != nil {
		return err
	}
	defer codeFile.Close()

	sourceMapFilter := &compiler.SourceMapFilter{Writer: codeFile}
	if s.options.CreateMapFile {
		m := &sourcemap.Map{File: filepath.Base(pkgObj)}
		mapFile, err := os.Create(pkgObj + ".map")
		if err != nil {
			return err
		}

		defer func() {
			m.WriteTo(mapFile)
			mapFile.Close()
			fmt.Fprintf(codeFile, "//# sourceMappingURL=%s.map\n", filepath.Base(pkgObj))
		}()

		sourceMapFilter.MappingCallback = NewMappingCallback(m, s.options.GOROOT, s.options.GOPATH)
	}

	deps, err := compiler.ImportDependencies(pkg.Archive, s.BuildImportPath)
	if err != nil {
		return err
	}
	return compiler.WriteProgramCode(deps, sourceMapFilter)
}
开发者ID:flying99999,项目名称:gopherjs,代码行数:37,代码来源:build.go

示例8: Open

func (fs serveCommandFileSystem) Open(requestName string) (http.File, error) {
	name := path.Join(fs.serveRoot, requestName[1:]) // requestName[0] == '/'

	dir, file := path.Split(name)
	base := path.Base(dir) // base is parent folder name, which becomes the output file name.

	isPkg := file == base+".js"
	isMap := file == base+".js.map"
	isIndex := file == "index.html"

	if isPkg || isMap || isIndex {
		// If we're going to be serving our special files, make sure there's a Go command in this folder.
		s := gbuild.NewSession(fs.options)
		pkg, err := gbuild.Import(path.Dir(name), 0, s.InstallSuffix(), fs.options.BuildTags)
		if err != nil || pkg.Name != "main" {
			isPkg = false
			isMap = false
			isIndex = false
		}

		switch {
		case isPkg:
			buf := bytes.NewBuffer(nil)
			browserErrors := bytes.NewBuffer(nil)
			exitCode := handleError(func() error {
				archive, err := s.BuildPackage(pkg)
				if err != nil {
					return err
				}

				sourceMapFilter := &compiler.SourceMapFilter{Writer: buf}
				m := &sourcemap.Map{File: base + ".js"}
				sourceMapFilter.MappingCallback = gbuild.NewMappingCallback(m, fs.options.GOROOT, fs.options.GOPATH)

				deps, err := compiler.ImportDependencies(archive, s.BuildImportPath)
				if err != nil {
					return err
				}
				if err := compiler.WriteProgramCode(deps, sourceMapFilter); err != nil {
					return err
				}

				mapBuf := bytes.NewBuffer(nil)
				m.WriteTo(mapBuf)
				buf.WriteString("//# sourceMappingURL=" + base + ".js.map\n")
				fs.sourceMaps[name+".map"] = mapBuf.Bytes()

				return nil
			}, fs.options, browserErrors)
			if exitCode != 0 {
				buf = browserErrors
			}
			return newFakeFile(base+".js", buf.Bytes()), nil

		case isMap:
			if content, ok := fs.sourceMaps[name]; ok {
				return newFakeFile(base+".js.map", content), nil
			}
		}
	}

	for _, d := range fs.dirs {
		dir := http.Dir(filepath.Join(d, "src"))

		f, err := dir.Open(name)
		if err == nil {
			return f, nil
		}

		// source maps are served outside of serveRoot
		f, err = dir.Open(requestName)
		if err == nil {
			return f, nil
		}
	}

	if isIndex {
		// If there was no index.html file in any dirs, supply our own.
		return newFakeFile("index.html", []byte(`<html><head><meta charset="utf-8"><script src="`+base+`.js"></script></head></html>`)), nil
	}

	return nil, os.ErrNotExist
}
开发者ID:pombredanne,项目名称:camlistore,代码行数:83,代码来源:tool.go

示例9: Open

func (fs serveCommandFileSystem) Open(name string) (http.File, error) {
	for _, d := range fs.dirs {
		file, err := http.Dir(filepath.Join(d, "src")).Open(name)
		if err == nil {
			return file, nil
		}
	}

	if strings.HasSuffix(name, "/main.js.map") {
		if content, ok := fs.sourceMaps[name]; ok {
			return newFakeFile("main.js.map", content), nil
		}
	}

	isIndex := strings.HasSuffix(name, "/index.html")
	isMain := strings.HasSuffix(name, "/main.js")
	if isIndex || isMain {
		s := gbuild.NewSession(fs.options)
		buildPkg, err := gbuild.Import(path.Dir(name[1:]), 0, s.InstallSuffix(), fs.options.BuildTags)
		if err != nil || buildPkg.Name != "main" {
			return nil, os.ErrNotExist
		}

		if isIndex {
			return newFakeFile("index.html", []byte(`<html><head><meta charset="utf-8"><script src="main.js"></script></head></html>`)), nil
		}

		if isMain {
			buf := bytes.NewBuffer(nil)
			browserErrors := bytes.NewBuffer(nil)
			exitCode := handleError(func() error {
				pkg := &gbuild.PackageData{Package: buildPkg}
				if err := s.BuildPackage(pkg); err != nil {
					return err
				}

				sourceMapFilter := &compiler.SourceMapFilter{Writer: buf}
				m := &sourcemap.Map{File: "main.js"}
				sourceMapFilter.MappingCallback = gbuild.NewMappingCallback(m, fs.options.GOROOT, fs.options.GOPATH)

				deps, err := compiler.ImportDependencies(pkg.Archive, s.ImportContext.Import)
				if err != nil {
					return err
				}
				if err := compiler.WriteProgramCode(deps, sourceMapFilter); err != nil {
					return err
				}

				mapBuf := bytes.NewBuffer(nil)
				m.WriteTo(mapBuf)
				buf.WriteString("//# sourceMappingURL=main.js.map\n")
				fs.sourceMaps[name+".map"] = mapBuf.Bytes()

				return nil
			}, fs.options, browserErrors)
			if exitCode != 0 {
				buf = browserErrors
			}
			return newFakeFile("main.js", buf.Bytes()), nil
		}
	}

	return nil, os.ErrNotExist
}
开发者ID:wmydz1,项目名称:gopherjs,代码行数:64,代码来源:tool.go

示例10: main


//.........这里部分代码省略.........
					req.ResponseType = xhr.ArrayBuffer
					go func(path string) {
						err := req.Send(nil)
						if err != nil || req.Status != 200 {
							scope.Apply(func() {
								scope.Set("output", []Line{Line{"type": "err", "content": `failed to load package "` + path + `"`}})
							})
							return
						}

						data := js.Global.Get("Uint8Array").New(req.Response).Interface().([]byte)
						packages[path], err = compiler.ReadArchive(path+".a", path, bytes.NewReader(data), importContext.Packages)
						if err != nil {
							scope.Apply(func() {
								scope.Set("output", []Line{Line{"type": "err", "content": err.Error()}})
							})
							return
						}
						pkgsReceived++
						if pkgsReceived == len(pkgsToLoad) {
							run(loadOnly)
						}
					}(path)
				}
				return
			}

			if loadOnly {
				return
			}

			jsCode := bytes.NewBuffer(nil)
			jsCode.WriteString("try{\n")
			compiler.WriteProgramCode(allPkgs, &compiler.SourceMapFilter{Writer: jsCode})
			jsCode.WriteString("} catch (err) {\ngoPanicHandler(err.message);\n}\n")
			js.Global.Set("$checkForDeadlock", true)
			js.Global.Call("eval", js.InternalObject(jsCode.String()))
		}
		scope.Set("run", run)
		go func() {
			<-codeReady // Wait for "code" value to be ready.
			run(true)
		}()

		scope.Set("format", func() {
			out, err := format.Source([]byte(scope.Get("code").String()))
			if err != nil {
				scope.Set("output", []Line{Line{"type": "err", "content": err.Error()}})
				return
			}
			scope.Set("code", string(out))
			scope.Set("output", []Line{})
		})

		scope.Set("share", func() {
			req := xhr.NewRequest("POST", "http://"+snippetStoreHost+"/share")
			req.ResponseType = xhr.ArrayBuffer
			go func() {
				err := req.Send([]byte(scope.Get("code").String())) // Send as binary.
				if err != nil || req.Status != 200 {
					scope.Apply(func() {
						scope.Set("output", []Line{Line{"type": "err", "content": `failed to share snippet`}})
					})
					return
				}
开发者ID:gbbr,项目名称:gopherjs.github.io,代码行数:66,代码来源:playground.go

示例11: control


//.........这里部分代码省略.........

		mainPkg, err := compiler.Compile("main",
			[]*ast.File{file}, fileSet,
			importContext, false,
		)
		packages["main"] = mainPkg
		if err != nil && len(pkgsToLoad) == 0 {
			if list, ok := err.(compiler.ErrorList); ok {
				output := make([]Line, 0)
				for _, entry := range list {
					output = append(output, errErrLine(entry))
				}
				scope.Set("output", output)
				return
			}
			scope.Set("output", []Line{errErrLine(err)})
			return
		}

		var allPkgs []*compiler.Archive
		if len(pkgsToLoad) == 0 {
			for _, depPath := range mainPkg.Dependencies {
				dep, _ := importContext.Import(string(depPath))
				allPkgs = append(allPkgs, dep)
			}
			allPkgs = append(allPkgs, mainPkg)
		}

		if len(pkgsToLoad) != 0 {
			pkgsReceived = 0
			for _, p := range pkgsToLoad {
				path := p

				req := js.Global.Get("XMLHttpRequest").New()
				req.Call("open", "GET", "pkg/"+path+".a", true)
				req.Set("responseType", "arraybuffer")
				req.Set("onload", func() {
					if req.Get("status").Int() != 200 {

						f := func() {
							emsg := fmt.Sprintf("cannot load package \"%s\"", path)
							scope.Set("output", []Line{errLine(emsg)})
						}
						scope.Apply(f)
						return
					}

					data := js.Global.Get("Uint8Array").New(req.Get("response")).Interface().([]byte)
					packages[path], err = compiler.UnmarshalArchive(
						path+".a", path, []byte(data), importContext,
					)
					if err != nil {
						scope.Apply(func() {
							scope.Set("output", []Line{errErrLine(err)})
						})
						return
					}
					pkgsReceived++
					if pkgsReceived == len(pkgsToLoad) {
						run(loadOnly)
					}
				})
				req.Call("send")
			}
			return
		}

		if loadOnly {
			return
		}

		mainPkgCode := bytes.NewBuffer(nil)
		compiler.WritePkgCode(packages["main"], false,
			&compiler.SourceMapFilter{Writer: mainPkgCode},
		)
		// scope.Set("generated", mainPkgCode.String())

		jsCode := bytes.NewBuffer(nil)
		jsCode.WriteString("try{\n")
		compiler.WriteProgramCode(allPkgs, importContext,
			&compiler.SourceMapFilter{Writer: jsCode},
		)
		jsCode.WriteString("} catch (err) {\ngoPanicHandler(err.message);\n}\n")
		js.Global.Call("eval", js.InternalObject(jsCode.String()))
	}

	scope.Set("run", run)
	run(true)

	scope.Set("format", func() {
		out, err := format.Source(getCode())
		if err != nil {
			scope.Set("output", []Line{errErrLine(err)})
			return
		}

		setCode(string(out))
		scope.Set("output", []Line{})
	})
}
开发者ID:h8liu,项目名称:h8liu.github.io,代码行数:101,代码来源:playground.go


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