Exemple #1
0
func TestIsIgnoredFile(t *testing.T) {
	home := osutil.HomeDir()
	fullpath := filepath.Join(home, "Downloads", "pony.jpg")
	var wantIgnored = map[string]bool{
		filepath.Join(home, filepath.FromSlash("Downloads/pony.jpg")): true,
		filepath.Join(home, filepath.FromSlash("Downloads/pony.*")):   true,
		filepath.Join(home, filepath.FromSlash("Downloads/*.jpg")):    true,
		filepath.Join(home, filepath.FromSlash("Downloads/*")):        true,
		"*.jpg":  true,
		"pony.*": true,
		"*.foo":  false,
		"foo.*":  false,
		filepath.Join(home, "Downloads"):           true,
		filepath.Join(home, "Down"):                false,
		filepath.FromSlash("~/Downloads/pony.jpg"): true,
		filepath.FromSlash("~/Downloads/pony.*"):   true,
		filepath.FromSlash("~/Downloads/*.jpg"):    true,
		filepath.FromSlash("~/Downloads"):          true,
		filepath.FromSlash("~/Down"):               false,
		filepath.FromSlash("~/DownloadsAndMore"):   false,
		home:        true,
		"Downloads": true,
		"Down":      false,
	}
	for pattern, want := range wantIgnored {
		ignoreChecker := newIgnoreChecker([]string{pattern})
		if ignoreChecker(fullpath) != want {
			t.Errorf("%v not ignored; did not match %v", fullpath, pattern)
		}
	}
}
func (s *format_1_18Suite) TestMissingAttributes(c *gc.C) {
	logDir, err := paths.LogDir(series.HostSeries())
	c.Assert(err, jc.ErrorIsNil)
	realDataDir, err := paths.DataDir(series.HostSeries())
	c.Assert(err, jc.ErrorIsNil)

	realDataDir = filepath.FromSlash(realDataDir)
	logPath := filepath.Join(logDir, "juju")
	logPath = filepath.FromSlash(logPath)

	dataDir := c.MkDir()
	configPath := filepath.Join(dataDir, agentConfigFilename)
	err = utils.AtomicWriteFile(configPath, []byte(configData1_18WithoutUpgradedToVersion), 0600)
	c.Assert(err, jc.ErrorIsNil)
	readConfig, err := ReadConfig(configPath)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(readConfig.UpgradedToVersion(), gc.Equals, version.MustParse("1.16.0"))
	configLogDir := filepath.FromSlash(readConfig.LogDir())
	configDataDir := filepath.FromSlash(readConfig.DataDir())
	c.Assert(configLogDir, gc.Equals, logPath)
	c.Assert(configDataDir, gc.Equals, realDataDir)
	c.Assert(readConfig.PreferIPv6(), jc.IsFalse)
	// The api info doesn't have the environment tag set.
	apiInfo, ok := readConfig.APIInfo()
	c.Assert(ok, jc.IsTrue)
	c.Assert(apiInfo.EnvironTag.Id(), gc.Equals, "")
}
Exemple #3
0
func loadDefaultKeys() (auths []ssh.AuthMethod, err error) {
	k := ""
	currentUser, err := user.Current()
	defaultKeyPathA := filepath.FromSlash(currentUser.HomeDir + "/.ssh/id_rsa")
	defaultKeyPathB := filepath.FromSlash(currentUser.HomeDir + "/ssh/id_rsa")
	if fileExists(defaultKeyPathA) {
		k = defaultKeyPathA
	} else if fileExists(defaultKeyPathB) {
		k = defaultKeyPathB
	}
	if len(k) == 0 {
		err = errors.New("No key specified")
		return
	}
	pemBytes, err := ioutil.ReadFile(k)
	if err != nil {
		return
	}
	signer, err := ssh.ParsePrivateKey(pemBytes)
	if err != nil {
		return
	}
	auths = []ssh.AuthMethod{ssh.PublicKeys(signer)}
	return
}
Exemple #4
0
// genSearchTypes duplicates some of the camlistore.org/pkg/search types into
// camlistore.org/app/publisher/js/zsearch.go , because it's too costly (in output
// file size) for now to import the search pkg into gopherjs.
func genSearchTypes() error {
	sourceFile := filepath.Join(buildSrcDir, filepath.FromSlash("pkg/search/describe.go"))
	outputFile := filepath.Join(buildSrcDir, filepath.FromSlash("app/publisher/js/zsearch.go"))
	fi1, err := os.Stat(sourceFile)
	if err != nil {
		return err
	}
	fi2, err := os.Stat(outputFile)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if err == nil && fi2.ModTime().After(fi1.ModTime()) {
		wantDestFile[outputFile] = true
		return nil
	}
	args := []string{"generate", "camlistore.org/app/publisher/js"}
	cmd := exec.Command("go", args...)
	cmd.Env = append(cleanGoEnv(),
		"GOPATH="+buildGoPath,
	)
	if out, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("go generate for publisher js error: %v, %v", err, string(out))
	}
	wantDestFile[outputFile] = true
	log.Printf("generated %v", outputFile)
	return nil
}
Exemple #5
0
func TestGetRelativePath(t *testing.T) {
	tests := []struct {
		path   string
		base   string
		expect interface{}
	}{
		{filepath.FromSlash("/a/b"), filepath.FromSlash("/a"), filepath.FromSlash("b")},
		{filepath.FromSlash("/a/b/c/"), filepath.FromSlash("/a"), filepath.FromSlash("b/c/")},
		{filepath.FromSlash("/c"), filepath.FromSlash("/a/b"), filepath.FromSlash("../../c")},
		{filepath.FromSlash("/c"), "", false},
	}
	for i, this := range tests {
		// ultimately a fancy wrapper around filepath.Rel
		result, err := GetRelativePath(this.path, this.base)

		if b, ok := this.expect.(bool); ok && !b {
			if err == nil {
				t.Errorf("[%d] GetRelativePath didn't return an expected error", i)
			}
		} else {
			if err != nil {
				t.Errorf("[%d] GetRelativePath failed: %s", i, err)
				continue
			}
			if result != this.expect {
				t.Errorf("[%d] GetRelativePath got %v but expected %v", i, result, this.expect)
			}
		}

	}
}
Exemple #6
0
func (d *VersionHandler) pkgPath(pkg string) string {
	root, sub := util.NormalizeName(pkg)

	// For the parent applications source skip the cache.
	if root == d.Config.Name {
		pth := gpath.Basepath()
		return filepath.Join(pth, filepath.FromSlash(sub))
	}

	dep := d.Config.Imports.Get(root)
	if dep == nil {
		dep = d.Config.DevImports.Get(root)
	}

	if dep == nil {
		dep, _ = d.Use.Get(root)

		if dep == nil {
			dep = &cfg.Dependency{Name: root}
		}
	}

	key, err := cache.Key(dep.Remote())
	if err != nil {
		msg.Die("Error generating cache key for %s", dep.Name)
	}

	return filepath.Join(cache.Location(), "src", key, filepath.FromSlash(sub))
}
Exemple #7
0
func (p *Page) TargetPath() (outfile string) {

	// Always use Url if it's specified
	if len(strings.TrimSpace(p.Url)) > 2 {
		outfile = strings.TrimSpace(p.Url)

		if strings.HasSuffix(outfile, "/") {
			outfile = outfile + "index.html"
		}
		outfile = filepath.FromSlash(outfile)
		return
	}

	// If there's a Permalink specification, we use that
	if override, ok := p.Site.Permalinks[p.Section()]; ok {
		var err error
		outfile, err = override.Expand(p)
		if err == nil {
			if strings.HasSuffix(outfile, "/") {
				outfile += "index.html"
			}
			outfile = filepath.FromSlash(outfile)
			return
		}
	}

	if len(strings.TrimSpace(p.Slug)) > 0 {
		outfile = strings.TrimSpace(p.Slug) + "." + p.Extension()
	} else {
		// Fall back to filename
		outfile = helpers.ReplaceExtension(p.Source.LogicalName(), p.Extension())
	}

	return filepath.Join(p.Source.Dir(), strings.TrimSpace(outfile))
}
Exemple #8
0
func (container *container) Run(spec garden.ProcessSpec, processIO garden.ProcessIO) (garden.Process, error) {
	cmd := exec.Command(filepath.FromSlash(spec.Path), spec.Args...)
	cmd.Dir = filepath.Join(container.workDir, filepath.FromSlash(spec.Dir))
	cmd.Env = append(os.Environ(), append(container.env, spec.Env...)...)

	return container.processTracker.Run(cmd, processIO, spec.TTY)
}
Exemple #9
0
func copylocal(s string) error {
	r, err := http.Get("http://uec-images.ubuntu.com/" + s)
	if err != nil {
		return fmt.Errorf("get %q: %v", s, err)
	}
	defer r.Body.Close()
	if r.StatusCode != 200 {
		return fmt.Errorf("status on %q: %s", s, r.Status)
	}
	path := filepath.Join(filepath.FromSlash(imagesRoot), filepath.FromSlash(s))
	d, _ := filepath.Split(path)
	if err := os.MkdirAll(d, 0777); err != nil {
		return err
	}
	file, err := os.Create(path)
	if err != nil {
		return err
	}
	defer file.Close()
	_, err = io.Copy(file, r.Body)
	if err != nil {
		return fmt.Errorf("error copying image file: %v", err)
	}
	return nil
}
Exemple #10
0
// Unzip is an exported method which sanitizes io paths and starts unzipping
func Unzip(src, dst string) error {
	z := &unzipper{
		src: filepath.Clean(filepath.FromSlash(src)),
		dst: filepath.Clean(filepath.FromSlash(dst)),
	}
	return z.do()
}
Exemple #11
0
func Untar(src, dst string) error {
	t := &untarmonster{
		src: filepath.Clean(filepath.FromSlash(src)),
		dst: filepath.Clean(filepath.FromSlash(dst)),
	}
	return t.do()
}
func (s *format_1_16Suite) TestMissingAttributes(c *gc.C) {
	logDir, err := paths.LogDir(series.HostSeries())
	c.Assert(err, jc.ErrorIsNil)
	realDataDir, err := paths.DataDir(series.HostSeries())
	c.Assert(err, jc.ErrorIsNil)

	realDataDir = filepath.FromSlash(realDataDir)
	logPath := filepath.Join(logDir, "juju")
	logPath = filepath.FromSlash(logPath)

	dataDir := c.MkDir()
	formatPath := filepath.Join(dataDir, legacyFormatFilename)
	err = utils.AtomicWriteFile(formatPath, []byte(legacyFormatFileContents), 0600)
	c.Assert(err, jc.ErrorIsNil)
	configPath := filepath.Join(dataDir, agentConfigFilename)

	err = utils.AtomicWriteFile(configPath, []byte(configDataWithoutNewAttributes), 0600)
	c.Assert(err, jc.ErrorIsNil)
	readConfig, err := ReadConfig(configPath)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(readConfig.UpgradedToVersion(), gc.Equals, version.MustParse("1.16.0"))
	configLogDir := filepath.FromSlash(readConfig.LogDir())
	configDataDir := filepath.FromSlash(readConfig.DataDir())

	c.Assert(configLogDir, gc.Equals, logPath)
	c.Assert(configDataDir, gc.Equals, realDataDir)
	// Test data doesn't include a StateServerKey so StateServingInfo
	// should *not* be available
	_, available := readConfig.StateServingInfo()
	c.Assert(available, jc.IsFalse)
}
Exemple #13
0
// Issue #1934
func TestYAMLMenuWithMultipleEntries(t *testing.T) {
	viper.Reset()
	defer viper.Reset()

	ps1 := []byte(`---
title: "Yaml 1"
weight: 5
menu: ["p_one", "p_two"]
---
Yaml Front Matter with Menu Pages`)

	ps2 := []byte(`---
title: "Yaml 2"
weight: 5
menu:
    p_three:
    p_four:
---
Yaml Front Matter with Menu Pages`)

	s := setupMenuTests(t, []source.ByteSource{
		{filepath.FromSlash("sect/yaml1.md"), ps1},
		{filepath.FromSlash("sect/yaml2.md"), ps2}})

	p1 := s.Pages[0]
	assert.Len(t, p1.Menus(), 2, "List YAML")
	p2 := s.Pages[1]
	assert.Len(t, p2.Menus(), 2, "Map YAML")

}
Exemple #14
0
func (e *Env) SetCamdevVars(altkey bool) {
	e.Set("CAMLI_CONFIG_DIR", filepath.Join("config", "dev-client-dir"))
	e.Set("CAMLI_AUTH", "userpass:camlistore:pass3179")
	e.Set("CAMLI_DEV_KEYBLOBS", filepath.FromSlash("config/dev-client-dir/keyblobs"))

	secring := defaultSecring
	identity := defaultIdentity

	if altkey {
		secring = filepath.FromSlash("pkg/jsonsign/testdata/password-foo-secring.gpg")
		identity = "C7C3E176"
		println("**\n** Note: password is \"foo\"\n**\n")
	} else {
		if *flagSecretRing != "" {
			secring = *flagSecretRing
		}
		if *flagIdentity != "" {
			identity = *flagIdentity
		}
	}

	entity, err := jsonsign.EntityFromSecring(identity, secring)
	if err != nil {
		panic(err)
	}
	armoredPublicKey, err := jsonsign.ArmoredPublicKey(entity)
	if err != nil {
		panic(err)
	}
	pubKeyRef := blob.SHA1FromString(armoredPublicKey)

	e.Set("CAMLI_SECRET_RING", secring)
	e.Set("CAMLI_KEYID", identity)
	e.Set("CAMLI_PUBKEY_BLOBREF", pubKeyRef.String())
}
Exemple #15
0
func TestConfig_LoadConfigsFileOrder(t *testing.T) {
	config1, err := LoadConfigDir("test-resources/etcnomad")
	if err != nil {
		t.Fatalf("Failed to load config: %s", err)
	}

	config2, err := LoadConfig("test-resources/myconf")
	if err != nil {
		t.Fatalf("Failed to load config: %s", err)
	}

	expected := []string{
		// filepath.FromSlash changes these to backslash \ on Windows
		filepath.FromSlash("test-resources/etcnomad/common.hcl"),
		filepath.FromSlash("test-resources/etcnomad/server.json"),
		filepath.FromSlash("test-resources/myconf"),
	}

	config := config1.Merge(config2)

	if !reflect.DeepEqual(config.Files, expected) {
		t.Errorf("Loaded configs don't match\nwant: %+v\n got: %+v\n",
			expected, config.Files)
	}
}
Exemple #16
0
func TestOverwriteFile(t *testing.T) {
	b, dir := setupBucketWithFiles()

	addFile(dir, "hoge", "piyo")
	b.AddFiles(dir)

	assertContents(t, b, 3)
	assertUploadCount(t, b, 0)

	addFile(dir, "hoge", "fuga2")
	b.AddFiles(dir)

	assertUploadCount(t, b, 1)

	addFile(dir, "hoge", "fuga3")
	b.AddFiles(dir)

	assertUploadCount(t, b, 2)

	addFile(dir, "hoge", "fuga2")
	b.AddFiles(dir)

	assertUploadCount(t, b, 2)

	addFile(dir, filepath.FromSlash("piyo/piyo"), "piyo2")
	b.AddFiles(dir)

	assertUploadCount(t, b, 3)

	addFile(dir, filepath.FromSlash("piyo/piyo"), "piyo2")
	b.AddFiles(dir)

	assertContents(t, b, 3)
	assertUploadCount(t, b, 3)
}
// normaliseWorkdir normalises a user requested working directory in a
// platform sematically consistent way.
func normaliseWorkdir(current string, requested string) (string, error) {
	if requested == "" {
		return "", fmt.Errorf("cannot normalise nothing")
	}

	current = filepath.FromSlash(current)
	requested = filepath.FromSlash(requested)

	// Target semantics is C:\somefolder, specifically in the format:
	// UPPERCASEDriveLetter-Colon-Backslash-FolderName. We are already
	// guaranteed that `current`, if set, is consistent. This allows us to
	// cope correctly with any of the following in a Dockerfile:
	//	WORKDIR a                       --> C:\a
	//	WORKDIR c:\\foo                 --> C:\foo
	//	WORKDIR \\foo                   --> C:\foo
	//	WORKDIR /foo                    --> C:\foo
	//	WORKDIR c:\\foo \ WORKDIR bar   --> C:\foo --> C:\foo\bar
	//	WORKDIR C:/foo \ WORKDIR bar    --> C:\foo --> C:\foo\bar
	//	WORKDIR C:/foo \ WORKDIR \\bar  --> C:\foo --> C:\bar
	//	WORKDIR /foo \ WORKDIR c:/bar   --> C:\foo --> C:\bar
	if len(current) == 0 || system.IsAbs(requested) {
		if (requested[0] == os.PathSeparator) ||
			(len(requested) > 1 && string(requested[1]) != ":") ||
			(len(requested) == 1) {
			requested = filepath.Join(`C:\`, requested)
		}
	} else {
		requested = filepath.Join(current, requested)
	}
	// Upper-case drive letter
	return (strings.ToUpper(string(requested[0])) + requested[1:]), nil
}
Exemple #18
0
// Compiles a single ASL file.
func compileFile(path string, file ASLFile, waiter chan bool) {
	defer recoverCompileError(file.in, waiter)

	// read file
	out := filepath.FromSlash(path + PathSeparator + file.out + PathSeparator + file.newname + sqfextension)
	fmt.Println(file.in + " -> " + out)
	code, err := ioutil.ReadFile(file.in)

	if err != nil {
		fmt.Println("Error reading file: " + file.in)
		return
	}

	// compile
	token := tokenizer.Tokenize(code, false)
	compiler := parser.Compiler{}
	sqf := compiler.Parse(token, pretty)

	os.MkdirAll(filepath.FromSlash(path+PathSeparator+file.out), 0777)
	err = ioutil.WriteFile(out, []byte(sqf), 0666)

	if err != nil {
		fmt.Println("Error writing file: " + file.out)
		fmt.Println(err)
	}

	waiter <- true // done
}
Exemple #19
0
func TestTargetPath(t *testing.T) {
	tests := []struct {
		doc             string
		content         string
		expectedOutFile string
		expectedSection string
	}{
		{"content/a/file.md", PAGE_URL_SPECIFIED, "mycategory/my-whatever-content/index.html", "a"},
		{"content/x/y/deepfile.md", SIMPLE_PAGE, "x/y/deepfile.html", "x/y"},
		{"content/x/y/z/deeperfile.md", SIMPLE_PAGE, "x/y/z/deeperfile.html", "x/y/z"},
		{"content/b/file.md", SIMPLE_PAGE, "b/file.html", "b"},
		{"a/file.md", SIMPLE_PAGE, "a/file.html", "a"},
		{"file.md", SIMPLE_PAGE, "file.html", ""},
	}

	if true {
		return
	}

	for _, test := range tests {
		p := pageMust(NewPageFrom(strings.NewReader(test.content), helpers.AbsPathify(filepath.FromSlash(test.doc))))

		expected := filepath.FromSlash(test.expectedOutFile)

		if p.TargetPath() != expected {
			t.Errorf("%s => OutFile  expected: '%s', got: '%s'", test.doc, expected, p.TargetPath())
		}

		if p.Section() != test.expectedSection {
			t.Errorf("%s => p.Section expected: %s, got: %s", test.doc, test.expectedSection, p.Section())
		}
	}
}
Exemple #20
0
// Creates a list of all ASL files to compile.
func readAslFiles(path string) {
	dir, err := ioutil.ReadDir(path)

	if err != nil {
		fmt.Println("Error reading in directory!")
		return
	}

	for i := 0; i < len(dir); i++ {
		name := dir[i].Name()

		if dir[i].IsDir() && recursive {
			readAslFiles(filepath.FromSlash(path + PathSeparator + name))
			continue
		}

		if !dir[i].IsDir() && strings.ToLower(filepath.Ext(name)) == extension {
			in := filepath.FromSlash(path + PathSeparator + dir[i].Name())
			out := filepath.FromSlash("./" + path[len(inDir):len(path)])
			newname := name[:len(name)-len(filepath.Ext(name))]

			file := ASLFile{in, out, newname}
			aslFiles = append(aslFiles, file)
		}
	}
}
Exemple #21
0
// For some reason (https://github.com/gopherjs/gopherjs/issues/415), the
// github.com/gopherjs/gopherjs/js import is treated specially, and it cannot be
// vendored at all for gopherjs to work properly. So we move it to our tmp GOPATH.
func moveGopherjs() error {
	dest := filepath.Join(buildGoPath, filepath.FromSlash("src/github.com/gopherjs/gopherjs"))
	if err := os.MkdirAll(dest, 0700); err != nil {
		return err
	}
	src := filepath.Join(buildSrcDir, filepath.FromSlash("vendor/github.com/gopherjs/gopherjs"))
	if err := filepath.Walk(src, func(path string, fi os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		suffix, err := filepath.Rel(src, path)
		if err != nil {
			return err
		}
		destName := filepath.Join(dest, suffix)
		if fi.IsDir() {
			return os.MkdirAll(destName, 0700)
		}
		destFi, err := os.Stat(destName)
		if err != nil && !os.IsNotExist(err) {
			return err
		}
		if err == nil && !fi.ModTime().After(destFi.ModTime()) {
			return nil
		}
		dataSrc, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		return ioutil.WriteFile(destName, dataSrc, 0600)
	}); err != nil {
		return err
	}
	return os.RemoveAll(src)
}
Exemple #22
0
// issue #83
func TestCanonical_RelativeSymlink(t *testing.T) {
	dir, err := ioutil.TempDir(wd, "")
	if err != nil {
		t.Fatalf("TempDir()=%v", err)
	}
	var (
		path     = filepath.Join(dir, filepath.FromSlash("a/b/c/d/e/f"))
		realpath = filepath.Join(dir, filepath.FromSlash("a/b/x/y/z/d/e/f"))
		rel      = filepath.FromSlash("x/y/z/../z/../z")
		chdir    = filepath.Join(dir, filepath.FromSlash("a/b"))
	)
	defer os.RemoveAll(dir)
	if err = os.MkdirAll(realpath, 0755); err != nil {
		t.Fatalf("MkdirAll()=%v", err)
	}
	if err := os.Chdir(chdir); err != nil {
		t.Fatalf("Chdir()=%v", err)
	}
	if err := nonil(os.Symlink(rel, "c"), os.Chdir(wd)); err != nil {
		t.Fatalf("Symlink()=%v", err)
	}
	got, err := canonical(path)
	if err != nil {
		t.Fatalf("canonical(%s)=%v", path, err)
	}
	if got != realpath {
		t.Fatalf("want canonical()=%s; got %s", realpath, got)
	}
}
Exemple #23
0
// This method handles requests for files. The supplied prefix may be absolute
// or relative. If the prefix is relative it is assumed to be relative to the
// application directory. The filepath may either be just a file or an
// additional filepath to search for the given file. This response may return
// the following responses in the event of an error or invalid request;
//   403(Forbidden): If the prefix filepath combination results in a directory.
//   404(Not found): If the prefix and filepath combination results in a non-existent file.
//   500(Internal Server Error): There are a few edge cases that would likely indicate some configuration error outside of revel.
//
// Note that when defining routes in routes/conf the parameters must not have
// spaces around the comma.
//   Bad:  Static.Serve("public/img", "favicon.png")
//   Good: Static.Serve("public/img","favicon.png")
//
// Examples:
// Serving a directory
//   Route (conf/routes):
//     GET /public/{<.*>filepath} Static.Serve("public")
//   Request:
//     public/js/sessvars.js
//   Calls
//     Static.Serve("public","js/sessvars.js")
//
// Serving a file
//   Route (conf/routes):
//     GET /favicon.ico Static.Serve("public/img","favicon.png")
//   Request:
//     favicon.ico
//   Calls:
//     Static.Serve("public/img", "favicon.png")
func (c Static) Serve(prefix, filepath string) revel.Result {
	var basePath string

	if !fpath.IsAbs(prefix) {
		basePath = revel.BasePath
	}

	basePathPrefix := fpath.Join(basePath, fpath.FromSlash(prefix))
	fname := fpath.Join(basePathPrefix, fpath.FromSlash(filepath))
	if !strings.HasPrefix(fname, basePathPrefix) {
		revel.WARN.Printf("Attempted to read file outside of base path: %s", fname)
		return c.NotFound("")
	}

	finfo, err := os.Stat(fname)
	if err != nil {
		if os.IsNotExist(err) {
			revel.WARN.Printf("File not found (%s): %s ", fname, err)
			return c.NotFound("File not found")
		}
		revel.ERROR.Printf("Error trying to get fileinfo for '%s': %s", fname, err)
		return c.RenderError(err)
	}

	if finfo.Mode().IsDir() {
		revel.WARN.Printf("Attempted directory listing of %s", fname)
		return c.Forbidden("Directory listing not allowed")
	}

	file, err := os.Open(fname)
	return c.RenderFile(file, revel.Inline)
}
Exemple #24
0
// This method handles requests for files. The supplied prefix may be absolute
// or relative. If the prefix is relative it is assumed to be relative to the
// application directory. The filepath may either be just a file or an
// additional filepath to search for the given file. This response may return
// the following responses in the event of an error or invalid request;
//   403(Forbidden): If the prefix filepath combination results in a directory.
//   404(Not found): If the prefix and filepath combination results in a non-existent file.
//   500(Internal Server Error): There are a few edge cases that would likely indicate some configuration error outside of revel.
//
// Note that when defining routes in routes/conf the parameters must not have
// spaces around the comma.
//   Bad:  Static.Serve("public/img", "favicon.png")
//   Good: Static.Serve("public/img","favicon.png")
//
// Examples:
// Serving a directory
//   Route (conf/routes):
//     GET /public/{<.*>filepath} Static.Serve("public")
//   Request:
//     public/js/sessvars.js
//   Calls
//     Static.Serve("public","js/sessvars.js")
//
// Serving a file
//   Route (conf/routes):
//     GET /favicon.ico Static.Serve("public/img","favicon.png")
//   Request:
//     favicon.ico
//   Calls:
//     Static.Serve("public/img", "favicon.png")
func (c Static) Serve(prefix, filepath string) revel.Result {
	var basePath string

	if !fpath.IsAbs(prefix) {
		basePath = revel.BasePath
	}

	fname := fpath.Join(basePath, fpath.FromSlash(prefix), fpath.FromSlash(filepath))

	finfo, err := os.Stat(fname)

	if err == nil {
		if finfo.Mode().IsDir() {
			revel.WARN.Printf("Attempted directory listing of %s", fname)
			return c.Forbidden("Directory listing not allowed")
		}
		file, err := os.Open(fname)
		if os.IsNotExist(err) {
			revel.WARN.Printf("File not found (%s): %s ", fname, err)
			return c.NotFound("File not found")
		} else if err != nil {
			revel.WARN.Printf("Problem opening file (%s): %s ", fname, err)
			return c.RenderError(err)
		}
		return c.RenderFile(file, "")
	} else {
		revel.ERROR.Printf("Error trying to get fileinfo for '%s': %s", fname, err)
	}

	return c.RenderError(err)

}
Exemple #25
0
func TestDraftAndFutureRender(t *testing.T) {
	viper.Reset()
	defer viper.Reset()

	hugofs.DestinationFS = new(afero.MemMapFs)
	sources := []source.ByteSource{
		{filepath.FromSlash("sect/doc1.md"), []byte("---\ntitle: doc1\ndraft: true\npublishdate: \"2414-05-29\"\n---\n# doc1\n*some content*")},
		{filepath.FromSlash("sect/doc2.md"), []byte("---\ntitle: doc2\ndraft: true\npublishdate: \"2012-05-29\"\n---\n# doc2\n*some content*")},
		{filepath.FromSlash("sect/doc3.md"), []byte("---\ntitle: doc3\ndraft: false\npublishdate: \"2414-05-29\"\n---\n# doc3\n*some content*")},
		{filepath.FromSlash("sect/doc4.md"), []byte("---\ntitle: doc4\ndraft: false\npublishdate: \"2012-05-29\"\n---\n# doc4\n*some content*")},
	}

	siteSetup := func() *Site {
		s := &Site{
			Source: &source.InMemorySource{ByteSource: sources},
		}

		s.initializeSiteInfo()

		if err := s.CreatePages(); err != nil {
			t.Fatalf("Unable to create pages: %s", err)
		}
		return s
	}

	viper.Set("baseurl", "http://auth/bub")

	// Testing Defaults.. Only draft:true and publishDate in the past should be rendered
	s := siteSetup()
	if len(s.Pages) != 1 {
		t.Fatal("Draft or Future dated content published unexpectedly")
	}

	// only publishDate in the past should be rendered
	viper.Set("BuildDrafts", true)
	s = siteSetup()
	if len(s.Pages) != 2 {
		t.Fatal("Future Dated Posts published unexpectedly")
	}

	//  drafts should not be rendered, but all dates should
	viper.Set("BuildDrafts", false)
	viper.Set("BuildFuture", true)
	s = siteSetup()
	if len(s.Pages) != 2 {
		t.Fatal("Draft posts published unexpectedly")
	}

	// all 4 should be included
	viper.Set("BuildDrafts", true)
	viper.Set("BuildFuture", true)
	s = siteSetup()
	if len(s.Pages) != 4 {
		t.Fatal("Drafts or Future posts not included as expected")
	}

	//setting defaults back
	viper.Set("BuildDrafts", false)
	viper.Set("BuildFuture", false)
}
Exemple #26
0
// Workdir returns the working directory for a package.
func Workdir(pkg *Package) string {
	if pkg.TestScope {
		ip := strings.TrimSuffix(filepath.FromSlash(pkg.ImportPath), "_test")
		return filepath.Join(pkg.Workdir(), ip, "_test", filepath.Dir(filepath.FromSlash(pkg.ImportPath)))
	}
	return filepath.Join(pkg.Workdir(), filepath.Dir(filepath.FromSlash(pkg.ImportPath)))
}
Exemple #27
0
func TestPageTranslator(t *testing.T) {
	tests := []struct {
		content  string
		expected string
	}{
		{"/", "index.html"},
		{"index.html", "index.html"},
		{"bar/index.html", "bar/index.html"},
		{"foo", "foo/index.html"},
		{"foo.html", "foo/index.html"},
		{"foo.xhtml", "foo/index.xhtml"},
		{"section", "section/index.html"},
		{"section/", "section/index.html"},
		{"section/foo", "section/foo/index.html"},
		{"section/foo.html", "section/foo/index.html"},
		{"section/foo.rss", "section/foo/index.rss"},
	}

	for _, test := range tests {
		f := new(PagePub)
		dest, err := f.Translate(filepath.FromSlash(test.content))
		expected := filepath.FromSlash(test.expected)
		if err != nil {
			t.Fatalf("Translate returned and unexpected err: %s", err)
		}

		if dest != expected {
			t.Errorf("Translate expected return: %s, got: %s", expected, dest)
		}
	}
}
Exemple #28
0
// loadPackage scans directory named by arg,
// which is either an import path or a file system path
// (if the latter, must be rooted or begin with . or ..),
// and returns a *Package describing the package
// found in that directory.
func loadPackage(arg string, stk *importStack) *Package {
	stk.push(arg)
	defer stk.pop()

	// Check package cache.
	if p := packageCache[arg]; p != nil {
		return reusePackage(p, stk)
	}

	// Find basic information about package path.
	t, importPath, err := build.FindTree(arg)
	dir := ""
	// Maybe it is a standard command.
	if err != nil && strings.HasPrefix(arg, "cmd/") {
		goroot := build.Path[0]
		p := filepath.Join(goroot.Path, "src", arg)
		if st, err1 := os.Stat(p); err1 == nil && st.IsDir() {
			t = goroot
			importPath = arg
			dir = p
			err = nil
		}
	}
	// Maybe it is a path to a standard command.
	if err != nil && (filepath.IsAbs(arg) || isLocalPath(arg)) {
		arg, _ := filepath.Abs(arg)
		goroot := build.Path[0]
		cmd := filepath.Join(goroot.Path, "src", "cmd") + string(filepath.Separator)
		if st, err1 := os.Stat(arg); err1 == nil && st.IsDir() && strings.HasPrefix(arg, cmd) {
			t = goroot
			importPath = filepath.FromSlash(arg[len(cmd):])
			dir = arg
			err = nil
		}
	}
	if err != nil {
		p := &Package{
			ImportPath: arg,
			Error: &PackageError{
				ImportStack: stk.copy(),
				Err:         err.Error(),
			},
			Incomplete: true,
		}
		packageCache[arg] = p
		return p
	}

	if dir == "" {
		dir = filepath.Join(t.SrcDir(), filepath.FromSlash(importPath))
	}

	// Maybe we know the package by its directory.
	if p := packageCache[dir]; p != nil {
		packageCache[importPath] = p
		return reusePackage(p, stk)
	}

	return scanPackage(&buildContext, t, arg, importPath, dir, stk)
}
Exemple #29
0
func (*SymlinkSuite) TestReplace(c *gc.C) {
	target, err := symlink.GetLongPathAsString(c.MkDir())
	c.Assert(err, gc.IsNil)
	target_second, err := symlink.GetLongPathAsString(c.MkDir())
	c.Assert(err, gc.IsNil)
	link := filepath.Join(target, "link")

	_, err = os.Stat(target)
	c.Assert(err, gc.IsNil)
	_, err = os.Stat(target_second)
	c.Assert(err, gc.IsNil)

	err = symlink.New(target, link)
	c.Assert(err, gc.IsNil)

	link_target, err := symlink.Read(link)
	c.Assert(err, gc.IsNil)
	c.Assert(link_target, gc.Equals, filepath.FromSlash(target))

	err = symlink.Replace(link, target_second)
	c.Assert(err, gc.IsNil)

	link_target, err = symlink.Read(link)
	c.Assert(err, gc.IsNil)
	c.Assert(link_target, gc.Equals, filepath.FromSlash(target_second))
}
Exemple #30
0
// CacheDir tries to acquire an OS-specific app cache directory for the given importPath.
// Cache directory contains the app's cached data that can be regenerated as needed.
// Apps should never rely on the existence of cache files.
//
// It's guaranteed to be a unique directory for the importPath.
// Before returning the directory's path, CacheDir creates the directory if it
// doesn't already exist, so it can be used right away.
func CacheDir(importPath string) (string, error) {
	var home string
	if u, err := user.Current(); err != nil {
		home = os.Getenv("HOME")
		if home == "" {
			return "", err
		}
	} else {
		home = u.HomeDir
	}
	// TODO: Support Windows in analogous ways. Also support mobile devices (iOS, Android).
	//       Think about web? While HTML5 Local Storage could be used, it's not going to be compatible
	//       with filepaths; so maybe consider returning a webdav.FileSystem or so instead? Needs consideration.
	switch {
	case runtime.GOOS == "darwin" && runtime.GOARCH == "amd64":
		dir := filepath.Join(home, "Library", "Caches", filepath.FromSlash(importPath))
		if err := os.MkdirAll(dir, 0700); err != nil {
			return "", err
		}
		return dir, nil
	case runtime.GOOS == "linux" && (runtime.GOARCH == "386" || runtime.GOARCH == "amd64"):
		// $HOME/.cache path is based on https://github.com/rsc/gt/blob/ee152ddc9ec2a99d345cf81b6ba0f40a83c9dd6f/main.go#L22.
		dir := filepath.Join(home, ".cache", filepath.FromSlash(importPath))
		if err := os.MkdirAll(dir, 0700); err != nil {
			return "", err
		}
		return dir, nil
	default:
		return "", fmt.Errorf("ospath.CacheDir not implemented for %s/%s", runtime.GOOS, runtime.GOARCH)
	}
}