Skip to content

Commit

Permalink
import source code
Browse files Browse the repository at this point in the history
  • Loading branch information
fzipp committed Sep 15, 2013
1 parent 3e6ed8c commit f5ae28d
Show file tree
Hide file tree
Showing 13 changed files with 1,440 additions and 0 deletions.
27 changes: 27 additions & 0 deletions LICENSE
@@ -0,0 +1,27 @@
Copyright (c) 2013 Frederik Zipp. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright owner nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
109 changes: 109 additions & 0 deletions main.go
@@ -0,0 +1,109 @@
// Copyright 2013 Frederik Zipp. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
"code.google.com/p/go.tools/importer"
"flag"
"fmt"
"github.com/fzipp/pythia/static"
"go/build"
"go/token"
"html/template"
"log"
"net/http"
"os"
"runtime"
"sort"
"strings"
)

var (
httpAddr = flag.String("http", ":8080", "HTTP listen address")
verbose = flag.Bool("v", false, "Verbose mode: print incoming queries")
args []string
files []string
listView *template.Template
sourceView *template.Template
)

func init() {
if os.Getenv("GOMAXPROCS") == "" {
n := runtime.NumCPU()
if n < 4 {
n = 4
}
runtime.GOMAXPROCS(n)
}
initTemplates()
}

func initTemplates() {
listView = template.Must(template.New("").Parse(static.Files["list.html"]))
sourceView = template.New("").Funcs(template.FuncMap{
"seq": seq,
})
template.Must(sourceView.Parse(static.Files["source.html"]))
}

const usage = `Web frontend for Go source code oracle.
Usage: pythia [<flag> ...] <args> ...
Use -help flag to display options.
` + importer.InitialPackagesUsage

func main() {
flag.Parse()
args = flag.Args()
if len(args) == 0 {
fmt.Fprint(os.Stderr, usage)
os.Exit(1)
}

var err error
files, err = scopeFiles(args)
if err != nil {
log.Fatal(err)
}

http.HandleFunc("/", serveList)
http.HandleFunc("/source", serveSource)
http.HandleFunc("/query", serveQuery)
staticPrefix := "/static/"
http.Handle(staticPrefix, http.StripPrefix(staticPrefix, http.HandlerFunc(serveStatic)))

fmt.Printf("http://localhost%s/\n", *httpAddr)
log.Fatal(http.ListenAndServe(*httpAddr, nil))
}

func seq(from, to int) <-chan int {
ch := make(chan int)
go func() {
for i := from; i <= to; i++ {
ch <- i
}
close(ch)
}()
return ch
}

func scopeFiles(args []string) ([]string, error) {
files := make([]string, 0)
imp := importer.New(&importer.Config{Build: &build.Default})
_, _, err := imp.LoadInitialPackages(args)
if err != nil {
return files, err
}
imp.Fset.Iterate(func(f *token.File) bool {
files = append(files, f.Name())
return true
})
sort.Strings(files)
return files, nil
}

func cmdLine(mode, pos, format string) string {
return fmt.Sprintf("oracle -mode=%s -pos=%s -format=%s %s",
mode, pos, format, strings.Join(args, " "))
}
95 changes: 95 additions & 0 deletions serve.go
@@ -0,0 +1,95 @@
// Copyright 2013 Frederik Zipp. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
"bytes"
"code.google.com/p/go.tools/oracle"
"encoding/json"
"github.com/fzipp/pythia/static"
"go/build"
"io"
"io/ioutil"
"log"
"net/http"
"sort"
"strings"
"time"
)

func serveList(w http.ResponseWriter, req *http.Request) {
listView.Execute(w, struct {
Scope string
Files []string
}{
Scope: strings.Join(args, " "),
Files: files,
})
}

type source struct {
FileName string
Code []byte
NLines int
}

func serveSource(w http.ResponseWriter, req *http.Request) {
fileName := req.FormValue("file")
i := sort.SearchStrings(files, fileName)
if i >= len(files) || files[i] != fileName {
http.Error(w, "Forbidden", 403)
return
}
code, err := ioutil.ReadFile(fileName)
if err != nil {
log.Println(req.RemoteAddr, err)
http.NotFound(w, req)
return
}
src := source{
FileName: fileName,
Code: code,
NLines: bytes.Count(code, []byte{'\n'}),
}
sourceView.Execute(w, src)
}

func serveQuery(w http.ResponseWriter, req *http.Request) {
mode := req.FormValue("mode")
pos := req.FormValue("pos")
format := req.FormValue("format")
if *verbose {
log.Println(req.RemoteAddr, cmdLine(mode, pos, format))
}
res, err := oracle.Query(args, mode, pos, nil, &build.Default)
if err != nil {
io.WriteString(w, err.Error())
return
}
writeResult(w, res, format)
}

func writeResult(w io.Writer, res *oracle.Result, format string) {
if format == "json" {
b, err := json.Marshal(res)
if err != nil {
io.WriteString(w, err.Error())
return
}
w.Write(b)
return
}
res.WriteTo(w)
}

func serveStatic(w http.ResponseWriter, req *http.Request) {
name := req.URL.Path
data, ok := static.Files[name]
if !ok {
http.NotFound(w, req)
return
}
http.ServeContent(w, req, name, time.Time{}, strings.NewReader(data))
}
88 changes: 88 additions & 0 deletions static/bake.go
@@ -0,0 +1,88 @@
// Copyright (c) 2013 The Go Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// +build ignore

// Command bake takes a list of file names and writes a Go source file to
// standard output that declares a map of string constants containing the input files.
//
// For example, the command
// bake foo.html bar.txt
// produces a source file in package main that declares the variable bakedFiles
// that is a map with keys "foo.html" and "bar.txt" that contain the contents
// of foo.html and bar.txt.
package main

import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"unicode/utf8"
)

func main() {
if err := bake(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

func bake(files []string) error {
w := bufio.NewWriter(os.Stdout)
fmt.Fprintf(w, "%v\n\npackage static\n\n", warning)
fmt.Fprintf(w, "var Files = map[string]string{\n")
for _, fn := range files {
b, err := ioutil.ReadFile(fn)
if err != nil {
return err
}
if !utf8.Valid(b) {
return fmt.Errorf("file %s is not valid UTF-8", fn)
}
fmt.Fprintf(w, "\t%q: `%s`,\n", filepath.Base(fn), sanitize(b))
}
fmt.Fprintln(w, "}")
return w.Flush()
}

// sanitize prepares a string as a raw string constant.
func sanitize(b []byte) []byte {
// Replace ` with `+"`"+`
b = bytes.Replace(b, []byte("`"), []byte("`+\"`\"+`"), -1)

// Replace BOM with `+"\xEF\xBB\xBF"+`
// (A BOM is valid UTF-8 but not permitted in Go source files.
// I wouldn't bother handling this, but for some insane reason
// jquery.js has a BOM somewhere in the middle.)
return bytes.Replace(b, []byte("\xEF\xBB\xBF"), []byte("`+\"\\xEF\\xBB\\xBF\"+`"), -1)
}

const warning = "// DO NOT EDIT ** This file was generated with the bake tool ** DO NOT EDIT //"
42 changes: 42 additions & 0 deletions static/bake.sh
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Copyright (c) 2013 The Go Authors. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

set -e

STATIC="
list.html
source.html
style.css
oracle.js
jquery.min.js
jquery-ui.min.js
jquery-layout.min.js
"

go run bake.go $STATIC | gofmt > static.go

0 comments on commit f5ae28d

Please sign in to comment.