本文整理汇总了Golang中github.com/gopherjs/gopherjs/build.NewSession函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSession函数的具体用法?Golang NewSession怎么用?Golang NewSession使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewSession函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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})
}
示例2: 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
}
示例3: NewJSSession
// NewJSSession returns a new session for build js files
func NewJSSession(tags []string, verbose, watch bool) *JSSession {
options := &build.Options{
Verbose: verbose,
Watch: watch,
CreateMapFile: true,
Minify: true,
BuildTags: tags,
}
session := build.NewSession(options)
return &JSSession{
Session: session,
Option: options,
}
}
示例4: Handler
func (g *GinGopher) Handler(c *gin.Context) {
f, err := ioutil.TempFile("", "gingopher")
if err != nil {
c.String(200, "console.error(%s);", strconv.Quote(err.Error()))
return
}
f.Close()
filename := f.Name()
defer os.Remove(filename)
options := &gbuild.Options{
GOROOT: "",
GOPATH: os.Getenv("GOPATH"),
Verbose: false,
Quiet: false,
Watch: false,
CreateMapFile: false,
Minify: false,
Color: true,
}
finalPath := "/"
// Try to deduce the package path.
paths := strings.Split(options.GOPATH, ":")
for _, p := range paths {
candidatePath := path.Join(p, "src", g.pkg)
st, e := os.Stat(candidatePath)
if e == nil && st.IsDir() {
finalPath = candidatePath
break
}
}
s := gbuild.NewSession(options)
err = s.BuildDir(finalPath, g.pkg, filename)
if err != nil {
c.String(200, "console.error(%s);", strconv.Quote(err.Error()))
return
}
http.ServeFile(c.Writer, c.Request, f.Name())
}
示例5: main
func main() {
options := &gbuild.Options{CreateMapFile: true}
var pkgObj string
pflag.BoolVarP(&options.Verbose, "verbose", "v", false, "print the names of packages as they are compiled")
flagVerbose := pflag.Lookup("verbose")
pflag.BoolVarP(&options.Quiet, "quiet", "q", false, "suppress non-fatal warnings")
flagQuiet := pflag.Lookup("quiet")
pflag.BoolVarP(&options.Watch, "watch", "w", false, "watch for changes to the source files")
flagWatch := pflag.Lookup("watch")
pflag.BoolVarP(&options.Minify, "minify", "m", false, "minify generated code")
flagMinify := pflag.Lookup("minify")
pflag.BoolVar(&options.Color, "color", terminal.IsTerminal(int(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb", "colored output")
flagColor := pflag.Lookup("color")
tags := pflag.String("tags", "", "a list of build tags to consider satisfied during the build")
flagTags := pflag.Lookup("tags")
cmdBuild := &cobra.Command{
Use: "build [packages]",
Short: "compile packages and dependencies",
}
cmdBuild.Flags().StringVarP(&pkgObj, "output", "o", "", "output file")
cmdBuild.Flags().AddFlag(flagVerbose)
cmdBuild.Flags().AddFlag(flagQuiet)
cmdBuild.Flags().AddFlag(flagWatch)
cmdBuild.Flags().AddFlag(flagMinify)
cmdBuild.Flags().AddFlag(flagColor)
cmdBuild.Flags().AddFlag(flagTags)
cmdBuild.Run = func(cmd *cobra.Command, args []string) {
options.BuildTags = strings.Fields(*tags)
for {
s := gbuild.NewSession(options)
exitCode := handleError(func() error {
if len(args) == 0 {
return s.BuildDir(currentDirectory, currentDirectory, pkgObj)
}
if strings.HasSuffix(args[0], ".go") || strings.HasSuffix(args[0], ".inc.js") {
for _, arg := range args {
if !strings.HasSuffix(arg, ".go") && !strings.HasSuffix(arg, ".inc.js") {
return fmt.Errorf("named files must be .go or .inc.js files")
}
}
if pkgObj == "" {
basename := filepath.Base(args[0])
pkgObj = basename[:len(basename)-3] + ".js"
}
names := make([]string, len(args))
for i, name := range args {
name = filepath.ToSlash(name)
names[i] = name
}
if err := s.BuildFiles(args, pkgObj, currentDirectory); err != nil {
return err
}
return nil
}
for _, pkgPath := range args {
pkgPath = filepath.ToSlash(pkgPath)
pkg, err := gbuild.Import(pkgPath, 0, s.InstallSuffix(), options.BuildTags)
if err != nil {
return err
}
archive, err := s.BuildPackage(pkg)
if err != nil {
return err
}
if pkgObj == "" {
pkgObj = filepath.Base(args[0]) + ".js"
}
if pkg.IsCommand() && !pkg.UpToDate {
if err := s.WriteCommandPackage(archive, pkgObj); err != nil {
return err
}
}
}
return nil
}, options, nil)
os.Exit(exitCode)
}
}
cmdInstall := &cobra.Command{
Use: "install [packages]",
Short: "compile and install packages and dependencies",
}
cmdInstall.Flags().AddFlag(flagVerbose)
cmdInstall.Flags().AddFlag(flagQuiet)
cmdInstall.Flags().AddFlag(flagWatch)
cmdInstall.Flags().AddFlag(flagMinify)
cmdInstall.Flags().AddFlag(flagColor)
cmdInstall.Flags().AddFlag(flagTags)
cmdInstall.Run = func(cmd *cobra.Command, args []string) {
options.BuildTags = strings.Fields(*tags)
for {
s := gbuild.NewSession(options)
//.........这里部分代码省略.........
示例6: 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
}
示例7: main
func main() {
flags := flag.NewFlagSet("", flag.ContinueOnError)
cmd := "help"
var cmdArgs []string
if err := flags.Parse(os.Args[1:]); err == nil && flags.NArg() != 0 {
cmd = flags.Arg(0)
cmdArgs = flags.Args()[1:]
if cmd == "help" && flags.NArg() == 2 {
cmd = flags.Arg(1)
cmdArgs = []string{"--help"}
}
}
options := &gbuild.Options{CreateMapFile: true}
switch cmd {
case "build":
buildFlags := flag.NewFlagSet("build command", flag.ExitOnError)
var pkgObj string
buildFlags.StringVar(&pkgObj, "o", "", "output file")
buildFlags.BoolVar(&options.Verbose, "v", false, "print the names of packages as they are compiled")
buildFlags.BoolVar(&options.Watch, "w", false, "watch for changes to the source files")
buildFlags.BoolVar(&options.Minify, "m", false, "minify generated code")
buildFlags.Parse(cmdArgs)
for {
s := gbuild.NewSession(options)
exitCode := handleError(func() error {
if buildFlags.NArg() == 0 {
return s.BuildDir(currentDirectory, currentDirectory, pkgObj)
}
if strings.HasSuffix(buildFlags.Arg(0), ".go") {
for _, arg := range buildFlags.Args() {
if !strings.HasSuffix(arg, ".go") {
return fmt.Errorf("named files must be .go files")
}
}
if pkgObj == "" {
basename := filepath.Base(buildFlags.Arg(0))
pkgObj = basename[:len(basename)-3] + ".js"
}
names := make([]string, buildFlags.NArg())
for i, name := range buildFlags.Args() {
name = filepath.ToSlash(name)
names[i] = name
if s.Watcher != nil {
s.Watcher.Watch(filepath.ToSlash(name))
}
}
if err := s.BuildFiles(buildFlags.Args(), pkgObj, currentDirectory); err != nil {
return err
}
return nil
}
for _, pkgPath := range buildFlags.Args() {
pkgPath = filepath.ToSlash(pkgPath)
if s.Watcher != nil {
s.Watcher.Watch(pkgPath)
}
buildPkg, err := gbuild.Import(pkgPath, 0, s.ArchSuffix())
if err != nil {
return err
}
pkg := &gbuild.PackageData{Package: buildPkg}
if err := s.BuildPackage(pkg); err != nil {
return err
}
if pkgObj == "" {
pkgObj = filepath.Base(buildFlags.Arg(0)) + ".js"
}
if err := s.WriteCommandPackage(pkg, pkgObj); err != nil {
return err
}
}
return nil
})
if s.Watcher == nil {
os.Exit(exitCode)
}
s.WaitForChange()
}
case "install":
installFlags := flag.NewFlagSet("install command", flag.ExitOnError)
installFlags.BoolVar(&options.Verbose, "v", false, "print the names of packages as they are compiled")
installFlags.BoolVar(&options.Watch, "w", false, "watch for changes to the source files")
installFlags.BoolVar(&options.Minify, "m", false, "minify generated code")
installFlags.Parse(cmdArgs)
for {
s := gbuild.NewSession(options)
exitCode := handleError(func() error {
pkgs := installFlags.Args()
if len(pkgs) == 0 {
firstGopathWorkspace := filepath.SplitList(build.Default.GOPATH)[0] // TODO: The GOPATH workspace that contains the package source should be chosen.
srcDir, err := filepath.EvalSymlinks(filepath.Join(firstGopathWorkspace, "src"))
//.........这里部分代码省略.........
示例8: main
func main() {
flags := flag.NewFlagSet("", flag.ContinueOnError)
cmd := "help"
var cmdArgs []string
if err := flags.Parse(os.Args[1:]); err == nil && flags.NArg() != 0 {
cmd = flags.Arg(0)
cmdArgs = flags.Args()[1:]
if cmd == "help" && flags.NArg() == 2 {
cmd = flags.Arg(1)
cmdArgs = []string{"--help"}
}
}
options := &gbuild.Options{CreateMapFile: true}
switch cmd {
case "build":
buildFlags := flag.NewFlagSet("build command", flag.ExitOnError)
var pkgObj string
buildFlags.StringVar(&pkgObj, "o", "", "output file")
buildFlags.BoolVar(&options.Verbose, "v", false, "print the names of packages as they are compiled")
buildFlags.BoolVar(&options.Watch, "w", false, "watch for changes to the source files")
buildFlags.BoolVar(&options.Minify, "m", false, "minify generated code")
buildFlags.Parse(cmdArgs)
for {
s := gbuild.NewSession(options)
exitCode := handleError(func() error {
if buildFlags.NArg() == 0 {
return s.BuildDir(currentDirectory, currentDirectory, pkgObj)
}
if strings.HasSuffix(buildFlags.Arg(0), ".go") {
for _, arg := range buildFlags.Args() {
if !strings.HasSuffix(arg, ".go") {
return fmt.Errorf("named files must be .go files")
}
}
if pkgObj == "" {
basename := filepath.Base(buildFlags.Arg(0))
pkgObj = basename[:len(basename)-3] + ".js"
}
names := make([]string, buildFlags.NArg())
for i, name := range buildFlags.Args() {
name = filepath.ToSlash(name)
names[i] = name
if s.Watcher != nil {
s.Watcher.Watch(filepath.ToSlash(name))
}
}
if err := s.BuildFiles(buildFlags.Args(), pkgObj, currentDirectory); err != nil {
return err
}
return nil
}
for _, pkgPath := range buildFlags.Args() {
pkgPath = filepath.ToSlash(pkgPath)
if s.Watcher != nil {
s.Watcher.Watch(pkgPath)
}
buildPkg, err := gbuild.Import(pkgPath, 0, s.ArchSuffix())
if err != nil {
return err
}
pkg := &gbuild.PackageData{Package: buildPkg}
if err := s.BuildPackage(pkg); err != nil {
return err
}
if pkgObj == "" {
pkgObj = filepath.Base(buildFlags.Arg(0)) + ".js"
}
if err := s.WriteCommandPackage(pkg, pkgObj); err != nil {
return err
}
}
return nil
})
if s.Watcher == nil {
os.Exit(exitCode)
}
s.WaitForChange()
}
case "install":
installFlags := flag.NewFlagSet("install command", flag.ExitOnError)
installFlags.BoolVar(&options.Verbose, "v", false, "print the names of packages as they are compiled")
installFlags.BoolVar(&options.Watch, "w", false, "watch for changes to the source files")
installFlags.BoolVar(&options.Minify, "m", false, "minify generated code")
installFlags.Parse(cmdArgs)
for {
s := gbuild.NewSession(options)
exitCode := handleError(func() error {
pkgs := installFlags.Args()
if len(pkgs) == 0 {
srcDir, err := filepath.EvalSymlinks(filepath.Join(build.Default.GOPATH, "src"))
if err != nil {
//.........这里部分代码省略.........
示例9: main
func main() {
options := &gbuild.Options{CreateMapFile: true}
var pkgObj string
pflag.BoolVarP(&options.Verbose, "verbose", "v", false, "print the names of packages as they are compiled")
flagVerbose := pflag.Lookup("verbose")
pflag.BoolVarP(&options.Watch, "watch", "w", false, "watch for changes to the source files")
flagWatch := pflag.Lookup("watch")
pflag.BoolVarP(&options.Minify, "minify", "m", false, "minify generated code")
flagMinify := pflag.Lookup("minify")
pflag.BoolVar(&options.Color, "color", terminal.IsTerminal(int(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb", "colored output")
flagColor := pflag.Lookup("color")
tags := pflag.String("tags", "", "a list of build tags to consider satisfied during the build")
flagTags := pflag.Lookup("tags")
cmdBuild := &cobra.Command{
Use: "build [packages]",
Short: "compile packages and dependencies",
}
cmdBuild.Flags().StringVarP(&pkgObj, "output", "o", "", "output file")
cmdBuild.Flags().AddFlag(flagVerbose)
cmdBuild.Flags().AddFlag(flagWatch)
cmdBuild.Flags().AddFlag(flagMinify)
cmdBuild.Flags().AddFlag(flagColor)
cmdBuild.Flags().AddFlag(flagTags)
cmdBuild.Run = func(cmd *cobra.Command, args []string) {
options.BuildTags = strings.Fields(*tags)
for {
s := gbuild.NewSession(options)
exitCode := handleError(func() error {
if len(args) == 0 {
return s.BuildDir(currentDirectory, currentDirectory, pkgObj)
}
if strings.HasSuffix(args[0], ".go") || strings.HasSuffix(args[0], ".inc.js") {
for _, arg := range args {
if !strings.HasSuffix(arg, ".go") && !strings.HasSuffix(arg, ".inc.js") {
return fmt.Errorf("named files must be .go or .inc.js files")
}
}
if pkgObj == "" {
basename := filepath.Base(args[0])
pkgObj = basename[:len(basename)-3] + ".js"
}
names := make([]string, len(args))
for i, name := range args {
name = filepath.ToSlash(name)
names[i] = name
if s.Watcher != nil {
s.Watcher.Add(name)
}
}
if err := s.BuildFiles(args, pkgObj, currentDirectory); err != nil {
return err
}
return nil
}
for _, pkgPath := range args {
pkgPath = filepath.ToSlash(pkgPath)
if s.Watcher != nil {
s.Watcher.Add(pkgPath)
}
buildPkg, err := gbuild.Import(pkgPath, 0, s.InstallSuffix(), options.BuildTags)
if err != nil {
return err
}
pkg := &gbuild.PackageData{Package: buildPkg}
if err := s.BuildPackage(pkg); err != nil {
return err
}
if pkgObj == "" {
pkgObj = filepath.Base(args[0]) + ".js"
}
if err := s.WriteCommandPackage(pkg, pkgObj); err != nil {
return err
}
}
return nil
}, options, nil)
if s.Watcher == nil {
os.Exit(exitCode)
}
s.WaitForChange()
}
}
cmdInstall := &cobra.Command{
Use: "install [packages]",
Short: "compile and install packages and dependencies",
}
cmdInstall.Flags().AddFlag(flagVerbose)
cmdInstall.Flags().AddFlag(flagWatch)
cmdInstall.Flags().AddFlag(flagMinify)
cmdInstall.Flags().AddFlag(flagColor)
cmdInstall.Flags().AddFlag(flagTags)
cmdInstall.Run = func(cmd *cobra.Command, args []string) {
options.BuildTags = strings.Fields(*tags)
//.........这里部分代码省略.........
示例10: 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
}