예제 #1
0
파일: main.go 프로젝트: aiviru/bzwikipedia
//
// Clear out any old rec*.xml.bz2 or titlecache.txt files
//
func cleanOldCache() {
	recs, _ := filepath.Glob(filepath.Join(conf["data_dir"], "rec*.xml.bz2"))
	tfs, _ := filepath.Glob(conf["title_file"])
	dfs, _ := filepath.Glob(conf["dat_file"])

	// If any old record or title cache files exist, give the user an opportunity
	// to ctrl-c to cancel this.

	if len(recs) > 0 || len(tfs) > 0 || len(dfs) > 0 {
		fmt.Println("Old record and/or title cache file exist. Removing in 5 seconds ...")
		time.Sleep(5000000000)
	}

	if len(recs) > 0 {
		fmt.Println("Removing old record files . . .")
		for _, fp := range recs {
			os.Remove(fp)
		}
	}

	if len(tfs) > 0 {
		fmt.Println("Removing old title file . . .")
		for _, fp := range tfs {
			os.Remove(fp)
		}
	}

	if len(dfs) > 0 {
		fmt.Println("Removing old dat file . . .")
		for _, fp := range dfs {
			os.Remove(fp)
		}
	}
}
예제 #2
0
파일: logos.go 프로젝트: pyisoeyz/chaparty
func loadLogos(context appengine.Context, globpaths ...string) map[string][]image.Image {
	logoImagesByName := make(map[string][]image.Image)

	for _, path := range globpaths {
		logoFolders, err := filepath.Glob(path + "/*")
		check(err, context)

		for _, logoFolder := range logoFolders {
			logoFiles, err := filepath.Glob(logoFolder + "/*")
			check(err, context)

			filename := filepath.Base(logoFolder)
			logoImages := make([]image.Image, 0)

			for _, logoFile := range logoFiles {
				//fmt.Fprintf(os.Stderr, "%s\n", logoFile)
				logoData, err := os.Open(logoFile)
				defer logoData.Close()
				check(err, context)

				reader := bufio.NewReader(logoData)
				logoImage, err := png.Decode(reader)
				check(err, context)

				logoImages = append(logoImages, logoImage)
			}

			logoImagesByName[filename] = logoImages

		}
	}

	return logoImagesByName
}
예제 #3
0
파일: func_map.go 프로젝트: kennylixi/qor
func (context *Context) loadActions(action string) template.HTML {
	var actions = map[string]string{}
	var actionKeys = []string{}
	var viewPaths = context.getViewPaths()

	for j := len(viewPaths); j > 0; j-- {
		view := viewPaths[j-1]
		globalfiles, _ := filepath.Glob(path.Join(view, "actions/*.tmpl"))
		files, _ := filepath.Glob(path.Join(view, "actions", action, "*.tmpl"))

		for _, file := range append(globalfiles, files...) {
			if _, ok := actions[path.Base(file)]; !ok {
				actionKeys = append(actionKeys, path.Base(file))
			}
			base := regexp.MustCompile("^\\d+\\.").ReplaceAllString(path.Base(file), "")
			actions[base] = file
		}
	}

	sort.Strings(actionKeys)

	var result = bytes.NewBufferString("")
	for _, key := range actionKeys {
		base := regexp.MustCompile("^\\d+\\.").ReplaceAllString(key, "")
		file := actions[base]
		if tmpl, err := template.New(path.Base(file)).Funcs(context.FuncMap()).ParseFiles(file); err == nil {
			if err := tmpl.Execute(result, context); err != nil {
				panic(err)
			}
		}
	}
	return template.HTML(strings.TrimSpace(result.String()))
}
예제 #4
0
func initTemplates() error {
	if templates == nil {
		templates = make(map[string]*template.Template)
	}

	templatesDir := "./templates/"

	layouts, err := filepath.Glob(templatesDir + "layouts/*.tmpl")

	if err != nil {
		return err
	}

	pages, err := filepath.Glob(templatesDir + "pages/*.tmpl")

	if err != nil {
		return err
	}

	for _, page := range pages {
		files := append(layouts, page)
		filename := filepath.Base(page)

		var err error

		templates[filename], err = template.New(filename).Funcs(template.FuncMap{"osIcon": osIcon}).ParseFiles(files...)

		if err != nil {
			return err
		}
	}

	return nil
}
예제 #5
0
// Run Gzipbeat.
func (gb *Gzipbeat) Run(b *beat.Beat) error {

	// iterate through each config section
	for _, input := range gb.config.Input {

		// list all gzip files in directory
		gzips, _ := filepath.Glob(input.Path)
		if input.Exclude != "" {
			exclude, _ := filepath.Glob(input.Exclude)
			gzips = diff(gzips, exclude)
		}
		gzips = diff(gzips, gb.registry)

		// do 1 file at the time
		for _, filename := range gzips {
			send(gb, filename, &input.Fields)
			err := saveToRegistry(gb, filename)
			if err != nil {
				logp.Err("Error saving to registry file %s: %v", gb.config.Registry, err)
				return err
			}
		}
	}

	return nil
}
예제 #6
0
func (a *analogPin) analogRead() int {
	var err error
	var fi *os.File

	ocp, err := filepath.Glob(Ocp)
	if err != nil {
		panic(err)
	}

	helper, err := filepath.Glob(fmt.Sprintf("%v/helper.*", ocp[0]))
	if err != nil {
		panic(err)
	}

	fi, err = os.Open(fmt.Sprintf("%v/%v", helper[0], a.pinNum))
	if err != nil {
		panic(err)
	}

	var buf = make([]byte, 1024)
	fi.Read(buf)
	fi.Close()

	i, _ := strconv.Atoi(strings.Split(string(buf), "\n")[0])
	return i
}
예제 #7
0
func (s *copydataSuite) TestCopyDataDoIdempotent(c *C) {
	// make sure that a retry wouldn't stumble on partial work

	v1 := snaptest.MockSnap(c, helloYaml1, helloContents, &snap.SideInfo{Revision: snap.R(10)})

	s.populateData(c, snap.R(10))
	homedir := s.populateHomeData(c, "user1", snap.R(10))

	// pretend we install a new version
	v2 := snaptest.MockSnap(c, helloYaml2, helloContents, &snap.SideInfo{Revision: snap.R(20)})

	// copy data
	err := s.be.CopySnapData(v2, v1, &s.nullProgress)
	c.Assert(err, IsNil)

	err = s.be.CopySnapData(v2, v1, &s.nullProgress)
	c.Assert(err, IsNil)

	v2data := filepath.Join(dirs.SnapDataDir, "hello/20")
	l, err := filepath.Glob(filepath.Join(v2data, "*"))
	c.Assert(err, IsNil)
	c.Assert(l, HasLen, 1)
	v2HomeData := filepath.Join(homedir, "hello/20")
	l, err = filepath.Glob(filepath.Join(v2HomeData, "*"))
	c.Assert(err, IsNil)
	c.Assert(l, HasLen, 1)
}
예제 #8
0
파일: group.go 프로젝트: fragmenta/assets
// RemoveFiles removes old compiled files for this group from dst
func (g *Group) RemoveFiles(dst string) error {

	if dst == "" {
		return fmt.Errorf("Empty destination string")
	}

	var assets []string

	pattern := path.Join(dst, "assets", "scripts", g.name+"-*.min.js")
	files, err := filepath.Glob(pattern)
	if err != nil {
		return err
	}

	assets = append(assets, files...)
	pattern = path.Join(dst, "assets", "styles", g.name+"-*.min.css")
	files, err = filepath.Glob(pattern)
	if err != nil {
		return err
	}
	assets = append(assets, files...)

	for _, a := range assets {
		err = os.Remove(a)
		if err != nil {
			return err
		}
	}

	return nil
}
예제 #9
0
// collectGitOrphans deletes all repos in dataPath except the one pointed to by
// a git deployer's "current" symlink.
// Errors are generally ignored; some are logged. If current does not exist, *all*
// repos are orphans, and all will be deleted; this should only be the case when
// converting a gitDeployer to a manifestDeployer.
func collectGitOrphans(dataPath string) {
	current, err := symlink.Read(filepath.Join(dataPath, gitCurrentPath))
	if os.IsNotExist(err) {
		logger.Debugf("no current staging repo")
	} else if err != nil {
		logger.Warningf("cannot read current staging repo: %v", err)
		return
	} else if !filepath.IsAbs(current) {
		current = filepath.Join(dataPath, current)
	}
	orphans, err := filepath.Glob(filepath.Join(dataPath, fmt.Sprintf("%s*", gitUpdatePrefix)))
	if err != nil {
		return
	}
	installOrphans, err := filepath.Glob(filepath.Join(dataPath, fmt.Sprintf("%s*", gitInstallPrefix)))
	if err != nil {
		return
	}
	orphans = append(orphans, installOrphans...)
	for _, repoPath := range orphans {
		if repoPath != dataPath && repoPath != current {
			if err = os.RemoveAll(repoPath); err != nil {
				logger.Warningf("failed to remove orphan repo at %s: %s", repoPath, err)
			}
		}
	}
}
예제 #10
0
파일: cmd_ls.go 프로젝트: kless/easycert
func runLs(cmd *flagplus.Subcommand, args []string) {
	if !*IsCert && !*IsRequest && !*IsKey {
		*IsCert = true
		*IsRequest = true
		*IsKey = true
	}

	if *IsCert {
		match, err := filepath.Glob(filepath.Join(Dir.Cert, "*"+EXT_CERT))
		if err != nil {
			log.Fatal(err)
		}
		printCert(match)
	}
	if *IsRequest {
		match, err := filepath.Glob(filepath.Join(Dir.Root, "*"+EXT_REQUEST))
		if err != nil {
			log.Fatal(err)
		}
		printCert(match)
	}
	if *IsKey {
		match, err := filepath.Glob(filepath.Join(Dir.Key, "*"+EXT_KEY))
		if err != nil {
			log.Fatal(err)
		}
		printCert(match)
	}
}
예제 #11
0
func SendMails(spool string, ss *Settings) {
	ecnt := 0
	files, err := filepath.Glob(spool + "/*.*")
	if err == nil {
		for _, f := range files {
			fn := path.Base(f)
			if strings.HasSuffix(f, ".env") {
				p := strings.Split(fn, "@")
				p = strings.Split(p[0], ".")
				ts, err := strconv.ParseInt(p[0], 36, 64)
				if err == nil {
					if ts+int64(ss.expire) <= time.Now().Unix() {
						ss.Debugf("SendMail: removing obsolete envelope: " + fn)
						purgeMsg(f, ss)
					} else {
						ecnt++
						go sendMail(f, ss)
					}
				} else {
					ss.Logf("RUNERR: invalid envelope: %s", fn)
				}
			} else {
				env, _ := filepath.Glob(f[0:len(f)-4] + "@*.env")
				if len(env) == 0 {
					ss.Debugf("SendMail: removing obsolete message: " + fn)
					purgeMsg(f, ss)
				}
			}
		}
		ss.Debugf("SendMails: queued_messages=%v", ecnt)
	} else {
		ss.Logf("RUNERR: %v", err)
	}
}
예제 #12
0
파일: update.go 프로젝트: dbenoot/stare
func migLanguage(language string) {
	fmt.Println("Migrating!")

	path := filepath.Join(site.pagedir, language)
	templatepath := filepath.Join(site.templatedir, language)
	// err :=
	os.MkdirAll(path, 0755)
	os.MkdirAll(templatepath, 0755)
	// if err != nil {
	//     return err
	// }
	pages, _ := filepath.Glob(site.pagedir + "/*.html")
	for c := 1; c < len(pages); c++ {
		copyfile(pages[c], filepath.Join(path, strings.Split(pages[c], "/")[len(strings.Split(pages[c], "/"))-1]))
		move(pages[c], filepath.Join("archive", pages[c]))
	}

	templates, _ := filepath.Glob(site.templatedir + "/*.html")
	for c := 0; c < len(templates); c++ {
		copyfile(templates[c], filepath.Join(templatepath, strings.Split(templates[c], "/")[len(strings.Split(templates[c], "/"))-1]))
		move(templates[c], filepath.Join("archive", templates[c]))
	}

	cfg.Section("general").NewKey("multiple_language_support", "y")
	cfg.Section("general").NewKey("primary_language", language)
	cfg.Section("general").NewKey("languages", language)
	cfg.SaveTo("config.ini")
}
예제 #13
0
파일: main.go 프로젝트: archeious/ARES
func init() {
	config.ReadConfigFile("settings.yaml")
	//TODO: Error Checking
	basePath, _ := config.GetString("TEMPLATES:BASE")
	layoutsPath, _ := config.GetString("TEMPLATES:LAYOUTS")
	partialsPath, _ := config.GetString("TEMPLATES:PARTIALS")

	dir, _ := os.Getwd()
	templatesPath = filepath.Join(dir, basePath)
	fmt.Printf("Processing templates in %s\n", templatesPath)

	if templates == nil {
		templates = make(map[string]*template.Template)
	}

	layouts, err := filepath.Glob(templatesPath + "/" + layoutsPath + "/*")
	if err != nil {
		log.Fatal(err)
	}

	partials, err := filepath.Glob(templatesPath + "/" + partialsPath + "/*")
	if err != nil {
		log.Fatal(err)
	}

	for _, layout := range layouts {
		files := append(partials, layout)
		templates[filepath.Base(layout)] = template.Must(template.ParseFiles(files...))
	}

	UserRepo = user.NewBaseUserRepository()
	if _, err := UserRepo.NewUser("jeff", "password"); err != nil {
		fmt.Println(err)
	}
}
예제 #14
0
파일: assets.go 프로젝트: fragmenta/assets
// collectAssets collects the assets with this extension under src
func collectAssets(src string, extensions []string) ([]string, error) {

	assets := []string{}

	// TODO: perhaps use filepath.Walk instead
	// filepath.Glob doesn't appear to support ** or {}
	// this should catch
	// src/app/images/img.png
	// src/app/assets/images/img.png
	// src/app/assets/images/group/img.png
	for _, e := range extensions {
		pattern := path.Join(src, "*/*/*."+e)
		files, err := filepath.Glob(pattern)
		if err != nil {
			return assets, err
		}
		assets = append(assets, files...)
		pattern = path.Join(src, "*/*/*/*."+e)
		files, err = filepath.Glob(pattern)
		if err != nil {
			return assets, err
		}
		assets = append(assets, files...)
		pattern = path.Join(src, "*/*/*/*/*."+e)
		files, err = filepath.Glob(pattern)
		if err != nil {
			return assets, err
		}
		assets = append(assets, files...)
	}

	return assets, nil

}
func BenchmarkComplexGolang(b *testing.B) {
	var buf bytes.Buffer

	funcMap := template.FuncMap{
		"safehtml": func(text string) template.HTML { return template.HTML(text) },
	}

	templates := make(map[string]*template.Template)
	templatesDir := "go/"

	layouts, err := filepath.Glob(templatesDir + "layout/*.tmpl")
	if err != nil {
		panic(err)
	}

	includes, err := filepath.Glob(templatesDir + "includes/*.tmpl")
	if err != nil {
		panic(err)
	}

	// Generate our templates map from our layouts/ and includes/ directories
	for _, layout := range layouts {
		files := append(includes, layout)
		templates[filepath.Base(layout)] = template.Must(template.New("").Funcs(funcMap).ParseFiles(files...))
	}
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		templates["index.tmpl"].ExecuteTemplate(&buf, "base", testComplexData)
	}
}
예제 #16
0
파일: render.go 프로젝트: hobo-c/gin_sample
func loadTemplatesDefault(templatesDir string) multitemplate.Render {
	r := multitemplate.New()

	layoutDir := templatesDir + "/layouts/"
	layouts, err := filepath.Glob(layoutDir + "*/*" + conf.TMPL_SUFFIX)
	if err != nil {
		panic(err.Error())
	}

	includeDir := templatesDir + "/includes/"
	includes, err := filepath.Glob(includeDir + "*" + conf.TMPL_SUFFIX)
	if err != nil {
		panic(err.Error())
	}

	// Generate our templates map from our layouts/ and includes/ directories
	for _, layout := range layouts {
		files := append(includes, layout)
		tmpl := template.Must(template.ParseFiles(files...))
		tmplName := strings.TrimPrefix(layout, layoutDir)
		tmplName = strings.TrimSuffix(tmplName, conf.TMPL_SUFFIX)
		log.DebugPrint("Tmpl add " + tmplName)
		r.Add(tmplName, tmpl)
	}
	return r
}
/******************************************************************************
** Go
******************************************************************************/
func TestComplexGolang(t *testing.T) {

	var buf bytes.Buffer

	funcMap := template.FuncMap{
		"safehtml": func(text string) template.HTML { return template.HTML(text) },
	}

	templates := make(map[string]*template.Template)
	templatesDir := "go/"

	layouts, err := filepath.Glob(templatesDir + "layout/*.tmpl")
	if err != nil {
		panic(err)
	}

	includes, err := filepath.Glob(templatesDir + "includes/*.tmpl")
	if err != nil {
		panic(err)
	}

	// Generate our templates map from our layouts/ and includes/ directories
	for _, layout := range layouts {
		files := append(includes, layout)
		templates[filepath.Base(layout)] = template.Must(template.New("").Funcs(funcMap).ParseFiles(files...))
	}
	templates["index.tmpl"].ExecuteTemplate(&buf, "base", testComplexData)

	if msg, ok := linesEquals(buf.String(), expectedtComplexResult); !ok {
		t.Error(msg)
	}
}
예제 #18
0
// Compiles all assembly files matching the specified file glob.
//
// @param match                 The file glob specifying which assembly files
//                                  to compile.
func (c *Compiler) CompileAs() error {
	files, _ := filepath.Glob("*.s")
	Sfiles, _ := filepath.Glob("*.S")
	files = append(files, Sfiles...)

	wd, err := os.Getwd()
	if err != nil {
		return err
	}

	log.Infof("Compiling assembly if outdated (%s/*.s) %s", wd,
		strings.Join(files, " "))
	for _, file := range files {
		if shouldIgnore := c.shouldIgnoreFile(file); shouldIgnore {
			log.Infof("Ignoring %s because package dictates it.", file)
			continue
		}

		compileRequired, err := c.depTracker.CompileRequired(file,
			COMPILER_TYPE_ASM)
		if err != nil {
			return err
		}
		if compileRequired {
			err = c.CompileFile(file, COMPILER_TYPE_ASM)
		} else {
			err = c.SkipSourceFile(file)
		}
		if err != nil {
			return err
		}
	}

	return nil
}
예제 #19
0
func (s *copydataSuite) TestCopyDataDoUndo(c *C) {
	v1 := snaptest.MockSnap(c, helloYaml1, helloContents, &snap.SideInfo{Revision: snap.R(10)})
	s.populateData(c, snap.R(10))
	homedir := s.populateHomeData(c, "user1", snap.R(10))

	// pretend we install a new version
	v2 := snaptest.MockSnap(c, helloYaml2, helloContents, &snap.SideInfo{Revision: snap.R(20)})

	// copy data
	err := s.be.CopySnapData(v2, v1, &s.nullProgress)
	c.Assert(err, IsNil)
	v2data := filepath.Join(dirs.SnapDataDir, "hello/20")
	l, err := filepath.Glob(filepath.Join(v2data, "*"))
	c.Assert(err, IsNil)
	c.Assert(l, HasLen, 1)
	v2HomeData := filepath.Join(homedir, "hello/20")
	l, err = filepath.Glob(filepath.Join(v2HomeData, "*"))
	c.Assert(err, IsNil)
	c.Assert(l, HasLen, 1)

	err = s.be.UndoCopySnapData(v2, v1, &s.nullProgress)
	c.Assert(err, IsNil)

	// now removed
	_, err = os.Stat(v2data)
	c.Assert(os.IsNotExist(err), Equals, true)
	_, err = os.Stat(v2HomeData)
	c.Assert(os.IsNotExist(err), Equals, true)
}
예제 #20
0
// Create goes through the `TemplatesDir` creating the template structure
// for rendering. Returns the Render instance.
func (r *Render) Create() *Render {
	r.Validate()

	layout := r.TemplatesDir + r.Layout + r.Ext

	// root dir
	tplRoot, err := filepath.Glob(r.TemplatesDir + "*" + r.Ext)
	if err != nil {
		panic(err.Error())
	}

	// sub dirs
	tplSub, err := filepath.Glob(r.TemplatesDir + "**/*" + r.Ext)
	if err != nil {
		panic(err.Error())
	}

	for _, tpl := range append(tplRoot, tplSub...) {

		// This check is to prevent `panic: template: redefinition of template "layout"`
		name := r.getTemplateName(tpl)
		if name == r.Layout {
			continue
		}

		r.AddFromFiles(name, layout, tpl)
	}

	return r
}
예제 #21
0
파일: template.go 프로젝트: atamis/wt3
// Load templates on program initialisation
func init() {
	bufpool = bpool.NewBufferPool(64)

	if templates == nil {
		templates = make(map[string]*template.Template)
	}

	templatesDir := config.Config.TemplatePath

	layouts, err := filepath.Glob(templatesDir + "layouts/*.tmpl")
	if err != nil {
		log.Fatal(err)
	}

	includes, err := filepath.Glob(templatesDir + "includes/*.tmpl")
	if err != nil {
		log.Fatal(err)
	}

	// Generate our templates map from our layouts/ and includes/ directories
	for _, layout := range layouts {
		files := append(includes, layout)
		templates[filepath.Base(layout)] = template.Must(template.ParseFiles(files...))
	}

}
예제 #22
0
func (cmd *cmd4cdg) Run(chatID, replyID int, text string, from tg.User, reply_ID *tg.Message) error {
	var (
		err error
	)
	if strings.Contains(text, " rules") {
		_, err = cmd.cli.SendText(chatID, "'4chan drinking card game' rules\n\n1. The left of the phone owner starts.\n2. Players take a card when it's their turn. They must do what the card says.\n3. You win the game when everyone else pass' out.\n\nCard types:\nAction: This is a standard 'do what it says' card.\nInstant: This card may be kept and used at anytime in the game.\nMandatory: Everyone must play this card.\nStatus: This is constant for the whole game or the timeframe indicated on the card.")
		return err
	}
	if len(cmd.f_slice) < 3 {
		cmd.f_slice, err = filepath.Glob(cmd.config.Path + "/*.jpg")
		if cmd.f_slice == nil {
			return err
		}
		temp, err := filepath.Glob(cmd.config.Path + "/*.png") //Cochinada maxima, pero funciona.
		if cmd.f_slice == nil {
			return err
		}
		cmd.f_slice = append(cmd.f_slice, temp...)
		_, err = cmd.cli.SendText(chatID, "Cards shuffled. A new game has begun...")
	}
	rndInt := rand.Intn(len(cmd.f_slice))
	img, err := ioutil.ReadFile(cmd.f_slice[rndInt])
	if err != nil {
		return err
	}
	imgName := strings.Split(cmd.f_slice[rndInt], "/")
	log.Println("SENT -> " + cmd.f_slice[rndInt])
	_, err = cmd.cli.SendPhoto(chatID, tg.File{Name: imgName[len(imgName)-1], Data: img})
	cmd.f_slice = append(cmd.f_slice[:rndInt], cmd.f_slice[rndInt+1:]...)
	return err
}
예제 #23
0
파일: listing.go 프로젝트: jbaikge/alcohol
func initListing(dir string, l *Listing) (err error) {
	l.Products = make([]*Product, 0, 4096)

	// Read in the entire product list, then build from there
	prices, err := filepath.Glob(filepath.Join(dir, "prices", "????-??.csv"))
	sort.Strings(prices)
	discounts, err := filepath.Glob(filepath.Join(dir, "discounts", "????-??.csv"))
	sort.Strings(discounts)
	prices = append(prices, discounts...)
	for _, path := range prices {
		if err = readListing(path, l); err != nil {
			return
		}
	}

	// Remove discontinued products
	for i := 0; i < l.Len(); {
		if p := l.Products[i]; p.delete || p.Type == IgnoreType {
			l.Products = append(l.Products[0:i], l.Products[i+1:]...)
			continue
		}
		i++
	}

	sort.Sort(l)

	return
}
예제 #24
0
파일: zipper.go 프로젝트: jbayer/cli
func exclusionsForPattern(dir string, pattern string) (exclusions []string) {
	starting_dir := dir

	findPatternMatches := func(dir string, f os.FileInfo, inErr error) (err error) {
		err = inErr
		if err != nil {
			return
		}

		absolutePaths := []string{}
		if f.IsDir() && f.Name() == pattern {
			absolutePaths, _ = filepath.Glob(filepath.Join(dir, "*"))
		} else {
			absolutePaths, _ = filepath.Glob(filepath.Join(dir, pattern))
		}

		for _, p := range absolutePaths {
			relpath, _ := filepath.Rel(starting_dir, p)

			exclusions = append(exclusions, relpath)
		}
		return
	}

	err := filepath.Walk(dir, findPatternMatches)
	if err != nil {
		return
	}

	return
}
예제 #25
0
func filePathsFromArgs(args []string) ([]string, error) {
	var output []string
	var err error

	if len(args) == 0 {
		output, err = filepath.Glob("*")
		if err != nil {
			return []string{}, err
		}
	} else {
		for _, arg := range args {
			if strings.Index(arg, "*") < 0 && strings.Index(arg, "?") < 0 {
				output = append(output, arg)
				continue
			}
			matches, err := filepath.Glob(arg)
			if err != nil {
				return []string{}, err
			}
			for _, match := range matches {
				output = append(output, match)
			}
		}
	}

	sort.Strings(output)

	return output, nil
}
예제 #26
0
파일: server.go 프로젝트: henryanand/vitess
func (srv *Server) classPath() ([]string, error) {
	dir := srv.zkDir
	if dir == "" {
		return systemClassPath()
	}
	if err := checkDirectory(dir); err != nil {
		return nil, err
	}
	// Two possibilities, as seen in zkEnv.sh:
	// 1) locally built binaries (jars are in build directory)
	// 2) release binaries
	if build := filepath.Join(dir, "build"); checkDirectory(build) == nil {
		dir = build
	}
	classPath, err := filepath.Glob(filepath.Join(dir, "zookeeper-*.jar"))
	if err != nil {
		panic(fmt.Errorf("glob for jar files: %v", err))
	}
	more, err := filepath.Glob(filepath.Join(dir, "lib/*.jar"))
	if err != nil {
		panic(fmt.Errorf("glob for lib jar files: %v", err))
	}

	classPath = append(classPath, more...)
	if len(classPath) == 0 {
		return nil, fmt.Errorf("zookeeper libraries not found in %q", dir)
	}
	return classPath, nil
}
예제 #27
0
func init() {
	if Map == nil {
		Map = make(map[string]*template.Template)
	}

	templatesDir := "templates/"

	layoutsMain, err := filepath.Glob(templatesDir + "layouts/*.html")
	if err != nil {
		log.Fatal(err)
	}

	layoutsProjects, err := filepath.Glob(templatesDir + "layouts/projects/*.html")
	if err != nil {
		log.Fatal(err)
	}

	layouts := append(layoutsMain, layoutsProjects...)

	includes, err := filepath.Glob(templatesDir + "includes/*.html")
	if err != nil {
		log.Fatal(err)
	}

	for _, layout := range layouts {
		files := append(includes, layout)
		Map[filepath.Base(layout)] = template.Must(template.ParseFiles(files...))
	}
}
예제 #28
0
func DateRangeFs(p string) FsDate {
	years, _ := filepath.Glob(p + "/*")
	minYear := math.MaxInt64
	for _, x := range years {
		res, _ := strconv.Atoi(filepath.Base(x))
		if res < minYear {
			minYear = res
		}
	}

	minYearMonths, _ := filepath.Glob(p + "/" + strconv.Itoa(minYear) + "/*")
	minYearMinMonth := math.MaxInt64
	for _, x := range minYearMonths {
		res, _ := strconv.Atoi(filepath.Base(x))
		if res < minYearMinMonth {
			minYearMinMonth = res
		}
	}

	minMonthDays, _ := filepath.Glob(p + "/" + strconv.Itoa(minYear) + "/" + strconv.Itoa(minYearMinMonth) + "/*")
	minMonthMinDay := math.MaxInt64
	for _, x := range minMonthDays {
		res, _ := strconv.Atoi(filepath.Base(x))
		if res < minMonthMinDay {
			minMonthMinDay = res
		}
	}

	return FsDate{Year: minYear, Month: minYearMinMonth, Day: minMonthMinDay}
}
예제 #29
0
// Run this shell script, but do it in Go so it can be run by "go test".
// 	go build -o testvet
// 	$(GOROOT)/test/errchk ./testvet -shadow -printfuncs='Warn:1,Warnf:1' testdata/*.go testdata/*.s
// 	rm testvet
//
func TestVet(t *testing.T) {
	// Plan 9 and Windows systems can't be guaranteed to have Perl and so can't run errchk.
	switch runtime.GOOS {
	case "plan9", "windows":
		t.Skip("skipping test; no Perl on %q", runtime.GOOS)
	}

	// go build
	cmd := exec.Command("go", "build", "-o", binary)
	run(cmd, t)

	// defer removal of vet
	defer os.Remove(binary)

	// errchk ./testvet
	gos, err := filepath.Glob(filepath.Join(dataDir, "*.go"))
	if err != nil {
		t.Fatal(err)
	}
	asms, err := filepath.Glob(filepath.Join(dataDir, "*.s"))
	if err != nil {
		t.Fatal(err)
	}
	files := append(gos, asms...)
	errchk := filepath.Join(runtime.GOROOT(), "test", "errchk")
	flags := []string{
		"./" + binary,
		"-printfuncs=Warn:1,Warnf:1",
		"-test", // TODO: Delete once -shadow is part of -all.
	}
	cmd = exec.Command(errchk, append(flags, files...)...)
	if !run(cmd, t) {
		t.Fatal("vet command failed")
	}
}
예제 #30
0
func _getFilesToBackup() ([]string, error) {
	const dataDir string = "/var/lib/juju"
	initMachineConfs, err := filepath.Glob("/etc/init/jujud-machine-*.conf")
	if err != nil {
		return nil, fmt.Errorf("failed to fetch machine upstart files: %v", err)
	}
	agentConfs, err := filepath.Glob(filepath.Join(dataDir, "agents", "machine-*"))
	if err != nil {
		return nil, fmt.Errorf("failed to fetch agent configuration files: %v", err)
	}
	jujuLogConfs, err := filepath.Glob("/etc/rsyslog.d/*juju.conf")
	if err != nil {
		return nil, fmt.Errorf("failed to fetch juju log conf files: %v", err)
	}

	backupFiles := []string{
		"/etc/init/juju-db.conf",
		filepath.Join(dataDir, "tools"),
		filepath.Join(dataDir, "server.pem"),
		filepath.Join(dataDir, "system-identity"),
		filepath.Join(dataDir, "nonce.txt"),
		filepath.Join(dataDir, "shared-secret"),
		"/home/ubuntu/.ssh/authorized_keys",
		"/var/log/juju/all-machines.log",
		"/var/log/juju/machine-0.log",
	}
	backupFiles = append(backupFiles, initMachineConfs...)
	backupFiles = append(backupFiles, agentConfs...)
	backupFiles = append(backupFiles, jujuLogConfs...)
	return backupFiles, nil
}