// writeFiles persists the given files to the system.
func (imp *Implementation) writeFiles(files []cloudconfig.WriteFile) {
	for _, f := range files {
		p, err := strconv.Atoi(f.Permissions)
		if err != nil {
			flog.Error("Failed to convert permissions",
				flog.Fields{
					Event: "strconv.Atoi",
					Error: err,
				},
				flog.Details{
					"file":        f.Path,
					"permissions": f.Permissions,
				},
			)
			continue
		}

		perms := os.FileMode(p)

		err = file.New(f.Path, file.Permissions(perms), file.Contents(f.Content))
		if err != nil {
			flog.Error("Failed to create file",
				flog.Fields{
					Event: "file.New",
					Error: err,
				},
				flog.Details{
					"file": f.Path,
				},
			)
		}
	}
}
Exemple #2
0
func TestNewFileCreation(t *testing.T) {
	Convey("Given a file path", t, func() {
		fname := filepath.Join(os.TempDir(), "__test_filepath")

		Convey("It should create an empty file", func() {
			err := file.New(fname)
			So(err, ShouldBeNil)
			defer os.Remove(fname)

			_, err = os.Stat(fname)
			So(err, ShouldBeNil)
		})

		Convey("With optional argument Contents", func() {
			c := "This is a file with text in it.\n"
			Convey("It should create a new file with the given contents", func() {
				err := file.New(fname, file.Contents(c))
				So(err, ShouldBeNil)
				defer os.Remove(fname)

				out, err := ioutil.ReadFile(fname)

				So(err, ShouldBeNil)
				So(string(out), ShouldEqual, c)
			})
		})

		Convey("With optional argument Permissions", func() {
			p := os.FileMode(0700)

			Convey("It should create a new file with the same permissions", func() {
				err := file.New(fname, file.Permissions(p))
				So(err, ShouldBeNil)
				defer os.Remove(fname)
				fi, err := os.Lstat(fname)

				So(err, ShouldBeNil)
				So(fi.Mode(), ShouldEqual, p)
			})
		})

		Convey("With optional argument User ID and/or Group ID", func() {
			userID, groupID := os.Getuid(), os.Getgid()

			Convey("It should create a new file belonging to given IDs", func() {
				err := file.New(fname, file.UID(userID), file.GID(groupID))
				So(err, ShouldBeNil)
				defer os.Remove(fname)
				fi, err := os.Lstat(fname)
				So(err, ShouldBeNil)

				uid := fi.Sys().(*syscall.Stat_t).Uid
				So(uid, ShouldEqual, userID)

				gid := fi.Sys().(*syscall.Stat_t).Gid
				So(gid, ShouldEqual, groupID)
			})
		})
	})
}