summaryrefslogtreecommitdiff
path: root/src/cmd/gofmt/gofmt_unix_test.go
blob: 45b923431207c1b7d00c0b3225453f7cb9b1028e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build unix

package main

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestPermissions(t *testing.T) {
	if os.Getuid() == 0 {
		t.Skip("skipping permission test when running as root")
	}

	dir := t.TempDir()
	fn := filepath.Join(dir, "perm.go")

	// Create a file that needs formatting without write permission.
	if err := os.WriteFile(filepath.Join(fn), []byte("  package main"), 0o400); err != nil {
		t.Fatal(err)
	}

	// Set mtime of the file in the past.
	past := time.Now().Add(-time.Hour)
	if err := os.Chtimes(fn, past, past); err != nil {
		t.Fatal(err)
	}

	info, err := os.Stat(fn)
	if err != nil {
		t.Fatal(err)
	}

	defer func() { *write = false }()
	*write = true

	initParserMode()
	initRewrite()

	const maxWeight = 2 << 20
	var buf, errBuf strings.Builder
	s := newSequencer(maxWeight, &buf, &errBuf)
	s.Add(fileWeight(fn, info), func(r *reporter) error {
		return processFile(fn, info, nil, r)
	})
	if errBuf.Len() > 0 {
		t.Log(errBuf)
	}
	if s.GetExitCode() == 0 {
		t.Fatal("rewrite of read-only file succeeded unexpectedly")
	}

	info, err = os.Stat(fn)
	if err != nil {
		t.Fatal(err)
	}
	if !info.ModTime().Equal(past) {
		t.Errorf("after rewrite mod time is %v, want %v", info.ModTime(), past)
	}
}