-
Notifications
You must be signed in to change notification settings - Fork 354
Expand file tree
/
Copy pathstringutil.go
More file actions
83 lines (74 loc) · 2.3 KB
/
stringutil.go
File metadata and controls
83 lines (74 loc) · 2.3 KB
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
// Package stringutil provides utility functions for working with strings.
package stringutil
import (
"fmt"
"strconv"
"strings"
)
// Truncate truncates a string to a maximum length, adding "..." if truncated.
// If maxLen is 3 or less, the string is truncated without "...".
//
// This is a general-purpose utility for truncating any string to a configurable
// length. For domain-specific workflow command identifiers with newline handling,
// see workflow.ShortenCommand instead.
func Truncate(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
if maxLen <= 3 {
return s[:maxLen]
}
return s[:maxLen-3] + "..."
}
// NormalizeWhitespace normalizes trailing whitespace and newlines to reduce spurious conflicts.
// It trims trailing whitespace from each line and ensures exactly one trailing newline.
func NormalizeWhitespace(content string) string {
// Split into lines and trim trailing whitespace from each line
lines := strings.Split(content, "\n")
for i, line := range lines {
lines[i] = strings.TrimRight(line, " \t")
}
// Join back and ensure exactly one trailing newline if content is not empty
normalized := strings.Join(lines, "\n")
normalized = strings.TrimRight(normalized, "\n")
if len(normalized) > 0 {
normalized += "\n"
}
return normalized
}
// ParseVersionValue converts version values of various types to strings.
// Supports string, int, int64, uint64, and float64 types.
// Returns empty string for unsupported types.
func ParseVersionValue(version any) string {
switch v := version.(type) {
case string:
return v
case int, int64, uint64:
return fmt.Sprintf("%d", v)
case float64:
return fmt.Sprintf("%g", v)
default:
return ""
}
}
// IsPositiveInteger checks if a string is a positive integer.
// Returns true for strings like "1", "123", "999" but false for:
// - Zero ("0")
// - Negative numbers ("-5")
// - Numbers with leading zeros ("007")
// - Floating point numbers ("3.14")
// - Non-numeric strings ("abc")
// - Empty strings ("")
func IsPositiveInteger(s string) bool {
// Must not be empty
if s == "" {
return false
}
// Must not have leading zeros (except "0" itself, but that's not positive)
if len(s) > 1 && s[0] == '0' {
return false
}
// Must be numeric and > 0
num, err := strconv.ParseInt(s, 10, 64)
return err == nil && num > 0
}