-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
538 lines (484 loc) · 11.9 KB
/
util.go
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nin
import (
"fmt"
"os"
"runtime"
"unsafe"
)
// Have a generic fall-through for different versions of C/C++.
// Log a fatalf message and exit.
func fatalf(msg string, s ...interface{}) {
fmt.Fprintf(os.Stderr, "nin: fatal: ")
fmt.Fprintf(os.Stderr, msg, s...)
fmt.Fprintf(os.Stderr, "\n")
// On Windows, some tools may inject extra threads.
// exit() may block on locks held by those threads, so forcibly exit.
_ = os.Stderr.Sync()
_ = os.Stdout.Sync()
os.Exit(1)
}
// Log a warning message.
func warningf(msg string, s ...interface{}) {
fmt.Fprintf(os.Stderr, "nin: warning: ")
fmt.Fprintf(os.Stderr, msg, s...)
fmt.Fprintf(os.Stderr, "\n")
}
// Log an error message.
func errorf(msg string, s ...interface{}) {
fmt.Fprintf(os.Stderr, "nin: error: ")
fmt.Fprintf(os.Stderr, msg, s...)
fmt.Fprintf(os.Stderr, "\n")
}
func isPathSeparator(c byte) bool {
return c == '/' || c == '\\'
}
// CanonicalizePath canonicalizes a path like "foo/../bar.h" into just "bar.h".
func CanonicalizePath(path string) string {
// TODO(maruel): Call site should be the lexers, so that it's done as a
// single pass.
// WARNING: this function is performance-critical; please benchmark
// any changes you make to it.
l := len(path)
if l == 0 {
return path
}
p := make([]byte, l+1)
copy(p, path)
// Tell the compiler that l is safe for p.
_ = p[l]
dst := 0
src := 0
if c := p[src]; c == '/' || c == '\\' {
if runtime.GOOS == "windows" && l > 1 {
// network path starts with //
if c := p[src+1]; c == '/' || c == '\\' {
src += 2
dst += 2
} else {
src++
dst++
}
} else {
src++
dst++
}
}
var components [60]int
for componentCount := 0; src < l; {
if p[src] == '.' {
// It is fine to read one byte past because p is l+1 in
// length. It will be a 0 zero if so.
c := p[src+1]
if src+1 == l || (c == '/' || c == '\\') {
// '.' component; eliminate.
src += 2
continue
}
if c == '.' {
// It is fine to read one byte past because p is l+1 in
// length. It will be a 0 zero if so.
c := p[src+2]
if src+2 == l || (c == '/' || c == '\\') {
// '..' component. Back up if possible.
if componentCount > 0 {
dst = components[componentCount-1]
src += 3
componentCount--
} else {
p[dst] = p[src]
p[dst+1] = p[src+1]
p[dst+2] = p[src+2]
dst += 3
src += 3
}
continue
}
}
}
if c := p[src]; c == '/' || c == '\\' {
src++
continue
}
if componentCount == len(components) {
fatalf("path has too many components : %s", path)
}
components[componentCount] = dst
componentCount++
for src != l {
c := p[src]
if c == '/' || c == '\\' {
break
}
p[dst] = c
dst++
src++
}
// Copy '/' or final \0 character as well.
p[dst] = p[src]
dst++
src++
}
if dst == 0 {
p[dst] = '.'
dst += 2
}
p = p[:dst-1]
if runtime.GOOS == "windows" {
for i, c := range p {
if c == '\\' {
p[i] = '/'
}
}
}
return unsafeString(p)
}
// CanonicalizePathBits canonicalizes a path like "foo/../bar.h" into just
// "bar.h".
//
// Returns a bits set starting from lowest for a backslash that was
// normalized to a forward slash. (only used on Windows)
func CanonicalizePathBits(path string) (string, uint64) {
// TODO(maruel): Call site should be the lexers, so that it's done as a
// single pass.
// WARNING: this function is performance-critical; please benchmark
// any changes you make to it.
l := len(path)
if l == 0 {
return path, 0
}
p := make([]byte, l+1)
copy(p, path)
// Tell the compiler that l is safe for p.
_ = p[l]
dst := 0
src := 0
if c := p[src]; c == '/' || c == '\\' {
if runtime.GOOS == "windows" && l > 1 {
// network path starts with //
if c := p[src+1]; c == '/' || c == '\\' {
src += 2
dst += 2
} else {
src++
dst++
}
} else {
src++
dst++
}
}
var components [60]int
for componentCount := 0; src < l; {
if p[src] == '.' {
// It is fine to read one byte past because p is l+1 in
// length. It will be a 0 zero if so.
c := p[src+1]
if src+1 == l || (c == '/' || c == '\\') {
// '.' component; eliminate.
src += 2
continue
}
if c == '.' {
// It is fine to read one byte past because p is l+1 in
// length. It will be a 0 zero if so.
c := p[src+2]
if src+2 == l || (c == '/' || c == '\\') {
// '..' component. Back up if possible.
if componentCount > 0 {
dst = components[componentCount-1]
src += 3
componentCount--
} else {
p[dst] = p[src]
p[dst+1] = p[src+1]
p[dst+2] = p[src+2]
dst += 3
src += 3
}
continue
}
}
}
if c := p[src]; c == '/' || c == '\\' {
src++
continue
}
if componentCount == len(components) {
fatalf("path has too many components : %s", path)
}
components[componentCount] = dst
componentCount++
for src != l {
c := p[src]
if c == '/' || c == '\\' {
break
}
p[dst] = c
dst++
src++
}
// Copy '/' or final \0 character as well.
p[dst] = p[src]
dst++
src++
}
if dst == 0 {
p[dst] = '.'
dst += 2
}
p = p[:dst-1]
bits := uint64(0)
if runtime.GOOS == "windows" {
bitsMask := uint64(1)
for i, c := range p {
switch c {
case '\\':
bits |= bitsMask
p[i] = '/'
fallthrough
case '/':
bitsMask <<= 1
}
}
}
return unsafeString(p), bits
}
func stringNeedsShellEscaping(input string) bool {
for i := 0; i < len(input); i++ {
ch := input[i]
if 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '0' <= ch && ch <= '9' {
continue
}
switch ch {
case '_', '+', '-', '.', '/':
default:
return true
}
}
return false
}
func stringNeedsWin32Escaping(input string) bool {
for i := 0; i < len(input); i++ {
switch input[i] {
case ' ', '"':
return true
default:
}
}
return false
}
// Escapes the item for bash.
func getShellEscapedString(input string) string {
if !stringNeedsShellEscaping(input) {
return input
}
const quote = byte('\'')
// Do one pass to calculate the ending size.
l := len(input) + 2
for i := 0; i != len(input); i++ {
if input[i] == quote {
l += 3
}
}
out := make([]byte, l)
out[0] = quote
offset := 1
for i := 0; i < len(input); i++ {
c := input[i]
out[offset] = c
if c == quote {
offset++
out[offset] = '\\'
offset++
out[offset] = '\''
offset++
out[offset] = '\''
}
offset++
}
out[offset] = quote
return unsafeString(out)
}
// Escapes the item for Windows's CommandLineToArgvW().
func getWin32EscapedString(input string) string {
if !stringNeedsWin32Escaping(input) {
return input
}
result := "\""
consecutiveBackslashCount := 0
spanBegin := 0
for it, c := range input {
switch c {
case '\\':
consecutiveBackslashCount++
case '"':
result += input[spanBegin:it]
for j := 0; j < consecutiveBackslashCount+1; j++ {
result += "\\"
}
spanBegin = it
consecutiveBackslashCount = 0
default:
consecutiveBackslashCount = 0
}
}
result += input[spanBegin:]
for j := 0; j < consecutiveBackslashCount; j++ {
result += "\\"
}
result += "\""
return result
}
// SpellcheckString provides the closest match to a misspelled string, given a
// list of correct spellings.
//
// Returns "" if there is no close enough match.
func SpellcheckString(text string, words ...string) string {
const maxValidEditDistance = 3
minDistance := maxValidEditDistance + 1
result := ""
for _, i := range words {
distance := editDistance(i, text, true, maxValidEditDistance)
if distance < minDistance {
minDistance = distance
result = i
}
}
return result
}
func islatinalpha(c byte) bool {
// isalpha() is locale-dependent.
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
/*
func calculateProcessorLoad(idleTicks, totalTicks uint64) float64 {
static uint64T previousIdleTicks = 0
static uint64T previousTotalTicks = 0
static double previousLoad = -0.0
uint64T idleTicksSinceLastTime = idleTicks - previousIdleTicks
uint64T totalTicksSinceLastTime = totalTicks - previousTotalTicks
bool firstCall = (previousTotalTicks == 0)
bool ticksNotUpdatedSinceLastCall = (totalTicksSinceLastTime == 0)
double load
if (firstCall || ticksNotUpdatedSinceLastCall) {
load = previousLoad
} else {
// Calculate load.
double idleToTotalRatio =
((double)idleTicksSinceLastTime) / totalTicksSinceLastTime
double loadSinceLastCall = 1.0 - idleToTotalRatio
// Filter/smooth result when possible.
if(previousLoad > 0) {
load = 0.9 * previousLoad + 0.1 * loadSinceLastCall
} else {
load = loadSinceLastCall
}
}
previousLoad = load
previousTotalTicks = totalTicks
previousIdleTicks = idleTicks
return load
}
uint64T FileTimeToTickCount(const FILETIME & ft)
{
uint64T high = (((uint64T)(ft.dwHighDateTime)) << 32)
uint64T low = ft.dwLowDateTime
return (high | low)
}
*/
// @return the load average of the machine. A negative value is returned
// on error.
func getLoadAverage() float64 {
/*
FILETIME idleTime, kernelTime, userTime
BOOL getSystemTimeSucceeded =
GetSystemTimes(&idleTime, &kernelTime, &userTime)
posixCompatibleLoad := 0.
if getSystemTimeSucceeded {
idleTicks := FileTimeToTickCount(idleTime)
// kernelTime from GetSystemTimes already includes idleTime.
uint64T totalTicks =
FileTimeToTickCount(kernelTime) + FileTimeToTickCount(userTime)
processorLoad := calculateProcessorLoad(idleTicks, totalTicks)
posixCompatibleLoad = processorLoad * GetProcessorCount()
} else {
posixCompatibleLoad = -0.0
}
return posixCompatibleLoad
*/
return 0
}
/*
// @return the load average of the machine. A negative value is returned
// on error.
func getLoadAverage() float64 {
return -0.0f
}
// @return the load average of the machine. A negative value is returned
// on error.
func getLoadAverage() float64 {
var cpuStats perfstatCpuTotalT
if perfstatCpuTotal(nil, &cpuStats, sizeof(cpuStats), 1) < 0 {
return -0.0f
}
// Calculation taken from comment in libperfstats.h
return double(cpuStats.loadavg[0]) / double(1 << SBITS)
}
// @return the load average of the machine. A negative value is returned
// on error.
func getLoadAverage() float64 {
var si sysinfo
if sysinfo(&si) != 0 {
return -0.0f
}
return 1.0 / (1 << SI_LOAD_SHIFT) * si.loads[0]
}
// @return the load average of the machine. A negative value is returned
// on error.
func getLoadAverage() float64 {
return -0.0f
}
*/
// Elide the given string @a str with '...' in the middle if the length
// exceeds @a width.
func elideMiddle(str string, width int) string {
switch width {
case 0:
return ""
case 1:
return "."
case 2:
return ".."
case 3:
return "..."
}
const margin = 3 // Space for "...".
result := str
if len(result) > width {
elideSize := (width - margin) / 2
result = result[0:elideSize] + "..." + result[len(result)-elideSize:]
}
return result
}
// unsafeString performs an unsafe conversion from a []byte to a string. The
// returned string will share the underlying memory with the []byte which thus
// allows the string to be mutable through the []byte. We're careful to use
// this method only in situations in which the []byte will not be modified.
//
// A workaround for the absence of https://github.com/golang/go/issues/2632.
func unsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}