aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: c41bfe228d3894150040c3438a066921e3538b6c (plain) (blame)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
)

var version = "dev"
var (
	writeFlag    = flag.Bool("w", false, "write result to (source) file instead of stdout")
	listFlag     = flag.Bool("l", false, "list files whose formatting differs from iku's")
	diffFlag     = flag.Bool("d", false, "display diffs instead of rewriting files")
	commentsFlag = flag.String("comments", "follow", "comment attachment mode: follow, precede, standalone")
	versionFlag  = flag.Bool("version", false, "print version")
)

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: iku [flags] [path ...]\n")
		flag.PrintDefaults()
	}

	flag.Parse()

	if *versionFlag {
		fmt.Printf("%s (%s)\n", version, runtime.Version())
		os.Exit(0)
	}

	commentMode, err := parseCommentMode(*commentsFlag)

	if err != nil {
		fmt.Fprintf(os.Stderr, "iku: %v\n", err)
		os.Exit(2)
	}

	formatter := &Formatter{CommentMode: commentMode}

	if flag.NArg() == 0 {
		if *writeFlag {
			fmt.Fprintln(os.Stderr, "iku: cannot use -w with standard input")
			os.Exit(2)
		}

		if err := processFile(formatter, "<stdin>", os.Stdin, os.Stdout, false); err != nil {
			fmt.Fprintf(os.Stderr, "iku: %v\n", err)
			os.Exit(1)
		}

		return
	}

	exitCode := 0

	for _, argumentPath := range flag.Args() {
		switch fileInfo, err := os.Stat(argumentPath); {
		case err != nil:
			fmt.Fprintf(os.Stderr, "iku: %v\n", err)

			exitCode = 1
		case fileInfo.IsDir():
			if err := processDirectory(formatter, argumentPath, &exitCode); err != nil {
				fmt.Fprintf(os.Stderr, "iku: %v\n", err)

				exitCode = 1
			}
		default:
			if err := processFilePath(formatter, argumentPath, &exitCode); err != nil {
				fmt.Fprintf(os.Stderr, "iku: %v\n", err)

				exitCode = 1
			}
		}
	}

	os.Exit(exitCode)
}

func parseCommentMode(commentModeString string) (CommentMode, error) {
	switch strings.ToLower(commentModeString) {
	case "follow":
		return CommentsFollow, nil
	case "precede":
		return CommentsPrecede, nil
	case "standalone":
		return CommentsStandalone, nil
	default:
		return 0, fmt.Errorf("invalid comment mode: %q (use follow, precede, or standalone)", commentModeString)
	}
}

var supportedFileExtensions = map[string]bool{
	".go":  true,
	".js":  true,
	".ts":  true,
	".jsx": true,
	".tsx": true,
}

func processDirectory(formatter *Formatter, directoryPath string, exitCode *int) error {
	var sourceFilePaths []string

	err := filepath.WalkDir(directoryPath, func(currentPath string, dirEntry fs.DirEntry, err error) error {
		if err != nil {
			return err
		}

		if !dirEntry.IsDir() && supportedFileExtensions[filepath.Ext(currentPath)] {
			sourceFilePaths = append(sourceFilePaths, currentPath)
		}

		return nil
	})

	if err != nil {
		return err
	}

	var waitGroup sync.WaitGroup
	var mutex sync.Mutex

	semaphore := make(chan struct{}, runtime.NumCPU())

	for _, filePath := range sourceFilePaths {
		waitGroup.Add(1)

		go func(currentFilePath string) {
			defer waitGroup.Done()

			semaphore <- struct{}{}

			defer func() { <-semaphore }()

			if err := processFilePath(formatter, currentFilePath, exitCode); err != nil {
				mutex.Lock()
				fmt.Fprintf(os.Stderr, "iku: %v\n", err)

				*exitCode = 1

				mutex.Unlock()
			}
		}(filePath)
	}

	waitGroup.Wait()

	return nil
}

func processFilePath(formatter *Formatter, filePath string, _ *int) error {
	sourceFile, err := os.Open(filePath)

	if err != nil {
		return err
	}

	defer func() { _ = sourceFile.Close() }()

	var outputDestination io.Writer = os.Stdout

	if *writeFlag {
		outputDestination = nil
	}

	return processFile(formatter, filePath, sourceFile, outputDestination, true)
}

func processFile(formatter *Formatter, filename string, inputReader io.Reader, outputWriter io.Writer, isFile bool) error {
	sourceContent, err := io.ReadAll(inputReader)

	if err != nil {
		return fmt.Errorf("%s: %v", filename, err)
	}

	formattedResult, err := formatter.Format(sourceContent, filename)

	if err != nil {
		return fmt.Errorf("%s: %v", filename, err)
	}

	if *listFlag {
		if !bytes.Equal(sourceContent, formattedResult) {
			fmt.Println(filename)
		}

		return nil
	}

	if *diffFlag {
		if !bytes.Equal(sourceContent, formattedResult) {
			diffOutput := unifiedDiff(filename, sourceContent, formattedResult)
			_, _ = os.Stdout.Write(diffOutput)
		}

		return nil
	}

	if *writeFlag && isFile {
		if !bytes.Equal(sourceContent, formattedResult) {
			return os.WriteFile(filename, formattedResult, 0644)
		}

		return nil
	}

	if outputWriter != nil {
		_, err = outputWriter.Write(formattedResult)

		return err
	}

	return nil
}

func unifiedDiff(filename string, originalSource, formattedSource []byte) []byte {
	var outputBuffer bytes.Buffer

	fmt.Fprintf(&outputBuffer, "--- %s\n", filename)
	fmt.Fprintf(&outputBuffer, "+++ %s\n", filename)

	originalSourceLines := strings.Split(string(originalSource), "\n")
	formattedSourceLines := strings.Split(string(formattedSource), "\n")

	fmt.Fprintf(&outputBuffer, "@@ -1,%d +1,%d @@\n", len(originalSourceLines), len(formattedSourceLines))

	for _, currentLine := range originalSourceLines {
		fmt.Fprintf(&outputBuffer, "-%s\n", currentLine)
	}

	for _, currentLine := range formattedSourceLines {
		fmt.Fprintf(&outputBuffer, "+%s\n", currentLine)
	}

	return outputBuffer.Bytes()
}