// Write the pidfile based on the flag. It is an error if the pidfile hasn't // been configured. func Write() error { if *pidfile == "" { return errNotConfigured } if err := os.MkdirAll(filepath.Dir(*pidfile), os.FileMode(0755)); err != nil { return err } file, err := atomicfile.New(*pidfile, os.FileMode(0644)) if err != nil { return fmt.Errorf("error opening pidfile %s: %s", *pidfile, err) } defer file.Close() // in case we fail before the explicit close _, err = fmt.Fprintf(file, "%d", os.Getpid()) if err != nil { return err } err = file.Close() if err != nil { return err } return nil }
func WritePidfile(pidfile string, pid int) error { if pidfile == "" { return errors.New("pidfile not configured") } if err := os.MkdirAll(filepath.Dir(pidfile), os.FileMode(0755)); err != nil { return err } file, err := atomicfile.New(pidfile, os.FileMode(0644)) if err != nil { return fmt.Errorf("error opening pidfile %s: %s", pidfile, err) } defer file.Close() _, err = fmt.Fprintf(file, "%d", pid) if err != nil { return err } err = file.Close() if err != nil { return err } return nil }
func TestAbort(t *testing.T) { contents := []byte("the answer is 42") t.Parallel() tmpfile, err := ioutil.TempFile("", "atomicfile-abort-") if err != nil { t.Fatal(err) } name := tmpfile.Name() if _, err := tmpfile.Write(contents); err != nil { t.Fatal(err) } defer os.Remove(name) f, err := atomicfile.New(name, os.FileMode(0666)) if err != nil { t.Fatal(err) } f.Write([]byte("foo")) if err := f.Abort(); err != nil { t.Fatal(err) } if _, err := os.Stat(name); err != nil { t.Fatalf("expected file to exist: %s", err) } actual, err := ioutil.ReadFile(name) if err != nil { t.Fatal(err) } if !bytes.Equal(contents, actual) { t.Fatalf(`did not find expected "%s" instead found "%s"`, contents, actual) } }
func test(t *testing.T, dir, prefix string) { t.Parallel() tmpfile, err := ioutil.TempFile(dir, prefix) if err != nil { t.Fatal(err) } name := tmpfile.Name() if err := os.Remove(name); err != nil { t.Fatal(err) } defer os.Remove(name) f, err := atomicfile.New(name, os.FileMode(0666)) if err != nil { t.Fatal(err) } f.Write([]byte("foo")) if _, err := os.Stat(name); !os.IsNotExist(err) { t.Fatal("did not expect file to exist") } if err := f.Close(); err != nil { t.Fatal(err) } if _, err := os.Stat(name); err != nil { t.Fatalf("expected file to exist: %s", err) } }
func (t LocalTarget) Create() (*atomicfile.File, error) { dirname := filepath.Dir(t.Path) if _, err := os.Stat(dirname); os.IsNotExist(err) { if err := os.MkdirAll(dirname, 0755); err != nil { return nil, err } } return atomicfile.New(t.Path, 0644) }
// WriteConfigFile writes the config from `cfg` into `filename`. func WriteConfigFile(filename string, cfg interface{}) error { err := os.MkdirAll(filepath.Dir(filename), 0775) if err != nil { return err } f, err := atomicfile.New(filename, 0660) if err != nil { return err } defer f.Close() return encode(f, cfg) }