// Install git-hook into current git repo func install(isInstall bool) { dirPath, err := getGitDirPath() if err != nil { logger.Errorln(MESSAGES["NotGitRepo"]) return } if isInstall { isExist, _ := exists(filepath.Join(dirPath, "hooks.old")) if isExist { logger.Errorln(MESSAGES["ExistHooks"]) return } installInto(dirPath, tplPostInstall) } else { isExist, _ := exists(filepath.Join(dirPath, "hooks.old")) if !isExist { logger.Errorln(MESSAGES["NotExistHooks"]) return } os.RemoveAll(filepath.Join(dirPath, "hooks")) os.Rename(filepath.Join(dirPath, "hooks.old"), filepath.Join(dirPath, "hooks")) logger.Infoln(MESSAGES["Restore"]) } }
// Creates a new etcd minion func NewEtcdMinion(name string, cfg etcdclient.Config) Minion { c, err := etcdclient.New(cfg) if err != nil { log.Fatal(err) } kapi := etcdclient.NewKeysAPI(c) id := utils.GenerateUUID(name) rootDir := filepath.Join(EtcdMinionSpace, id.String()) queueDir := filepath.Join(rootDir, "queue") classifierDir := filepath.Join(rootDir, "classifier") logDir := filepath.Join(rootDir, "log") taskQueue := make(chan *task.Task) done := make(chan struct{}) m := &etcdMinion{ name: name, rootDir: rootDir, queueDir: queueDir, classifierDir: classifierDir, logDir: logDir, id: id, kapi: kapi, taskQueue: taskQueue, done: done, } return m }
// TestRunDeviceSymlink checks run with device that follows symlink (#13840) func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) { testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon) if _, err := os.Stat("/dev/zero"); err != nil { c.Skip("Host does not have /dev/zero") } // Create a temporary directory to create symlink tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests") c.Assert(err, checker.IsNil) defer os.RemoveAll(tmpDir) // Create a symbolic link to /dev/zero symZero := filepath.Join(tmpDir, "zero") err = os.Symlink("/dev/zero", symZero) c.Assert(err, checker.IsNil) // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp", // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp". tmpFile := filepath.Join(tmpDir, "temp") err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666) c.Assert(err, checker.IsNil) symFile := filepath.Join(tmpDir, "file") err = os.Symlink(tmpFile, symFile) c.Assert(err, checker.IsNil) // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum") c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23")) // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device. out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum") c.Assert(err, check.NotNil) c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'")) }
// Issue #3960: "ADD src ." hangs func TestAddSingleFileToWorkdir(t *testing.T) { buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd", "SingleFileToWorkdir") f, err := os.OpenFile(filepath.Join(buildDirectory, "test_file"), os.O_CREATE, 0644) if err != nil { t.Fatal(err) } f.Close() buildCmd := exec.Command(dockerBinary, "build", "-t", "testaddimg", ".") buildCmd.Dir = buildDirectory done := make(chan error) go func() { out, exitCode, err := runCommandWithOutput(buildCmd) if err != nil || exitCode != 0 { done <- fmt.Errorf("build failed to complete: %s %v", out, err) return } done <- nil }() select { case <-time.After(5 * time.Second): if err := buildCmd.Process.Kill(); err != nil { fmt.Printf("could not kill build (pid=%d): %v\n", buildCmd.Process.Pid, err) } t.Fatal("build timed out") case err := <-done: if err != nil { t.Fatal(err) } } deleteImages("testaddimg") logDone("build - add single file to workdir") }
// Search looks for the closest valid repository, starting from the current path // of this Repository object. func (repo *Repository) Search() error { // First expand the current path to an absolute form. if path, err := filepath.Abs(repo.path); err == nil { repo.path = path } else { return err } originalPath := repo.path // If we are already given a .git directory, we're done. if repo.IsValid() { return nil } // We're probably in a non-bare repo. Start with that hypothetical path. repo.path = filepath.Join(repo.path, ".git") // Traverse upward until we hit a valid repo or root. for !repo.IsValid() { if repo.path == "/.git" { break } repo.path = filepath.Clean(filepath.Join(repo.path, "..", "..", ".git")) } if repo.IsValid() { return nil } return core.Errorf("Not a git repository (or any of the parent directories): %s", originalPath) }
// mirrorLocalZoneInfo tries to reproduce the /etc/localtime target in stage1/ to satisfy systemd-nspawn func mirrorLocalZoneInfo(root string) { zif, err := os.Readlink(localtimePath) if err != nil { return } // On some systems /etc/localtime is a relative symlink, make it absolute if !filepath.IsAbs(zif) { zif = filepath.Join(filepath.Dir(localtimePath), zif) zif = filepath.Clean(zif) } src, err := os.Open(zif) if err != nil { return } defer src.Close() destp := filepath.Join(common.Stage1RootfsPath(root), zif) if err = os.MkdirAll(filepath.Dir(destp), 0755); err != nil { return } dest, err := os.OpenFile(destp, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return } defer dest.Close() _, _ = io.Copy(dest, src) }
// Stop profiling and output results to a file. Also dump a memory profile. func (pro *Prof) Stop() error { pprof.StopCPUProfile() pro.fd.Close() profileDir := "Profile-" + time.Now().Format("Jan_02_2006-15.04.05") if err := os.Mkdir(profileDir, 0777); err != nil { return err } cpuProfilePath := filepath.Join(profileDir, pro.fname) if err := os.Rename(pro.fname+".tmp", cpuProfilePath); err != nil { return fmt.Errorf("failed to rename tmp file: %s", err) } memProfilePath := filepath.Join(profileDir, pro.fname+".mem") memFile, err := os.Create(memProfilePath) if err != nil { return fmt.Errorf("failed to create mem file: %s", err) } defer memFile.Close() runtime.GC() if err := pprof.WriteHeapProfile(memFile); err != nil { return fmt.Errorf("failed to write heap profile: %s", err) } return nil }
func initDefaultCachePath() string { xdgCache := os.Getenv("XDG_CACHE_HOME") if xdgCache == "" { xdgCache = filepath.Join(os.Getenv("HOME"), ".cache") } return filepath.Join(xdgCache, "bashbrew") }
func (bdeb *DebWriter) Build(tempDir, destDir string) error { wtr, err := os.Create(filepath.Join(destDir, bdeb.Filename)) if err != nil { return err } defer wtr.Close() aw := ar.NewWriter(wtr) err = bdeb.writeBytes(aw, "debian-binary", []byte(bdeb.DebianBinaryVersion+"\n")) if err != nil { return fmt.Errorf("Error writing debian-binary into .ar archive: %v", err) } err = bdeb.writeFromFile(aw, filepath.Join(tempDir, bdeb.ControlArchive)) if err != nil { return fmt.Errorf("Error writing control archive into .ar archive: %v", err) } err = bdeb.writeFromFile(aw, filepath.Join(tempDir, bdeb.DataArchive)) if err != nil { return fmt.Errorf("Error writing data archive into .ar archive: %v", err) } err = aw.Close() if err != nil { return fmt.Errorf("Error closing .ar archive: %v", err) } return nil }
func (b *Builder) buildHash(hash string) error { log.Println(b.name, "building", hash) // create place in which to do work workpath := filepath.Join(*buildroot, b.name+"-"+hash[:12]) if err := os.Mkdir(workpath, mkdirPerm); err != nil { return err } defer removePath(workpath) buildLog, runTime, err := b.buildRepoOnHash(workpath, hash, b.buildCmd()) if err != nil { // record failure return b.recordResult(false, "", hash, "", buildLog, runTime) } // record success if err = b.recordResult(true, "", hash, "", "", runTime); err != nil { return fmt.Errorf("recordResult: %s", err) } // build sub-repositories goRoot := filepath.Join(workpath, *buildTool) goPath := workpath b.buildSubrepos(goRoot, goPath, hash) return nil }
func initDefaultConfigPath() string { xdgConfig := os.Getenv("XDG_CONFIG_HOME") if xdgConfig == "" { xdgConfig = filepath.Join(os.Getenv("HOME"), ".config") } return filepath.Join(xdgConfig, "bashbrew") }
func TestCopyFileWithTarSrcFile(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := filepath.Join(folder, "dest") srcFolder := filepath.Join(folder, "src") src := filepath.Join(folder, filepath.Join("src", "src")) err = os.MkdirAll(srcFolder, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } ioutil.WriteFile(src, []byte("content"), 0777) err = CopyWithTar(src, dest+"/") if err != nil { t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err) } _, err = os.Stat(dest) if err != nil { t.Fatalf("Destination folder should contain the source file but did not.") } }
// Do the same test as above but with the destination as file, it should fail func TestUntarPathWithDestinationFile(t *testing.T) { tmpFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpFolder) srcFile := filepath.Join(tmpFolder, "src") tarFile := filepath.Join(tmpFolder, "src.tar") os.Create(filepath.Join(tmpFolder, "src")) // Translate back to Unix semantics as next exec.Command is run under sh srcFileU := srcFile tarFileU := tarFile if runtime.GOOS == "windows" { tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar" srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src" } cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } destFile := filepath.Join(tmpFolder, "dest") _, err = os.Create(destFile) if err != nil { t.Fatalf("Fail to create the destination file") } err = UntarPath(tarFile, destFile) if err == nil { t.Fatalf("UntarPath should throw an error if the destination if a file") } }
func TestUntarPathWithInvalidDest(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) invalidDestFolder := filepath.Join(tempFolder, "invalidDest") // Create a src file srcFile := filepath.Join(tempFolder, "src") tarFile := filepath.Join(tempFolder, "src.tar") os.Create(srcFile) os.Create(invalidDestFolder) // being a file (not dir) should cause an error // Translate back to Unix semantics as next exec.Command is run under sh srcFileU := srcFile tarFileU := tarFile if runtime.GOOS == "windows" { tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar" srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src" } cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } err = UntarPath(tarFile, invalidDestFolder) if err == nil { t.Fatalf("UntarPath with invalid destination path should throw an error.") } }
// getCertPaths returns the cert paths // codegangsta/cli will not set the cert paths if the storage-path // is set to something different so we cannot use the paths // in the global options. le sigh. func getCertPathInfo(c *cli.Context) libmachine.CertPathInfo { // setup cert paths caCertPath := c.GlobalString("tls-ca-cert") caKeyPath := c.GlobalString("tls-ca-key") clientCertPath := c.GlobalString("tls-client-cert") clientKeyPath := c.GlobalString("tls-client-key") if caCertPath == "" { caCertPath = filepath.Join(utils.GetMachineCertDir(), "ca.pem") } if caKeyPath == "" { caKeyPath = filepath.Join(utils.GetMachineCertDir(), "ca-key.pem") } if clientCertPath == "" { clientCertPath = filepath.Join(utils.GetMachineCertDir(), "cert.pem") } if clientKeyPath == "" { clientKeyPath = filepath.Join(utils.GetMachineCertDir(), "key.pem") } return libmachine.CertPathInfo{ CaCertPath: caCertPath, CaKeyPath: caKeyPath, ClientCertPath: clientCertPath, ClientKeyPath: clientKeyPath, } }
// buildBenchmark builds the benchmark binary. func (b *Builder) buildBenchmark(workpath string, update bool) (benchBin, log string, err error) { goroot := filepath.Join(workpath, "go") gobin := filepath.Join(goroot, "bin", "go") + exeExt gopath := filepath.Join(*buildroot, "gopath") env := append([]string{ "GOROOT=" + goroot, "GOPATH=" + gopath}, b.envv()...) // First, download without installing. args := []string{"get", "-d"} if update { args = append(args, "-u") } args = append(args, *benchPath) var buildlog bytes.Buffer runOpts := []runOpt{runTimeout(*buildTimeout), runEnv(env), allOutput(&buildlog), runDir(workpath)} err = run(exec.Command(gobin, args...), runOpts...) if err != nil { fmt.Fprintf(&buildlog, "go get -d %s failed: %s", *benchPath, err) return "", buildlog.String(), err } // Then, build into workpath. benchBin = filepath.Join(workpath, "benchbin") + exeExt args = []string{"build", "-o", benchBin, *benchPath} buildlog.Reset() err = run(exec.Command(gobin, args...), runOpts...) if err != nil { fmt.Fprintf(&buildlog, "go build %s failed: %s", *benchPath, err) return "", buildlog.String(), err } return benchBin, "", nil }
// NAME // test-mysql - check data generated from ModSQL into a MySQL database // // DESCRIPTION // // To create the database: // // mysql -p // mysql> create database modsql_test; // mysql> GRANT ALL PRIVILEGES ON modsql_test.* to USER@localhost; // // Note: substitute "USER" by your user name. // // To remove it: // // mysql> drop database modsql_test; func TaskTestMySQL(t *tasking.T) { // Format used in "github.com/serbaut/go-mysql" //db, err := sql.Open("mysql", fmt.Sprintf("mysql://%s@(unix)/%s?socket=%s", //username, dbname, host.mysql)) db, err := sql.Open("mysql", fmt.Sprintf("%s@unix(%s)/%s?parseTime=true", username, host.mysql, dbname)) if err != nil { t.Fatal(err) } if err = modsql.Load(db, filepath.Join("data", "sql", "mysql_init.sql")); err != nil { t.Error(err) } else { if err = modsql.Load(db, filepath.Join("data", "sql", "mysql_test.sql")); err != nil { t.Error(err) } testInsert(t, db, modsql.MySQL) if err = modsql.Load(db, filepath.Join("data", "sql", "mysql_drop.sql")); err != nil { t.Error(err) } } db.Close() if !t.Failed() { t.Log("--- PASS") } }
func init() { registerCommand(&cmd.Command{ Name: "doc", UsageLine: `doc <pkg> <sym>[.<method>]`, Short: "show documentation for a package or symbol", Long: ` Doc shows documentation for a package or symbol. See 'go help doc'. `, Run: func(ctx *gb.Context, args []string) error { env := cmd.MergeEnv(os.Environ(), map[string]string{ "GOPATH": fmt.Sprintf("%s:%s", ctx.Projectdir(), filepath.Join(ctx.Projectdir(), "vendor")), }) if len(args) == 0 { args = append(args, ".") } args = append([]string{filepath.Join(ctx.Context.GOROOT, "bin", "godoc")}, args...) cmd := exec.Cmd{ Path: args[0], Args: args, Env: env, Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, } return cmd.Run() }, ParseArgs: func(_ *gb.Context, _ string, args []string) []string { return args }, }) }
func (s *charmsSuite) TestGetUsesCache(c *gc.C) { // Add a fake charm archive in the cache directory. cacheDir := filepath.Join(s.DataDir(), "charm-get-cache") err := os.MkdirAll(cacheDir, 0755) c.Assert(err, jc.ErrorIsNil) // Create and save a bundle in it. charmDir := testcharms.Repo.ClonedDir(c.MkDir(), "dummy") testPath := filepath.Join(charmDir.Path, "utils.js") contents := "// blah blah" err = ioutil.WriteFile(testPath, []byte(contents), 0755) c.Assert(err, jc.ErrorIsNil) var buffer bytes.Buffer err = charmDir.ArchiveTo(&buffer) c.Assert(err, jc.ErrorIsNil) charmArchivePath := filepath.Join( cacheDir, charm.Quote("local:trusty/django-42")+".zip") err = ioutil.WriteFile(charmArchivePath, buffer.Bytes(), 0644) c.Assert(err, jc.ErrorIsNil) // Ensure the cached contents are properly retrieved. uri := s.charmsURI(c, "?url=local:trusty/django-42&file=utils.js") resp, err := s.authRequest(c, "GET", uri, "", nil) c.Assert(err, jc.ErrorIsNil) s.assertGetFileResponse(c, resp, contents, "application/javascript") }
// copies a user's config file from user's home directory to the equivalent // location in the chroot func copyUserConfigFile(source, chroot string) error { userInfo, err := user.Current() if err != nil { return err } sourcepath := filepath.Join(userInfo.HomeDir, source) if _, err := os.Stat(sourcepath); err != nil { return nil } chrootHome := filepath.Join(chroot, "home", userInfo.Username) sourceDir := filepath.Dir(source) if sourceDir != "." { if err := os.MkdirAll( filepath.Join(chrootHome, sourceDir), 0700); err != nil { return err } } tartgetpath := filepath.Join(chrootHome, source) if err := system.CopyRegularFile(sourcepath, tartgetpath); err != nil { return err } return nil }
func TestBuildCacheADD(t *testing.T) { buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildCacheADD", "1") buildCmd := exec.Command(dockerBinary, "build", "-t", "testcacheadd1", ".") buildCmd.Dir = buildDirectory exitCode, err := runCommand(buildCmd) errorOut(err, t, fmt.Sprintf("build failed to complete: %v", err)) if err != nil || exitCode != 0 { t.Fatal("failed to build the image") } buildDirectory = filepath.Join(workingDirectory, "build_tests", "TestBuildCacheADD", "2") buildCmd = exec.Command(dockerBinary, "build", "-t", "testcacheadd2", ".") buildCmd.Dir = buildDirectory out, exitCode, err := runCommandWithOutput(buildCmd) errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err)) if err != nil || exitCode != 0 { t.Fatal("failed to build the image") } if strings.Contains(out, "Using cache") { t.Fatal("2nd build used cache on ADD, it shouldn't") } deleteImages("testcacheadd1") deleteImages("testcacheadd2") logDone("build - build two images with ADD") }
// SetupTestPackage sets up the test package with binaries k8s required for node conformance test func (c *ConformanceRemote) SetupTestPackage(tardir string) error { // Build the executables if err := builder.BuildGo(); err != nil { return fmt.Errorf("failed to build the depedencies: %v", err) } // Make sure we can find the newly built binaries buildOutputDir, err := builder.GetK8sBuildOutputDir() if err != nil { return fmt.Errorf("failed to locate kubernetes build output directory %v", err) } // Build node conformance tarball. if err := buildConformanceTest(buildOutputDir); err != nil { return fmt.Errorf("failed to build node conformance test %v", err) } // Copy files requiredFiles := []string{"kubelet", conformanceTestBinary, conformanceTarfile} for _, file := range requiredFiles { source := filepath.Join(buildOutputDir, file) if _, err := os.Stat(source); err != nil { return fmt.Errorf("failed to locate test file %s: %v", file, err) } output, err := exec.Command("cp", source, filepath.Join(tardir, file)).CombinedOutput() if err != nil { return fmt.Errorf("failed to copy %q: error - %v output - %q", file, err, output) } } return nil }
func (i *installer) run(scripts []string, dstDir string) []api.InstallResult { var userResults, sourceResults, defaultResults map[string]*downloadResult // get scripts from user provided URL if i.scriptsURL != "" { userResults = i.download(i.scriptsURL, scripts, filepath.Join(dstDir, api.UserScripts)) } // get scripts from source sourceResults = make(map[string]*downloadResult, len(scripts)) for _, script := range scripts { sourceResults[script] = &downloadResult{location: api.SourceScripts} file := filepath.Join(dstDir, api.SourceScripts, script) if !i.fs.Exists(file) { sourceResults[script].err = errors.NewDownloadError(file, -1) } } // get scripts from default URL defaultURL, err := i.docker.GetScriptsURL(i.image) if err == nil && defaultURL != "" { defaultResults = i.download(defaultURL, scripts, filepath.Join(dstDir, api.DefaultScripts)) } return i.install(scripts, userResults, sourceResults, defaultResults, dstDir) }
// 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") } }
func (ss *StoreServer) createVolumeHandler(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } var volIDIP VolumeIDIP if err = json.Unmarshal(body, &volIDIP); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } id := volIDIP.ID volIDStr := fmt.Sprintf("%d", id) volPath := filepath.Join(ss.volumeDir, volIDStr+".vol") needleMapPath := filepath.Join(ss.volumeDir, fmt.Sprintf("needle_map_vol%d", id)) file, err := os.OpenFile(volPath, os.O_RDWR|os.O_CREATE, 0644) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } v, err := storage.NewVolume(id, file, needleMapPath, ss.garbageThreshold) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } ss.localVolIDIPs = append(ss.localVolIDIPs, volIDIP) bytes, err := json.Marshal(ss.localVolIDIPs) if err = ioutil.WriteFile(filepath.Join(ss.volumeDir, "volIDIPs.json"), bytes, 0644); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } ss.volumeMap[id] = v }
// TestTags verifies that the -tags argument controls which files to check. func TestTags(t *testing.T) { // go build cmd := exec.Command("go", "build", "-o", binary) run(cmd, t) // defer removal of vet defer os.Remove(binary) args := []string{ "-tags=testtag", "-v", // We're going to look at the files it examines. "testdata/tagtest", } cmd = exec.Command("./"+binary, args...) output, err := cmd.CombinedOutput() if err != nil { t.Fatal(err) } // file1 has testtag and file2 has !testtag. if !bytes.Contains(output, []byte(filepath.Join("tagtest", "file1.go"))) { t.Error("file1 was excluded, should be included") } if bytes.Contains(output, []byte(filepath.Join("tagtest", "file2.go"))) { t.Error("file2 was included, should be excluded") } }
func lintChart(path string) (support.Linter, error) { var chartPath string linter := support.Linter{} if strings.HasSuffix(path, ".tgz") { tempDir, err := ioutil.TempDir("", "helm-lint") if err != nil { return linter, err } defer os.RemoveAll(tempDir) file, err := os.Open(path) if err != nil { return linter, err } defer file.Close() if err = chartutil.Expand(tempDir, file); err != nil { return linter, err } base := strings.Split(filepath.Base(path), "-")[0] chartPath = filepath.Join(tempDir, base) } else { chartPath = path } // Guard: Error out of this is not a chart. if _, err := os.Stat(filepath.Join(chartPath, "Chart.yaml")); err != nil { return linter, errLintNoChart } return lint.All(chartPath), nil }
// CleanDir removes binary files under rundir in case they were not // accessed for more than CleanFileDelay nanoseconds. A last-cleaned // marker file is created so that the next verification is only done // after CleanFileDelay nanoseconds. func CleanDir(rundir string, now int64) os.Error { cleanedfile := filepath.Join(rundir, "last-cleaned") if info, err := os.Stat(cleanedfile); err == nil && info.Mtime_ns > now-CleanFileDelay { // It's been cleaned recently. return nil } f, err := os.Create(cleanedfile) if err != nil { return err } _, err = f.Write([]byte(strconv.Itoa64(now))) f.Close() if err != nil { return err } // Look for expired files. d, err := os.Open(rundir) if err != nil { return err } infos, err := d.Readdir(-1) expired := now - CleanFileDelay for _, info := range infos { if info.Atime_ns < expired { os.Remove(filepath.Join(rundir, info.Name)) } } return nil }
func (w *Watcher) Watch(oom_cb func(count int64)) error { events, err := eventfd.NewEventFD() if err != nil { return err } defer events.Close() oom_control, err := os.Open(filepath.Join( w.cgroup_path, "memory.oom_control")) if err != nil { return err } defer oom_control.Close() event_control, err := os.OpenFile(filepath.Join( w.cgroup_path, "cgroup.event_control"), os.O_WRONLY, 0666) if err != nil { return err } _, err = fmt.Fprintf(event_control, "%d %d\n", events.Fd(), oom_control.Fd()) event_control.Close() if err != nil { return err } for { count, err := events.ReadEvents() if err != nil { return err } oom_cb(count) } }
func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) { dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir) list, err := ioutil.ReadDir(dirname) if err != nil { t.Errorf("testDir(%s): %s", dirname, err) } for _, f := range list { if time.Now().After(endTime) { t.Log("testing time used up") return } switch { case !f.IsDir(): // try extensions for _, ext := range pkgExts { if strings.HasSuffix(f.Name(), ext) { name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension if testPath(t, filepath.Join(dir, name)) { nimports++ } } } case f.IsDir(): nimports += testDir(t, filepath.Join(dir, f.Name()), endTime) } } return }