Exemple #1
0
func toBasicLitString(n ast.Node) *ast.BasicLit {
	switch node := n.(type) {
	case *ast.BasicLit:
		if node.Kind == token.STRING {
			return node
		}
	case *ast.BinaryExpr:
		if node.Op != token.ADD {
			return nil
		}
		X := toBasicLitString(node.X)
		Y := toBasicLitString(node.Y)
		if X == nil || Y == nil {
			return nil
		}
		x, _ := strconv.Unquote(X.Value)
		y, _ := strconv.Unquote(Y.Value)
		return &ast.BasicLit{
			ValuePos: node.Pos(),
			Kind:     token.STRING,
			Value:    strconv.Quote(x + y),
		}
	case *ast.ParenExpr:
		x := toBasicLitString(node.X)
		if x == nil {
			return nil
		}
		x.ValuePos = node.Pos()
		return x
	}
	return nil
}
Exemple #2
0
func main() {
	var mode string
	flag.StringVar(&mode, "mode", "", "package_imports|package_imports_tests")
	flag.Parse()
	switch mode {
	case "package_imports":
		for fileNode := range parseArgs() {
			fmt.Printf("package %s\n", fileNode.Name.Name)
			for spec := range extractImports(fileNode) {
				importPath, _ := strconv.Unquote(string(spec.Path.Value))
				fmt.Printf("import %s\n", importPath)
			}
		}
	case "package_imports_tests":
		for fileNode := range parseArgs() {
			fmt.Printf("package %s\n", fileNode.Name.Name)
			for spec := range extractImports(fileNode) {
				importPath, _ := strconv.Unquote(string(spec.Path.Value))
				fmt.Printf("import %s\n", importPath)
			}
			for decl := range extractTests(fileNode) {
				fmt.Printf("%s.%s\n", fileNode.Name.Name, decl.Name.Name)
			}
		}
	default:
		flag.Usage()
		os.Exit(1)
	}
}
Exemple #3
0
// parseDefinition parses a {{define}} ... {{end}} template definition and
// returns a defineNode. The "define" keyword has already been scanned.
//
//	{{define stringValue}} itemList {{end}}
//	{{define stringValue stringValue}} itemList {{end}}
func (p *parser) parseDefinition(pos Pos) *DefineNode {
	const context = "define clause"
	defer p.popVars(1)
	line := p.lex.lineNumber()
	var name, parent string
	token := p.nextNonSpace()
	switch token.typ {
	case itemString, itemRawString:
		s, err := strconv.Unquote(token.val)
		if err != nil {
			p.error(err)
		}
		name = s
	default:
		p.unexpected(token, context)
	}
	token = p.nextNonSpace()
	switch token.typ {
	case itemString, itemRawString:
		s, err := strconv.Unquote(token.val)
		if err != nil {
			p.error(err)
		}
		parent = s
		p.expect(itemRightDelim, context)
	case itemRightDelim:
	default:
		p.unexpected(token, context)
	}
	list, end := p.itemList()
	if end.Type() != nodeEnd {
		p.errorf("unexpected %s in %s", end, context)
	}
	return newDefine(pos, line, name, parent, list, p.text)
}
Exemple #4
0
func (bnd *bndBool) bind(value bool, position int, c StmtCfg, stmt *Stmt) (err error) {
	//Log.Infof("%s.bind(%t, %d)", bnd, value, position)
	bnd.stmt = stmt
	var str string
	if value {
		str, err = strconv.Unquote(strconv.QuoteRune(c.TrueRune))
	} else {
		str, err = strconv.Unquote(strconv.QuoteRune(c.FalseRune))
	}
	if err != nil {
		return err
	}
	bnd.cString = C.CString(str)
	r := C.OCIBINDBYPOS(
		bnd.stmt.ocistmt,            //OCIStmt      *stmtp,
		(**C.OCIBind)(&bnd.ocibnd),  //OCIBind      **bindpp,
		bnd.stmt.ses.srv.env.ocierr, //OCIError     *errhp,
		C.ub4(position),             //ub4          position,
		unsafe.Pointer(bnd.cString), //void         *valuep,
		C.LENGTH_TYPE(1),            //sb8          value_sz,
		C.SQLT_AFC,                  //ub2          dty,
		nil,                         //void         *indp,
		nil,                         //ub2          *alenp,
		nil,                         //ub2          *rcodep,
		0,                           //ub4          maxarr_len,
		nil,                         //ub4          *curelep,
		C.OCI_DEFAULT)               //ub4          mode );
	if r == C.OCI_ERROR {
		return bnd.stmt.ses.srv.env.ociError()
	}
	return nil
}
Exemple #5
0
func init() {
	flag.StringVar(&driver, "driver", "", "Sets the driver")
	flag.StringVar(&source, "source", "", "Sets the source")
	flag.StringVar(&schemaPath, "schema", "db/schema.go", "Sets the schema path")
	flag.IntVar(&steps, "steps", 0, "Sets the steps")
	flag.Parse()

	if driver == "" {
		panic("driver not set")
	}
	if source == "" {
		panic("source not set")
	}

	// Unquote
	d, err := strconv.Unquote(driver)
	if err != nil {
		panic(err)
	}
	driver = d

	s, err := strconv.Unquote(source)
	if err != nil {
		panic(err)
	}
	source = s

	sp, err := strconv.Unquote(schemaPath)
	if err != nil {
		panic(err)
	}
	schemaPath = sp
}
func TestKubeVersion(t *testing.T) {
	Convey("Subject: Version Checking", t, func() {
		kversion, err := exec.Command("kubectl", "version").Output()
		Convey("kubectl version returns no error", func() {
			So(err, ShouldBeNil)
		})
		versions := bytes.Split(kversion, []byte("\n"))
		cver := string(versions[0])
		cver = cver[strings.IndexRune(cver, '{')+1:]
		cver = strings.TrimRight(cver, "}")
		sver := string(versions[1])
		sver = sver[strings.IndexRune(sver, '{')+1:]
		sver = strings.TrimRight(sver, "}")
		Convey("Subject: Client and Server version should be equal", func() {
			So(cver, ShouldEqual, sver)
		})
		kver := strings.Split(cver, ",")
		vmap := make(map[string]string)
		for _, item := range kver {
			entry := strings.Split(strings.TrimSpace(item), ":")
			vmap[entry[0]] = entry[1]
		}

		rversion, err := exec.Command("rpm", "-q", "kubernetes").Output()
		Convey("rpm -q kubernetes returns no error", func() {
			So(err, ShouldBeNil)
		})
		srver := string(rversion)
		rgit := strings.Split(srver, "-")[1]
		rver := strings.FieldsFunc(srver, func(r rune) bool {
			return r == '-' || r == '.'
		})
		rmajor := rver[1]
		rminor := rver[2]
		rcommit := rver[7][3:]
		vmajor, err := strconv.Unquote(vmap["Major"])
		Convey("unquote major return no error", func() {
			So(err, ShouldBeNil)
		})
		Convey("version major should match", func() {
			So(vmajor, ShouldEqual, rmajor)
		})
		vminor, err := strconv.Unquote(vmap["Minor"])
		Convey("unquote minor return no error", func() {
			So(err, ShouldBeNil)
		})
		Convey("version minor should match", func() {
			So(vminor, ShouldEqual, rminor)
		})
		Convey("rpm git version should be within kubectl git version", func() {
			So(vmap["GitVersion"], ShouldContainSubstring, rgit)
		})
		Convey("rpm git commit should be within kubectl git commit", func() {
			So(vmap["GitCommit"], ShouldContainSubstring, rcommit)
		})
	})
}
Exemple #7
0
func NewSubStringExpr(a, b Attrib) (*SubStringExpr, error) {
	astr, err := strconv.Unquote(string(a.(*token.Token).Lit))
	if err != nil {
		return nil, err
	}
	bstr, err := strconv.Unquote(string(b.(*token.Token).Lit))
	if err != nil {
		return nil, err
	}
	return &SubStringExpr{astr, bstr}, nil
}
Exemple #8
0
func (cmd *ntuple_create) Run() gribble.Value {
	id := cmd.Id
	title, err := strconv.Unquote(cmd.Title)
	if err != nil {
		return err
	}
	//nvars := cmd.Nvars.(int)
	vars, err := strconv.Unquote(cmd.Vars)
	ntvars := strings.Split(vars, ",")
	return cmd.mgr.Create(id, title, ntvars)
}
Exemple #9
0
// checkCanonicalFieldTag checks a single struct field tag.
func checkCanonicalFieldTag(f *File, field *ast.Field, seen *map[[2]string]token.Pos) {
	if field.Tag == nil {
		return
	}

	tag, err := strconv.Unquote(field.Tag.Value)
	if err != nil {
		f.Badf(field.Pos(), "unable to read struct tag %s", field.Tag.Value)
		return
	}

	if err := validateStructTag(tag); err != nil {
		raw, _ := strconv.Unquote(field.Tag.Value) // field.Tag.Value is known to be a quoted string
		f.Badf(field.Pos(), "struct field tag %#q not compatible with reflect.StructTag.Get: %s", raw, err)
	}

	for _, key := range checkTagDups {
		val := reflect.StructTag(tag).Get(key)
		if val == "" || val == "-" || val[0] == ',' {
			continue
		}
		if i := strings.Index(val, ","); i >= 0 {
			val = val[:i]
		}
		if *seen == nil {
			*seen = map[[2]string]token.Pos{}
		}
		if pos, ok := (*seen)[[2]string{key, val}]; ok {
			f.Badf(field.Pos(), "struct field %s repeats %s tag %q also at %s", field.Names[0].Name, key, val, f.loc(pos))
		} else {
			(*seen)[[2]string{key, val}] = field.Pos()
		}
	}

	// Check for use of json or xml tags with unexported fields.

	// Embedded struct. Nothing to do for now, but that
	// may change, depending on what happens with issue 7363.
	if len(field.Names) == 0 {
		return
	}

	if field.Names[0].IsExported() {
		return
	}

	for _, enc := range [...]string{"json", "xml"} {
		if reflect.StructTag(tag).Get(enc) != "" {
			f.Badf(field.Pos(), "struct field %s has %s tag but is not exported", field.Names[0].Name, enc)
			return
		}
	}
}
Exemple #10
0
func resolveExtension(extension string) (resolved string) {
	resp, err := http.Get(caddyRegistry)
	if err != nil {
		return
	}

	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)

	f, err := parser.ParseFile(token.NewFileSet(), "", data, 0)
	node, ok := f.Scope.Lookup("Registry").Decl.(ast.Node)
	if !ok {
		return
	}

	c := node.(*ast.ValueSpec).Values[0].(*ast.CompositeLit)
	for _, m := range c.Elts {
		var directive *ast.BasicLit
		var directiveRepo *ast.BasicLit
		token := m.(*ast.CompositeLit).Elts

		if v, ok := token[0].(*ast.BasicLit); ok {
			directive = v
		} else {
			return
		}

		name, err := strconv.Unquote(directive.Value)
		if err != nil {
			return
		}

		if v, ok := token[1].(*ast.BasicLit); ok {
			directiveRepo = v
		} else {
			return
		}

		repo, err := strconv.Unquote(directiveRepo.Value)
		if err != nil {
			return
		}

		if name == extension {
			if len(repo) > 0 {
				resolved = repo
			}
			return
		}
	}

	return
}
Exemple #11
0
func (p *noder) basicLit(lit *syntax.BasicLit) Val {
	// TODO: Don't try to convert if we had syntax errors (conversions may fail).
	//       Use dummy values so we can continue to compile. Eventually, use a
	//       form of "unknown" literals that are ignored during type-checking so
	//       we can continue type-checking w/o spurious follow-up errors.
	switch s := lit.Value; lit.Kind {
	case syntax.IntLit:
		x := new(Mpint)
		x.SetString(s)
		return Val{U: x}

	case syntax.FloatLit:
		x := newMpflt()
		x.SetString(s)
		return Val{U: x}

	case syntax.ImagLit:
		x := new(Mpcplx)
		x.Imag.SetString(strings.TrimSuffix(s, "i"))
		return Val{U: x}

	case syntax.RuneLit:
		var r rune
		if u, err := strconv.Unquote(s); err == nil && len(u) > 0 {
			// Package syntax already reported any errors.
			// Check for them again though because 0 is a
			// better fallback value for invalid rune
			// literals than 0xFFFD.
			if len(u) == 1 {
				r = rune(u[0])
			} else {
				r, _ = utf8.DecodeRuneInString(u)
			}
		}
		x := new(Mpint)
		x.SetInt64(int64(r))
		x.Rune = true
		return Val{U: x}

	case syntax.StringLit:
		if len(s) > 0 && s[0] == '`' {
			// strip carriage returns from raw string
			s = strings.Replace(s, "\r", "", -1)
		}
		// Ignore errors because package syntax already reported them.
		u, _ := strconv.Unquote(s)
		return Val{U: u}

	default:
		panic("unhandled BasicLit kind")
	}
}
Exemple #12
0
func main() {
	interval, _ := strconv.ParseInt(os.Getenv("LABELGUN_INTERVAL"), 10, 64)
	kube_master = os.Getenv("KUBE_MASTER")
	for {
		// Get Kube Node name
		n, _ := sh.Command("kubectl", "-s", kube_master, "describe", "pod", os.Getenv("HOSTNAME")).Command("grep", "Node").Command("awk", "{print $2}").Command("sed", "s@/.*@@").Output()
		node = string(n)
		node = strings.TrimSpace(node)
		fmt.Println(node)

		// Get instance id
		instance_id, _ := sh.Command("curl", "-s", "http://169.254.169.254/latest/meta-data/instance-id").Output()
		fmt.Println(string(instance_id))

		// Get AWS instance metadata
		params := &ec2.DescribeInstancesInput{
			InstanceIds: []*string{
				aws.String(string(instance_id)),
			},
		}
		resp, err := svc.DescribeInstances(params)

		if err != nil {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
			return
		}

		// Pretty-print the response data.
		//fmt.Println(resp.Reservations[0].Instances[0].InstanceType)
		meta = resp.Reservations[0].Instances[0]

		// Apply Availability Zone
		availabilityZone, _ := strconv.Unquote(string(awsutil.Prettify(meta.Placement.AvailabilityZone)))
		label("AvailabilityZone=" + availabilityZone)

		// Apply Instance Type
		instanceType, _ := strconv.Unquote(string(awsutil.Prettify(meta.InstanceType)))
		label("InstanceType=" + instanceType)

		// Apply EC2 Tags
		tags := meta.Tags
		for _, tag := range tags {
			label(*tag.Key + "=" + *tag.Value)
		}
		// Sleep until interval
		fmt.Println("Sleeping for " + os.Getenv("LABELGUN_INTERVAL") + " seconds")
		time.Sleep(time.Duration(interval) * time.Second)
	}

}
Exemple #13
0
// FindEnv returns map of environment variables.
// Key of map is key of environment variable, Value of map is value of
// environment variable.
func FindEnv(basedir string) (map[string]string, error) {
	if basedir == "" {
		pwd, err := os.Getwd()
		if err != nil {
			return nil, err
		}
		basedir = pwd
	}
	env := make(map[string]string)
	if err := filepath.Walk(basedir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		switch info.Name()[0] {
		case '.', '_':
			if info.IsDir() {
				return filepath.SkipDir
			}
			return nil
		}
		if info.IsDir() {
			return nil
		}
		if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
			return nil
		}
		body, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		matches := settingEnvRegexp.FindAllStringSubmatch(string(body), -1)
		if matches == nil {
			return nil
		}
		for _, m := range matches {
			key, err := strconv.Unquote(m[1])
			if err != nil {
				continue
			}
			value, err := strconv.Unquote(m[2])
			if err != nil {
				value = "WILL BE SET IN RUNTIME"
			}
			env[key] = value
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return env, nil
}
Exemple #14
0
func (this *Parser) ParseAlterStatement(alterStatement string) (err error) {
	allStringSubmatch := renameColumnRegexp.FindAllStringSubmatch(alterStatement, -1)
	for _, submatch := range allStringSubmatch {
		if unquoted, err := strconv.Unquote(submatch[2]); err == nil {
			submatch[2] = unquoted
		}
		if unquoted, err := strconv.Unquote(submatch[3]); err == nil {
			submatch[3] = unquoted
		}

		this.columnRenameMap[submatch[2]] = submatch[3]
	}
	return nil
}
Exemple #15
0
func (c *Connection) parseFieldOptions(tag reflect.StructTag) map[string]interface{} {
	options := make(map[string]interface{})
	optionString := string(tag)

	for optionString != "" {
		// following code is adapted from the golang reflect package
		i := 0
		for i < len(optionString) && optionString[i] == ' ' {
			i++
		}
		optionString = optionString[i:]
		if optionString == "" {
			break
		}

		// scan to colon.
		// a space or a quote is a syntax error
		i = 0
		for i < len(optionString) && optionString[i] != ' ' && optionString[i] != ':' && optionString[i] != '"' {
			i++
		}
		if i+1 >= len(optionString) || optionString[i] != ':' || optionString[i+1] != '"' {
			break
		}
		name := string(optionString[:i])
		optionString = optionString[i+1:]

		// scan quoted string to find value
		i = 1
		for i < len(optionString) && optionString[i] != '"' {
			if optionString[i] == '\\' {
				i++
			}
			i++
		}
		if i >= len(optionString) {
			break
		}
		qvalue := string(optionString[:i+1])
		optionString = optionString[i+1:]

		if name[:2] == "ar" {
			options[name[2:]], _ = strconv.Unquote(qvalue)
		} else {
			options[name[2:]], _ = strconv.Unquote(qvalue)
		}
	}

	return options
}
Exemple #16
0
// Field = Name Type [ string_lit ] .
//
func (p *parser) parseField(parent *types.Package) (*types.Var, string) {
	pkg, name := p.parseName(parent, true)
	typ := p.parseType(parent)
	anonymous := false
	if name == "" {
		// anonymous field - typ must be T or *T and T must be a type name
		switch typ := deref(typ).(type) {
		case *types.Basic: // basic types are named types
			pkg = nil // objects defined in Universe scope have no package
			name = typ.Name()
		case *types.Named:
			name = typ.Obj().Name()
		default:
			p.errorf("anonymous field expected")
		}
		anonymous = true
	}
	tag := ""
	if p.tok == scanner.String {
		s := p.expect(scanner.String)
		var err error
		tag, err = strconv.Unquote(s)
		if err != nil {
			p.errorf("invalid struct tag %s: %s", s, err)
		}
	}
	return types.NewField(token.NoPos, pkg, name, typ, anonymous), tag
}
Exemple #17
0
// RewriteImports rewrites imports in the passed AST (in-place).
// It returns bool changed set to true if any changes were made
// and non-nil err on error
func RewriteImports(f *ast.File, prefix string, remove bool) (changed bool, err error) {
	for _, impNode := range f.Imports {
		imp, err := strconv.Unquote(impNode.Path.Value)
		if err != nil {
			log.Printf("Error unquoting import value %v - %s\n", impNode.Path.Value, err)
			return false, err
		}
		// skip standard library imports and relative references
		if !strings.Contains(imp, ".") || strings.HasPrefix(imp, ".") {
			continue
		}
		if remove {
			if strings.HasPrefix(imp, prefix) {
				changed = true
				impNode.Path.Value = strconv.Quote(imp[len(prefix):])
			}
		} else {
			// if import does not start with the prefix already, add it
			if !strings.HasPrefix(imp, prefix) {
				changed = true
				impNode.Path.Value = strconv.Quote(prefix + imp)
			}
		}
	}
	return
}
Exemple #18
0
func TestParfind(t *testing.T) {
	createTestingDirectory()
	for _, params := range TestParams {
		out, err := runParfind(params.version, params.workers, params.root, params.print0, t)
		if params.root == TestingDirectory && err != "" {
			t.Fatalf("Unexpected output on stderr")
		}
		f := FmtDefault
		if params.print0 {
			f = FmtPrint0
		}
		res := f.FindAllStringSubmatch(out, -1)
		if params.root == TestingDirectory && len(res) != RequiredResults {
			t.Fatalf("Expected %d results, got %d", RequiredResults, len(res))
		}
		for _, v := range res {
			f := v[1]
			if params.print0 == false {
				f, _ = strconv.Unquote(f)
			}
			if _, e := os.Stat(f); e != nil {
				t.Errorf("Can't stat result %s", f)
			}
		}
	}
}
Exemple #19
0
func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) {
	var buffer bytes.Buffer

	logger := New()
	logger.Out = &buffer
	logger.Formatter = &TextFormatter{
		DisableColors: true,
	}

	log(logger)

	fields := make(map[string]string)
	for _, kv := range strings.Split(buffer.String(), " ") {
		if !strings.Contains(kv, "=") {
			continue
		}
		kvArr := strings.Split(kv, "=")
		key := strings.TrimSpace(kvArr[0])
		val := kvArr[1]
		if kvArr[1][0] == '"' {
			var err error
			val, err = strconv.Unquote(val)
			assert.NoError(t, err)
		}
		fields[key] = val
	}
	assertions(fields)
}
Exemple #20
0
func (p *Parser) atos(str string) string {
	value, err := strconv.Unquote(str)
	if err != nil {
		p.errorf("%s", err)
	}
	return value
}
Exemple #21
0
// factor = const | '+' factor | '-' factor | '~' factor | '(' expr ')'
func (p *Parser) factor() uint64 {
	tok := p.next()
	switch tok.ScanToken {
	case scanner.Int:
		return p.atoi(tok.String())
	case scanner.Char:
		str, err := strconv.Unquote(tok.String())
		if err != nil {
			p.errorf("%s", err)
		}
		r, w := utf8.DecodeRuneInString(str)
		if w == 1 && r == utf8.RuneError {
			p.errorf("illegal UTF-8 encoding for character constant")
		}
		return uint64(r)
	case '+':
		return +p.factor()
	case '-':
		return -p.factor()
	case '~':
		return ^p.factor()
	case '(':
		v := p.expr()
		if p.next().ScanToken != ')' {
			p.errorf("missing closing paren")
		}
		return v
	}
	p.errorf("unexpected %s evaluating expression", tok)
	return 0
}
Exemple #22
0
func Transform(src *ast.File) *ast.File {
	// find the golex import...
	var toplevel ToplevelVisitor

	for _, spec := range src.Imports {
		ast.Print(nil, spec)
		if conv, err := strconv.Unquote(spec.Path.Value); err != nil || conv != "golex" {
			continue
		}
		if spec.Name != nil {
			toplevel.golexPackage = spec.Name.Name
		} else {
			toplevel.golexPackage = "golex"
		}
		break
	}
	if toplevel.golexPackage == "" {
		log.Print("Not a lex input")

		return src
	}

	ast.Walk(&toplevel, src)
	// Now, find switch statemnts...
	return src
}
Exemple #23
0
// unquote returns the unquoted string.
func unquote(s string) string {
	t, err := strconv.Unquote(s)
	if err != nil {
		log.Fatalf("cover: improperly quoted string %q\n", s)
	}
	return t
}
Exemple #24
0
func unquote(s string) string {
	res, err := strconv.Unquote(s)
	if err != nil {
		return "could_not_unquote"
	}
	return res
}
Exemple #25
0
// ImportPath = string_lit .
//
func (p *gcParser) parsePkgId() *ast.Object {
	id, err := strconv.Unquote(p.expect(scanner.String))
	if err != nil {
		p.error(err)
	}

	switch id {
	case "":
		// id == "" stands for the imported package id
		// (only known at time of package installation)
		id = p.id
	case "unsafe":
		// package unsafe is not in the imports map - handle explicitly
		return Unsafe
	}

	pkg := p.imports[id]
	if pkg == nil {
		scope = ast.NewScope(nil)
		pkg = ast.NewObj(ast.Pkg, "")
		pkg.Data = scope
		p.imports[id] = pkg
	}

	return pkg
}
Exemple #26
0
func importPath(n *ast.ImportSpec) string {
	p, err := strconv.Unquote(n.Path.Value)
	if err != nil {
		fail("invalid string literal %q in ast.ImportSpec", n.Path.Value)
	}
	return p
}
Exemple #27
0
// importPath returns the unquoted import path of s,
// or "" if the path is not properly quoted.
func importPath(s *ast.ImportSpec) string {
	t, err := strconv.Unquote(s.Path.Value)
	if err == nil {
		return t
	}
	return ""
}
Exemple #28
0
func getLocalImports(filename string) (imports map[string]bool, error os.Error) {
	source, error := ioutil.ReadFile(filename)
	if error != nil {
		return
	}
	file, error := parser.ParseFile(filename, source, parser.ImportsOnly)
	if error != nil {
		return
	}
	for _, importDecl := range file.Decls {
		importDecl, ok := importDecl.(*ast.GenDecl)
		if ok {
			for _, importSpec := range importDecl.Specs {
				importSpec, ok := importSpec.(*ast.ImportSpec)
				if ok {
					for _, importPath := range importSpec.Path {
						importPath, _ := strconv.Unquote(string(importPath.Value))
						if len(importPath) > 0 && importPath[0] == '.' {
							if imports == nil {
								imports = make(map[string]bool)
							}
							dir, _ := path.Split(filename)
							imports[path.Join(dir, path.Clean(importPath))] = true
						}
					}
				}
			}
		}
	}

	return
}
Exemple #29
0
func unquoteIfPossible(s string) (string, error) {
	if len(s) == 0 || s[0] != '"' {
		return s, nil
	}

	return strconv.Unquote(s)
}
Exemple #30
0
func parseRegexp(text string) (*regexp.Regexp, error) {
	pattern, err := strconv.Unquote(text)
	if err != nil {
		return nil, fmt.Errorf("can't unquote %s", text)
	}
	return regexp.Compile(pattern)
}