func (mfs mapFS) ReadDir(p string) ([]os.FileInfo, error) { mfs.mu.RLock() defer mfs.mu.RUnlock() // proxy mapfs.mapFS.ReadDir to not return errors for empty directories // created with Mkdir p = slash(p) fis, err := mfs.FileSystem.ReadDir(p) if os.IsNotExist(err) { _, ok := mfs.dirs[p] if ok { // return a list of subdirs and files (the underlying ReadDir impl // fails here because it thinks the directories don't exist). fis = nil for dir, _ := range mfs.dirs { if (p != "/" && filepath.Dir(dir) == p) || (p == "/" && filepath.Dir(dir) == "." && dir != "." && dir != "") { fis = append(fis, newDirInfo(dir)) } } for fn, b := range mfs.m { if slashdir(fn) == "/"+p { fis = append(fis, newFileInfo(fn, b)) } } return fis, nil } } return fis, err }
func (imp Importer) importSearchFromVisualization(file string) error { type record struct { Title string `json:"title"` SavedSearchID string `json:"savedSearchId"` } reader, err := ioutil.ReadFile(file) if err != nil { return nil } var jsonContent record json.Unmarshal(reader, &jsonContent) id := jsonContent.SavedSearchID if len(id) == 0 { // no search used return nil } // directory with the visualizations dir := filepath.Dir(file) // main directory mainDir := filepath.Dir(dir) searchFile := path.Join(mainDir, "search", id+".json") if searchFile != "" { // visualization depends on search if err := imp.ImportSearch(searchFile); err != nil { return err } } return nil }
// 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) }
// ResolveLocalPaths resolves all relative paths in the config object with respect to the stanza's LocationOfOrigin // this cannot be done directly inside of LoadFromFile because doing so there would make it impossible to load a file without // modification of its contents. func ResolveLocalPaths(config *clientcmdapi.Config) error { for _, cluster := range config.Clusters { if len(cluster.LocationOfOrigin) == 0 { continue } base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin)) if err != nil { return fmt.Errorf("Could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err) } if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil { return err } } for _, authInfo := range config.AuthInfos { if len(authInfo.LocationOfOrigin) == 0 { continue } base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin)) if err != nil { return fmt.Errorf("Could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err) } if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil { return err } } return nil }
// 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") } }
// AddSnapServices adds service units for the applications from the snap which are services. func AddSnapServices(s *snap.Info, inter interacter) error { for _, app := range s.Apps { if app.Daemon == "" { continue } // Generate service file content, err := generateSnapServiceFile(app) if err != nil { return err } svcFilePath := app.ServiceFile() os.MkdirAll(filepath.Dir(svcFilePath), 0755) if err := osutil.AtomicWriteFile(svcFilePath, []byte(content), 0644, 0); err != nil { return err } // Generate systemd socket file if needed if app.Socket { content, err := generateSnapSocketFile(app) if err != nil { return err } svcSocketFilePath := app.ServiceSocketFile() os.MkdirAll(filepath.Dir(svcSocketFilePath), 0755) if err := osutil.AtomicWriteFile(svcSocketFilePath, []byte(content), 0644, 0); err != nil { return err } } } return nil }
// Gets meta type and name based on a path func getMetaForPath(path string) (metaName string, objectName string) { parentDir := filepath.Dir(path) parentName := filepath.Base(parentDir) grandparentName := filepath.Base(filepath.Dir(parentDir)) fileName := filepath.Base(path) for _, mp := range metapaths { if mp.hasFolder && grandparentName == mp.path { metaName = mp.name if mp.onlyFolder { objectName = parentName } else { objectName = parentName + "/" + fileName } return } if mp.path == parentName { metaName = mp.name objectName = fileName return } } // Unknown, so use path metaName = parentName objectName = fileName return }
// Open is part of the intents.file interface. realBSONFiles need to have Open called before // Read can be called func (f *realBSONFile) Open() (err error) { if f.path == "" { // This should not occur normally. All realBSONFile's should have a path return fmt.Errorf("error creating BSON file without a path, namespace: %v", f.intent.Namespace()) } err = os.MkdirAll(filepath.Dir(f.path), os.ModeDir|os.ModePerm) if err != nil { return fmt.Errorf("error creating directory for BSON file %v: %v", filepath.Dir(f.path), err) } fileName := f.path file, err := os.Create(fileName) if err != nil { return fmt.Errorf("error creating BSON file %v: %v", fileName, err) } var writeCloser io.WriteCloser if f.gzip { writeCloser = gzip.NewWriter(file) } else { // wrap writer in buffer to reduce load on disk writeCloser = writeFlushCloser{ atomicFlusher{ bufio.NewWriterSize(file, 32*1024), }, } } f.WriteCloser = &wrappedWriteCloser{ WriteCloser: writeCloser, inner: file, } return nil }
func expandPaths(paths []string) []string { if len(paths) == 0 { paths = []string{"."} } dirs := map[string]bool{} for _, path := range paths { if strings.HasSuffix(path, "/...") { root := filepath.Dir(path) _ = filepath.Walk(root, func(p string, i os.FileInfo, err error) error { kingpin.FatalIfError(err, "invalid path '"+p+"'") base := filepath.Base(p) skip := strings.ContainsAny(base[0:1], "_.") && base != "." && base != ".." if i.IsDir() { if skip { return filepath.SkipDir } } else if !skip && strings.HasSuffix(p, ".go") { dirs[filepath.Clean(filepath.Dir(p))] = true } return nil }) } else { dirs[filepath.Clean(path)] = true } } out := make([]string, 0, len(dirs)) for d := range dirs { out = append(out, d) } return out }
func (context *ExecutionContext) FetchInputDocument(loc string, relativeToSource bool) (doc *xml.XmlDocument) { //create the map if needed if context.InputDocuments == nil { context.InputDocuments = make(map[string]*xml.XmlDocument) } // rely on caller to tell us how to resolve relative paths base := "" if relativeToSource { base, _ = filepath.Abs(filepath.Dir(context.Source.Uri())) } else { base, _ = filepath.Abs(filepath.Dir(context.Style.Doc.Uri())) } resolvedLoc := filepath.Join(base, loc) //if abspath in map return existing document doc, ok := context.InputDocuments[resolvedLoc] if ok { return } //else load the document and add to map doc, e := xml.ReadFile(resolvedLoc, xml.StrictParseOption) if e != nil { fmt.Println(e) return } context.InputDocuments[resolvedLoc] = doc return }
func TestExecutableMatch(t *testing.T) { ep, err := GetCurrentExecutePath() if err != nil { t.Fatalf("Executable failed: %v", err) } // fullpath to be of the form "dir/prog". dir := filepath.Dir(filepath.Dir(ep)) fullpath, err := filepath.Rel(dir, ep) if err != nil { t.Fatalf("filepath.Rel: %v", err) } // Make child start with a relative program path. // Alter argv[0] for child to verify getting real path without argv[0]. cmd := &exec.Cmd{ Dir: dir, Path: fullpath, Env: []string{fmt.Sprintf("%s=%s", executableEnvVar, executableEnvValueMatch)}, } out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("exec(self) failed: %v", err) } outs := string(out) if !filepath.IsAbs(outs) { t.Fatalf("Child returned %q, want an absolute path", out) } if !sameFile(outs, ep) { t.Fatalf("Child returned %q, not the same file as %q", out, ep) } }
// UpdateFile downloads a file to temp dir and replaces the file only if // contents have changed. If tempDir is "" default will be os.TempDir(). func UpdateFile(file, url string) error { if err := os.MkdirAll(filepath.Dir(file), 0777); err != nil { return err } t, err := ioutil.TempFile(filepath.Dir(file), "sdkUpdateCheck") if err != nil { return err } t.Close() tempFile := t.Name() defer os.Remove(tempFile) if err := DownloadFile(tempFile, url); err != nil { return err } equal, err := cmpFileBytes(file, tempFile) if os.IsExist(err) { // file may not exist, that is ok return err } if equal { plog.Infof("%v is up to date", file) return nil } // not equal so delete any existing file and rename tempFile to file if err := os.Rename(tempFile, file); err != nil { return err } return nil }
func winInstaller(buildos, buildarch, dir string, buildMatrix map[string]Release) error { cmd := exec.Command("cp", "script/install.bat.example", filepath.Join(dir, "install.bat")) if err := logAndRun(cmd); err != nil { return err } installerPath := filepath.Dir(filepath.Dir(dir)) name := zipName(buildos, buildarch) + ".zip" full := filepath.Join(installerPath, name) matches, err := filepath.Glob(dir + "/*") if err != nil { return err } addToMatrix(buildMatrix, buildos, buildarch, name) args := make([]string, len(matches)+2) args[0] = "-j" // junk the zip paths args[1] = full copy(args[2:], matches) cmd = exec.Command("zip", args...) return logAndRun(cmd) }
func parseConfig() *viper.Viper { if verbose { logrus.SetLevel(logrus.DebugLevel) logrus.SetOutput(os.Stderr) } // Get home directory for current user homeDir, err := homedir.Dir() if err != nil { fatalf("Cannot get current user home directory: %v", err) } if homeDir == "" { fatalf("Cannot get current user home directory") } // By default our trust directory (where keys are stored) is in ~/.notary/ mainViper.SetDefault("trust_dir", filepath.Join(homeDir, filepath.Dir(configDir))) // If there was a commandline configFile set, we parse that. // If there wasn't we attempt to find it on the default location ~/.notary/config if configFile != "" { configFileExt = strings.TrimPrefix(filepath.Ext(configFile), ".") configFileName = strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile)) configPath = filepath.Dir(configFile) } else { configPath = filepath.Join(homeDir, filepath.Dir(configDir)) } // Setup the configuration details into viper mainViper.SetConfigName(configFileName) mainViper.SetConfigType(configFileExt) mainViper.AddConfigPath(configPath) // Find and read the config file err = mainViper.ReadInConfig() if err != nil { logrus.Debugf("Configuration file not found, using defaults") // If we were passed in a configFile via -c, bail if it doesn't exist, // otherwise ignore it: we can use the defaults if configFile != "" || !os.IsNotExist(err) { fatalf("error opening config file %v", err) } } // At this point we either have the default value or the one set by the config. // Either way, the command-line flag has precedence and overwrites the value if trustDir != "" { mainViper.Set("trust_dir", trustDir) } // Expands all the possible ~/ that have been given, either through -d or config // If there is no error, use it, if not, attempt to use whatever the user gave us expandedTrustDir, err := homedir.Expand(mainViper.GetString("trust_dir")) if err == nil { mainViper.Set("trust_dir", expandedTrustDir) } logrus.Debugf("Using the following trust directory: %s", mainViper.GetString("trust_dir")) return mainViper }
func TestStepTempDir_notmpdir(t *testing.T) { tempenv := "TMPDIR" if runtime.GOOS == "windows" { tempenv = "TMP" } // Verify empty TMPDIR maps to current working directory oldenv := os.Getenv(tempenv) os.Setenv(tempenv, "") defer os.Setenv(tempenv, oldenv) dir1 := testStepTempDir_impl(t) // Now set TMPDIR to current directory abspath, err := filepath.Abs(".") if err != nil { t.Fatalf("could not get current working directory") } os.Setenv(tempenv, abspath) dir2 := testStepTempDir_impl(t) if filepath.Dir(dir1) != filepath.Dir(dir2) { t.Fatalf("temp base directories do not match: %s %s", filepath.Dir(dir1), filepath.Dir(dir2)) } }
// ContainerSnapshotRename renames a snapshot of a container. func (s *storageBtrfs) ContainerSnapshotRename( snapshotContainer container, newName string) error { oldPath := snapshotContainer.Path() newPath := containerPath(newName, true) // Create the new parent. if !shared.PathExists(filepath.Dir(newPath)) { os.MkdirAll(filepath.Dir(newPath), 0700) } // Now rename the snapshot. if !s.isSubvolume(oldPath) { if err := os.Rename(oldPath, newPath); err != nil { return err } } else { if err := s.subvolsSnapshot(oldPath, newPath, true); err != nil { return err } if err := s.subvolsDelete(oldPath); err != nil { return err } } // Remove the old parent (on container rename) if its empty. if ok, _ := shared.PathIsEmpty(filepath.Dir(oldPath)); ok { os.Remove(filepath.Dir(oldPath)) } return nil }
func winInstaller(textfiles []string, buildos, buildarch, dir string, buildMatrix map[string]Release) error { for _, filename := range textfiles { by, err := ioutil.ReadFile(filename) if err != nil { return err } winEndings := strings.Replace(string(by), "\n", "\r\n", -1) err = ioutil.WriteFile(filepath.Join(dir, filename), []byte(winEndings), 0644) if err != nil { return err } } installerPath := filepath.Dir(filepath.Dir(dir)) name := zipName(buildos, buildarch) + ".zip" full := filepath.Join(installerPath, name) matches, err := filepath.Glob(dir + "/*") if err != nil { return err } addToMatrix(buildMatrix, buildos, buildarch, name) args := make([]string, len(matches)+2) args[0] = "-j" // junk the zip paths args[1] = full copy(args[2:], matches) cmd := exec.Command("zip", args...) return logAndRun(cmd) }
// LoadConfig reads the configuration from the config path; if the path does // not exist, it returns a default configuration. func LoadConfig(path string) (*Config, error) { data, err := ioutil.ReadFile(path) if os.IsNotExist(err) { // A missing file is equivalent to the default configuration. withPath := DefaultConfig withPath.ConfigDir = filepath.Dir(path) return &withPath, nil } if err != nil { return nil, fmt.Errorf("cannot read config file: %v", err) } var c Config err = yaml.Unmarshal(data, &c) if err != nil { return nil, fmt.Errorf("cannot parse configuration: %v", err) } if c.Remotes == nil { c.Remotes = make(map[string]RemoteConfig) } c.ConfigDir = filepath.Dir(path) for k, v := range StaticRemotes { c.Remotes[k] = v } return &c, nil }
func copyDir(src, dst string) error { // ensure the parent path of the src exists if err := os.MkdirAll(filepath.Dir(src), 0777); err != nil { log.Errorf("Error when creating parent directory for src: %s", err.Error()) return err } // ensure the parent path of the dst exists cmd := exec.Command("mkdir", "-p", filepath.Dir(dst)) out, err := cmd.Output() if err != nil { return err } // cp options: // -a: preserve attributes // -r: copy recursively cmd = exec.Command("cp", "-aR", src, dst) out, err = cmd.CombinedOutput() if err != nil { log.Errorf("Error when cp: %s", err.Error()) return err } log.Printf("The cp output is: %s", out) return nil }
func findSgovendoredPkgs(whence string, sgovendored map[string]func() (*annotations.Annotation, error)) error { dirPath, err := filepath.Abs(whence) if err != nil { return err } annPaths := map[string]string{} for { dir, err := os.Open(dirPath) if err != nil { return err } fileNames, err := dir.Readdirnames(-1) dir.Close() if err != nil { return err } for _, sgovendorPath := range fileNames { if sgovendorPath != "sgovendor" { continue } sgovendorPath = filepath.Join(dirPath, sgovendorPath) info, err := os.Lstat(sgovendorPath) if err != nil { return err } if !info.IsDir() { continue } filepath.Walk(sgovendorPath, func(path string, info os.FileInfo, err error) error { if info.IsDir() || filepath.Ext(path) != ".sgoann" { return nil } pkgPath := filepath.Dir(path[len(sgovendorPath)+1:]) if _, ok := annPaths[pkgPath]; ok { return nil } annPaths[pkgPath] = filepath.Dir(path) return nil }) } nextDirPath := filepath.Dir(dirPath) if nextDirPath == dirPath { break } dirPath = nextDirPath } for pkgPath, dirPath := range annPaths { pkgPath, dirPath := pkgPath, dirPath sgovendored[pkgPath] = func() (*annotations.Annotation, error) { return readSgovendorDir(dirPath) } } return nil }
func (t *Tombstoner) writeTombstone(tombstones []string) error { tmp, err := ioutil.TempFile(filepath.Dir(t.Path), "tombstone") if err != nil { return err } defer tmp.Close() if _, err := tmp.Write([]byte(strings.Join(tombstones, "\n"))); err != nil { return err } // fsync the file to flush the write if err := tmp.Sync(); err != nil { return err } if err := os.Rename(tmp.Name(), t.tombstonePath()); err != nil { return err } // fsync the dir to flush the rename dir, err := os.OpenFile(filepath.Dir(t.tombstonePath()), os.O_RDONLY, os.ModeDir) if err != nil { return err } defer dir.Close() return dir.Sync() }
// Load loads a configuration by filename. func Load(filename string) (*Configfile, error) { b, err := ioutil.ReadFile(filename) if err != nil { return nil, err } abs, err := filepath.Abs(filename) if err != nil { return nil, err } cfg, err := Parse(b) if err != nil { return cfg, err } cfg.filename = abs if cfg.Repos.Dir == "" { cfg.Repos.Dir = filepath.Join(filepath.Dir(abs), "cache") } if cfg.Workspace == nil { cfg.Workspace = &Workspace{} } if cfg.Workspace.Dir == "" { cfg.Workspace.Dir = filepath.Join(filepath.Dir(abs), "workspace") } return cfg, nil }
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.") } }
func (w *Watcher) Watch(name string, cb interface{}) error { log.Finest("Watch(%s)", name) fi, err := os.Stat(name) isDir := err == nil && fi.IsDir() // If the file doesn't exist currently we will add watcher for file // directory and look for create event inside the directory if os.IsNotExist(err) { log.Debug("File doesn't exist, Watching parent dir") if err := w.Watch(filepath.Dir(name), nil); err != nil { return err } } w.lock.Lock() defer w.lock.Unlock() if err := w.add(name, cb); err != nil { if !isDir || exist(w.dirs, name) { return err } } // If exists in watchers we are already watching the path // Or // If the file is under one of watched dirs // // no need to create watcher if exist(w.watchers, name) || (!isDir && exist(w.dirs, filepath.Dir(name))) { return nil } if err := w.watch(name); err != nil { return err } if isDir { w.flushDir(name) } return nil }
func (ca *CA) MakeClientCertificate(certFile, keyFile string, u user.Info) (*TLSCertificateConfig, error) { glog.V(4).Infof("Generating client cert in %s and key in %s", certFile, keyFile) // ensure parent dirs if err := os.MkdirAll(filepath.Dir(certFile), os.FileMode(0755)); err != nil { return nil, err } if err := os.MkdirAll(filepath.Dir(keyFile), os.FileMode(0755)); err != nil { return nil, err } clientPublicKey, clientPrivateKey, _ := NewKeyPair() clientTemplate, _ := newClientCertificateTemplate(x509request.UserToSubject(u)) clientCrt, _ := ca.signCertificate(clientTemplate, clientPublicKey) certData, err := encodeCertificates(clientCrt) if err != nil { return nil, err } keyData, err := encodeKey(clientPrivateKey) if err != nil { return nil, err } if err = ioutil.WriteFile(certFile, certData, os.FileMode(0644)); err != nil { return nil, err } if err = ioutil.WriteFile(keyFile, keyData, os.FileMode(0600)); err != nil { return nil, err } return GetTLSCertificateConfig(certFile, keyFile) }
// Remove removes the specified volume and all underlying data. If the // given volume does not belong to this driver and an error is // returned. The volume is reference counted, if all references are // not released then the volume is not removed. func (r *Root) Remove(v volume.Volume) error { r.m.Lock() defer r.m.Unlock() lv, ok := v.(*localVolume) if !ok { return fmt.Errorf("unknown volume type %T", v) } realPath, err := filepath.EvalSymlinks(lv.path) if err != nil { if !os.IsNotExist(err) { return err } realPath = filepath.Dir(lv.path) } if !r.scopedPath(realPath) { return fmt.Errorf("Unable to remove a directory of out the Docker root %s: %s", r.scope, realPath) } if err := removePath(realPath); err != nil { return err } delete(r.volumes, lv.name) return removePath(filepath.Dir(lv.path)) }
// callerPkgDir returns a pathname containing the build-time location of the // deepest calling function that is not within this package. If that cannot be // found, ok will be false and dir will be empty. func callerPkgDir() (dir string, ok bool) { _, thisFile, _, c*k := runtime.Caller(0) // /home/me/workspace/src/fastly/go-utils/tls/tls.go if !c*k { return } thisDir := filepath.Dir(thisFile) // /home/me/workspace/src/fastly/go-utils/tls sep := fmt.Sprintf("%csrc%c", os.PathSeparator, os.PathSeparator) // /src/ p := strings.SplitN(thisDir, sep, 2) if len(p) < 2 { return } thisPkg := p[1] // fastly/go-utils/tls/ for i := 1; ; i++ { if i > 10 { // typical stack is tls.ConfigureServer -> tls.GenerateConfig -> // tls.LoadPackagedKeypair -> tls.LocatePackagedPEMFile -> // tls.LocatePackagedPEMDir -> tls.searchUpwards panic("excessive recursion inside tls package") } _, file, _, c*k := runtime.Caller(i) // /home/me/workspace/src/foo/bar/subpkg/thing.go if !c*k { return } if !strings.Contains(file, thisPkg) { return filepath.Dir(file), true // /home/me/workspace/src/foo/bar/subpkg } } }
func (s *AdditionalSketchFilesCopier) Run(context map[string]interface{}) error { sketch := context[constants.CTX_SKETCH].(*types.Sketch) sketchBuildPath := context[constants.CTX_SKETCH_BUILD_PATH].(string) err := utils.EnsureFolderExists(sketchBuildPath) if err != nil { return utils.WrapError(err) } sketchBasePath := filepath.Dir(sketch.MainFile.Name) for _, file := range sketch.AdditionalFiles { relativePath, err := filepath.Rel(sketchBasePath, file.Name) if err != nil { return utils.WrapError(err) } targetFilePath := filepath.Join(sketchBuildPath, relativePath) err = utils.EnsureFolderExists(filepath.Dir(targetFilePath)) if err != nil { return utils.WrapError(err) } bytes, err := ioutil.ReadFile(file.Name) if err != nil { return utils.WrapError(err) } utils.WriteFileBytes(targetFilePath, bytes) } return nil }
func TestCommandRelativeName(t *testing.T) { if runtime.GOOS == "darwin" && runtime.GOARCH == "arm" { t.Skip("skipping on darwin/arm") } // Run our own binary as a relative path // (e.g. "_test/exec.test") our parent directory. base := filepath.Base(os.Args[0]) // "exec.test" dir := filepath.Dir(os.Args[0]) // "/tmp/go-buildNNNN/os/exec/_test" if dir == "." { t.Skip("skipping; running test at root somehow") } parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec" dirBase := filepath.Base(dir) // "_test" if dirBase == "." { t.Skipf("skipping; unexpected shallow dir of %q", dir) } cmd := exec.Command(filepath.Join(dirBase, base), "-test.run=TestHelperProcess", "--", "echo", "foo") cmd.Dir = parentDir cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} out, err := cmd.Output() if err != nil { t.Errorf("echo: %v", err) } if g, e := string(out), "foo\n"; g != e { t.Errorf("echo: want %q, got %q", e, g) } }
func (s *storageLvm) ContainerSnapshotRename( snapshotContainer container, newContainerName string) error { oldName := containerNameToLVName(snapshotContainer.NameGet()) newName := containerNameToLVName(newContainerName) output, err := s.renameLV(oldName, newName) if err != nil { s.log.Error("Failed to rename a snapshot LV", log.Ctx{"oldName": oldName, "newName": newName, "err": err, "output": string(output)}) return fmt.Errorf("Failed to rename a container LV, oldName='%s', newName='%s', err='%s'", oldName, newName, err) } oldPath := snapshotContainer.PathGet("") oldSymPath := fmt.Sprintf("%s.lv", oldPath) newPath := snapshotContainer.PathGet(newName) newSymPath := fmt.Sprintf("%s.lv", newPath) if err := os.Rename(oldSymPath, newSymPath); err != nil { s.log.Error("Failed to rename symlink", log.Ctx{"oldSymPath": oldSymPath, "newSymPath": newSymPath, "err": err}) return fmt.Errorf("Failed to rename symlink err='%s'", err) } if strings.Contains(snapshotContainer.NameGet(), "/") { if !shared.PathExists(filepath.Dir(newPath)) { os.MkdirAll(filepath.Dir(newPath), 0700) } } if strings.Contains(snapshotContainer.NameGet(), "/") { if ok, _ := shared.PathIsEmpty(filepath.Dir(oldPath)); ok { os.Remove(filepath.Dir(oldPath)) } } return nil }