本文整理汇总了Golang中os.Rename函数的典型用法代码示例。如果您正苦于以下问题:Golang Rename函数的具体用法?Golang Rename怎么用?Golang Rename使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Rename函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestIrregular_RemexecPs1NotExists
func TestIrregular_RemexecPs1NotExists(t *testing.T) {
scriptName := filepath.Join(baseDir, "remexec.ps1")
tmpScriptName := filepath.Join(baseDir, "remexec.ps1.tmp")
os.Rename(scriptName, tmpScriptName)
defer os.Rename(tmpScriptName, scriptName)
c := capturer.NewStdoutCapturer()
c.Start()
rc, err := executeRemoteCommand("pwd")
output := c.Stop()
if err != nil {
t.Fatalf("Error occured: %s", err)
}
if rc != 255 {
t.Errorf("RC => %d, wants %d", rc, 255)
}
if strings.Contains(output, "REX003E") {
t.Errorf("Output contains unexpected error message.")
t.Log("Output:")
t.Log(output)
}
}
示例2: saveConns
func saveConns(conf *types.Configuration) {
filename := replaceHome(connectionsPath)
tmp := filename + ".tmp"
wr, err := os.Create(tmp)
p(err, "opening "+filename)
defer func() {
if err := os.Rename(tmp, filename); err != nil {
p(os.Remove(filename), "deleting old connections.xml")
p(os.Rename(tmp, filename), "overwriting connections.xml")
}
}()
defer wr.Close()
encoding := unicode.UTF16(unicode.LittleEndian, unicode.ExpectBOM)
textEncoder := encoding.NewEncoder()
writer := textEncoder.Writer(wr)
fmt.Fprintln(writer, `<?xml version="1.0" encoding="utf-16"?>
<!-- ****************************************************************-->
<!-- * *-->
<!-- * PuTTY Configuration Manager save file - All right reserved. *-->
<!-- * *-->
<!-- ****************************************************************-->
<!-- The following lines can be modified at your own risks. -->`)
encoder := xml.NewEncoder(writer)
encoder.Indent("", " ")
p(encoder.Encode(&conf), "encoding xml")
}
示例3: saveTaskList
func saveTaskList(tasks TaskList) {
path := *fileFlag
previous := path + "~"
temp := path + "~~"
var serializeError error = nil
if file, err := os.Create(temp); err == nil {
defer func() {
if err = file.Close(); err != nil {
os.Remove(temp)
} else {
if serializeError != nil {
return
}
if _, err := os.Stat(path); err == nil {
if err = os.Rename(path, previous); err != nil {
fatal("unable to rename %s to %s", path, previous)
}
}
if err = os.Rename(temp, path); err != nil {
fatal("unable to rename %s to %s", temp, path)
}
}
}()
writer := NewJsonIO()
if serializeError = writer.Serialize(file, tasks); serializeError != nil {
fatal(serializeError.Error())
}
}
}
示例4: uploadChromiumBuild
func uploadChromiumBuild(localOutDir, gsDir, targetPlatform string, gs *GsUtil) error {
localUploadDir := localOutDir
if targetPlatform == "Android" {
localUploadDir = filepath.Join(localUploadDir, "apks")
} else {
// Temporarily move the not needed large "gen" and "obj" directories so
// that they do not get uploaded to Google Storage. Move them back after
// the method completes.
genDir := filepath.Join(localOutDir, "gen")
genTmpDir := filepath.Join(ChromiumBuildsDir, "gen")
if err := os.Rename(genDir, genTmpDir); err != nil {
return fmt.Errorf("Could not rename gen dir: %s", err)
}
defer util.Rename(genTmpDir, genDir)
objDir := filepath.Join(localOutDir, "obj")
objTmpDir := filepath.Join(ChromiumBuildsDir, "obj")
if err := os.Rename(objDir, objTmpDir); err != nil {
return fmt.Errorf("Could not rename obj dir: %s", err)
}
defer util.Rename(objTmpDir, objDir)
}
return gs.UploadDir(localUploadDir, gsDir, true)
}
示例5: Archive
func (p *PcapLogger) Archive() {
newBasename := filepath.Join(p.ArchiveDir, filepath.Base(p.basename))
os.Rename(p.basename, newBasename)
for i := 1; i < p.pcapLogNum+1; i++ {
os.Rename(filepath.Join(p.LogDir, fmt.Sprintf("%s.pcap.%d", p.Flow.String(), i)), fmt.Sprintf("%s.%d", newBasename, i))
}
}
示例6: TestGitGetter
func TestGitGetter(t *testing.T) {
if !testHasGit {
t.Log("git not found, skipping")
t.Skip()
}
g := new(GitGetter)
dst := tempDir(t)
// Git doesn't allow nested ".git" directories so we do some hackiness
// here to get around that...
moduleDir := filepath.Join(fixtureDir, "basic-git")
oldName := filepath.Join(moduleDir, "DOTgit")
newName := filepath.Join(moduleDir, ".git")
if err := os.Rename(oldName, newName); err != nil {
t.Fatalf("err: %s", err)
}
defer os.Rename(newName, oldName)
// With a dir that doesn't exist
if err := g.Get(dst, testModuleURL("basic-git")); err != nil {
t.Fatalf("err: %s", err)
}
// Verify the main file exists
mainPath := filepath.Join(dst, "main.tf")
if _, err := os.Stat(mainPath); err != nil {
t.Fatalf("err: %s", err)
}
}
示例7: Delete
// Delete atomically removes an image from the graph.
func (graph *Graph) Delete(id string) error {
garbage, err := graph.Garbage()
if err != nil {
return err
}
graph.idIndex.Delete(id)
err = os.Rename(graph.imageRoot(id), garbage.imageRoot(id))
if err != nil {
// FIXME: this introduces a race condition in Delete() if the image is already present
// in garbage. Let's store at random names in grabage instead.
if isNotEmpty(err) {
Debugf("The image %s is already present in garbage. Removing it.", id)
if err = os.RemoveAll(garbage.imageRoot(id)); err != nil {
Debugf("Error while removing the image %s from garbage: %s\n", id, err)
return err
}
Debugf("Image %s removed from garbage", id)
if err = os.Rename(graph.imageRoot(id), garbage.imageRoot(id)); err != nil {
return err
}
Debugf("Image %s put in the garbage", id)
} else {
Debugf("Error putting the image %s to garbage: %s\n", id, err)
}
return err
}
return nil
}
示例8: Finish
func (h *hashRecord) Finish() (string, error) {
err := h.tmpf.Close()
if err != nil {
return "", err
}
hs := hex.EncodeToString(h.sh.Sum([]byte{}))
fn := hashFilename(h.base, hs)
if h.hashin != "" && h.hashin != hs {
return "", fmt.Errorf("Invalid hash %v != %v",
h.hashin, hs)
}
err = os.Rename(h.tmpf.Name(), fn)
if err != nil {
os.MkdirAll(filepath.Dir(fn), 0777)
os.Remove(fn)
err = os.Rename(h.tmpf.Name(), fn)
if err != nil {
log.Printf("Error renaming %v to %v: %v",
h.tmpf.Name(), fn, err)
os.Remove(h.tmpf.Name())
return "", err
}
}
h.tmpf = nil
return hs, nil
}
示例9: upgradeTo
// Upgrade to the given release, saving the previous binary with a ".old" extension.
func upgradeTo(path string, rel Release, archExtra string) error {
expectedRelease := fmt.Sprintf("syncthing-%s-%s%s-%s.", runtime.GOOS, runtime.GOARCH, archExtra, rel.Tag)
if debug {
l.Debugf("expected release asset %q", expectedRelease)
}
for _, asset := range rel.Assets {
if debug {
l.Debugln("considering release", asset)
}
if strings.HasPrefix(asset.Name, expectedRelease) {
if strings.HasSuffix(asset.Name, ".zip") {
fname, err := readZip(asset.URL, filepath.Dir(path))
if err != nil {
return err
}
old := path + ".old"
os.Remove(old)
err = os.Rename(path, old)
if err != nil {
return err
}
err = os.Rename(fname, path)
if err != nil {
return err
}
return nil
}
}
}
return ErrVersionUnknown
}
示例10: main
func main() {
// ディレクトリを作成
os.MkdirAll("testdir", 0777)
// ディレクトリの名前変更
err := os.Rename("testdir", "newdir")
// エラーチェック
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// 空のファイルを作成
file, _ := os.Create("testfile")
file.Close()
// ファイルの名前変更
err = os.Rename("testfile", "newfile")
// エラーチェック
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
示例11: restorePage
func restorePage(page string) string {
// 1. count # deleted versions
deletedVers := sortedVersions("deleted/" + page)
n := len(deletedVers)
pageAlreadyThere := fileExists(pageFile(page, -1))
if pageAlreadyThere {
n++
}
// 2. rename pre-existing old versions ahead of deleted version count
if n > 0 {
preExistVers := sortedVersions("old/" + page)
for _, ver := range preExistVers {
old := fmt.Sprintf("old/%s.%d", page, ver)
newname := fmt.Sprintf("old/%s.%d", page, ver+n)
os.Rename(old, newname)
}
}
// 3. rename deleteds to old.(1:n-1)
i := 1
for _, ver := range deletedVers {
old := fmt.Sprintf("deleted/%s.%d", page, ver)
newname := fmt.Sprintf("old/%s.%d", page, i)
os.Rename(old, newname)
i++
}
// 4. rename deleted page as appropriate and redirect
if pageAlreadyThere {
os.Rename("deleted/"+page, fmt.Sprintf("old/%s.%d", page, n))
return fmt.Sprintf("/edit/%s?ver=%d", page, n)
}
os.Rename("deleted/"+page, "pages/"+page)
return "/" + page
}
示例12: install
func install(name string, p []byte) error {
oldExecPath := name + ".old"
execDir := filepath.Dir(name)
part := filepath.Join(execDir, "hk.part")
err := ioutil.WriteFile(part, p, 0755)
if err != nil {
return err
}
defer os.Remove(part)
// remove old executable leftover from previous update
if err = os.Remove(oldExecPath); err != nil && !os.IsNotExist(err) {
return err
}
// move the existing executable to a new file in the same directory
err = os.Rename(name, oldExecPath)
if err != nil {
return err
}
// move the new executable in to become the new program
err = os.Rename(part, name)
if err != nil {
// copy unsuccessful
_ = os.Rename(oldExecPath, name)
return err
} else {
// copy successful, remove the old binary (fails on Windows)
_ = os.Remove(oldExecPath)
}
return nil
}
示例13: Migrate
func Migrate(dataDir string) {
if !server.FileExists(dataDir) {
logger.Printf("Data directory '%v' doesn't appear to exist, so aborting migration.", dataDir)
return
}
logger.Printf("Migrating data in %v to version %v", dataDir, DATA_VERSION)
deployedDataVersion := readDataVersion(dataDir)
if deployedDataVersion == DATA_VERSION {
logger.Printf("Actually, data format was already up-to-date, so skipping migration.")
return
}
migrateEntityGraph(dataDir, "person")
migrateEntityGraph(dataDir, "org")
migrateEntityGraph(dataDir, "place")
server.Must(os.Remove(filepath.Join(dataDir, "personGraph.dat")))
server.Must(os.Remove(filepath.Join(dataDir, "orgGraph.dat")))
server.Must(os.Remove(filepath.Join(dataDir, "placeGraph.dat")))
server.Must(os.Rename(filepath.Join(dataDir, "personGraph.dat.tmp"), filepath.Join(dataDir, "personGraph.dat")))
server.Must(os.Rename(filepath.Join(dataDir, "orgGraph.dat.tmp"), filepath.Join(dataDir, "orgGraph.dat")))
server.Must(os.Rename(filepath.Join(dataDir, "placeGraph.dat.tmp"), filepath.Join(dataDir, "placeGraph.dat")))
WriteDataVersion(dataDir)
logger.Printf("Data in %v successfully migrated to version %v", dataDir, DATA_VERSION)
}
示例14: finishUpload
func finishUpload(num int, req *http.Request) error {
newuploadLock.Lock()
_, ok := uploads[num]
if ok {
delete(uploads, num)
}
newuploadLock.Unlock()
if !ok {
return fmt.Errorf("no such upload: %d", num)
}
finalPath, filename, err := computeFinalPathAndFile(num)
if err != nil {
return err
}
if err := os.MkdirAll(finalPath, 0755); err != nil {
return err
}
err = os.Rename(path.Join(directory, "tmp", strconv.Itoa(num)), path.Join(finalPath, filename))
if err != nil {
return err
}
tmpsig := path.Join(directory, "tmp", strconv.Itoa(num)+".asc")
if _, err := os.Stat(tmpsig); err == nil {
err = os.Rename(tmpsig, path.Join(finalPath, filename+".asc"))
if err != nil {
return err
}
}
return nil
}
示例15: DumpNeedleMapToCdb
// dumps a NeedleMap into a cdb
func DumpNeedleMapToCdb(cdbName string, nm *NeedleMap) error {
tempnam := cdbName + "t"
fnames := make([]string, 1, 2)
adder, closer, err := openTempCdb(tempnam)
if err != nil {
return fmt.Errorf("error creating factory: %s", err)
}
fnames[0] = tempnam
elt := cdb.Element{Key: make([]byte, 8), Data: make([]byte, 8)}
fcount := uint64(0)
walk := func(key uint64, offset, size uint32) error {
if fcount >= maxCdbRecCount {
if err = closer(); err != nil {
return err
}
tempnam = cdbName + "t2"
if adder, closer, err = openTempCdb(tempnam); err != nil {
return fmt.Errorf("error creating second factory: %s", err)
}
fnames = append(fnames, tempnam)
fcount = 0
}
util.Uint64toBytes(elt.Key, key)
util.Uint32toBytes(elt.Data[:4], offset)
util.Uint32toBytes(elt.Data[4:], size)
fcount++
return adder(elt)
}
// and write out the cdb from there
err = nm.Visit(func(nv NeedleValue) error {
return walk(uint64(nv.Key), nv.Offset, nv.Size)
})
if err != nil {
closer()
return fmt.Errorf("error walking index %s: %s", nm, err)
}
// store fileBytes
data, e := json.Marshal(nm.mapMetric)
if e != nil {
return fmt.Errorf("error marshaling metric %s: %s", nm.mapMetric, e)
}
if err = adder(cdb.Element{Key: []byte{'M'}, Data: data}); err != nil {
return err
}
if err = closer(); err != nil {
return err
}
os.Remove(cdbName)
if len(fnames) == 1 {
return os.Rename(fnames[0], cdbName)
}
bn, ext := nakeFilename(cdbName)
if err = os.Rename(fnames[0], bn+".1"+ext); err != nil {
return err
}
return os.Rename(fnames[1], bn+".2"+ext)
}