forked from justinfx/gofileseq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileseq.go
281 lines (244 loc) · 6.85 KB
/
fileseq.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
/*
Package fileseq is a library for parsing file sequence strings commonly
used in VFX and animation applications.
Frame Range Shorthand
Support for:
Standard: 1-10
Comma Delimited: 1-10,10-20
Chunked: 1-100x5
Filled: 1-100y5
Staggered: 1-100:3 (1-100x3, 1-100x2, 1-100)
Negative frame numbers: -10-100
Padding: #=4 padded, @=single pad
Printf Syntax Padding: %04d=4 padded, %01d=1 padded
Houdini Syntax Padding: $F4=4 padding, $F=1 padded
*/
package fileseq
import (
"errors"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
)
const Version = "2.8.0"
var (
rangePatterns []*regexp.Regexp
splitPattern *regexp.Regexp
singleFrame *regexp.Regexp
printfPattern *regexp.Regexp
houdiniPattern *regexp.Regexp
)
func init() {
// Regular expression patterns for matching frame set strings.
// Examples:
// 1-100
// 100
// 1-100x5
rangePatterns = []*regexp.Regexp{
// Frame range: 1-10
regexp.MustCompile(`^(-?\d+)-(-?\d+)$`),
// Single frame: 10
regexp.MustCompile(`^(-?\d+)$`),
// Complex range: 1-10x2
regexp.MustCompile(`^(-?\d+)-(-?\d+)([:xy])(-?\d+)$`),
}
// Regular expression for matching a file sequence string.
// Example:
// /film/shot/renders/hero_bty.1-100#.exr
// /film/shot/renders/hero_bty.@@.exr
// /film/shot/renders/hero_bty.1-100%04d.exr
// /film/shot/renders/hero_bty.1-100$F04.exr
splitPattern = regexp.MustCompile(
`^(?P<name>.*?)` +
`(?P<range>[\d-][:xy\d,-]*)?` +
`(?P<pad>` +
`[#@]+` + // standard pad chars
`|%\d*d` + // or printf padding
`|\$F\d*` + // or houdini padding
`)` + // end <pad>
// multiple extension parts:
`(?P<ext>\.(?:\w*[a-zA-Z]\w*)*(?:\.[a-zA-Z0-9]+)?)$`)
// /film/shot/renders/hero_bty.100.exr
singleFrame = regexp.MustCompile(
`^(?P<name>.*?)` +
`(?P<frame>-?\d+)` +
// multiple extension parts:
`(?P<ext>(?:\.\w*[a-zA-Z]\w*)*(?:\.[a-zA-Z0-9]+)?)$`)
// Regular expression pattern for matching padding against a
// printf syntax padding string E.g. %04d
printfPattern = regexp.MustCompile(`^%(\d*)d$`)
// Regular expression pattern for matching padding against
// houdini syntax. E.g. $F04
houdiniPattern = regexp.MustCompile(`^\$F(\d*)$`)
}
// IsFrameRange returns true if the given string is a valid frame
// range format. Any padding characters, such as '#' and '@' are ignored.
func IsFrameRange(frange string) bool {
_, err := frameRangeMatches(frange)
if err == nil {
return true
}
return false
}
// FramesToFrameRange takes a slice of frame numbers and
// compresses them into a frame range string.
//
// If sorted == true, pre-sort the frames instead of respecting
// their current order in the range.
//
// If zfill > 1, then pad out each number with "0" to the given
// total width.
func FramesToFrameRange(frames []int, sorted bool, zfill int) string {
count := len(frames)
if count == 0 {
return ""
}
if count == 1 {
return zfillInt(frames[0], zfill)
}
if sorted {
sort.Ints(frames)
}
var i, frame, step int
var start, end string
var buf strings.Builder
// Keep looping until all frames are consumed
for len(frames) > 0 {
count = len(frames)
// If we get to the last element, just write it
// and end
if count <= 2 {
for _, frame = range frames {
if buf.Len() > 0 {
buf.WriteString(",")
}
buf.WriteString(zfillInt(frame, zfill))
}
break
}
// At this point, we have 3 or more frames to check.
// Scan the current window of the slice to see how
// many frames we can consume into a group
step = frames[1] - frames[0]
for i = 0; i < len(frames)-1; i++ {
// We have scanned as many frames as we can
// for this group. Now write them and stop
// looping on this window
if (frames[i+1] - frames[i]) != step {
break
}
}
// Subsequent groups are comma-separated
if buf.Len() > 0 {
buf.WriteString(",")
}
// We only have a single frame to write for this group
if i == 0 {
buf.WriteString(zfillInt(frames[0], zfill))
frames = frames[1:]
continue
}
// First do a check to see if we could have gotten a larger range
// out of subsequent values with a different step size
if i == 1 && count > 3 {
// Check if the next two pairwise frames have the same step.
// If so, then it is better than our current grouping.
if (frames[2] - frames[1]) == (frames[3] - frames[2]) {
// Just consume the first frame, and allow the next
// loop to scan the new stepping
buf.WriteString(zfillInt(frames[0], zfill))
frames = frames[1:]
continue
}
}
// Otherwise write out this step range
start = zfillInt(frames[0], zfill)
end = zfillInt(frames[i], zfill)
buf.WriteString(fmt.Sprintf("%s-%s", start, end))
if step > 1 {
buf.WriteString(fmt.Sprintf("x%d", step))
}
frames = frames[i+1:]
}
return buf.String()
}
// frameRangeMatches breaks down the string frame range
// into groups of range matches, for further processing.
func frameRangeMatches(frange string) ([][]string, error) {
for _, k := range defaultPadding.AllChars() {
frange = strings.Replace(frange, k, "", -1)
}
var (
matched bool
match []string
rx *regexp.Regexp
)
frange = strings.Replace(frange, " ", "", -1)
// For each comma-sep component, we will parse a frame range
parts := strings.Split(frange, ",")
size := len(parts)
matches := make([][]string, size, size)
for i, part := range parts {
matched = false
// Build up frames for all comma-sep components
for _, rx = range rangePatterns {
if match = rx.FindStringSubmatch(part); match == nil {
continue
}
matched = true
matches[i] = match[1:]
}
// If any component of the comma-sep frame range fails to
// parse, we bail out
if !matched {
err := fmt.Errorf("Failed to parse frame range: %s on part %q", frange, part)
return nil, err
}
}
return matches, nil
}
// Expands a start, end, and stepping value
// into the full range of int values.
func toRange(start, end, step int) []int {
nums := []int{}
if step < 1 {
step = 1
}
if start <= end {
for i := start; i <= end; {
nums = append(nums, i)
i += step
}
} else {
for i := start; i >= end; {
nums = append(nums, i)
i -= step
}
}
return nums
}
// Parse an int from a specific part of a frame
// range string component
var parseIntErr error = errors.New("Failed to parse int from part of range string")
func parseInt(s string) (int, error) {
val, err := strconv.Atoi(s)
if err != nil {
return 0, parseIntErr
}
return val, nil
}
// Return whether a string component from a frame
// range string is a valid modifier symbol
func isModifier(s string) bool {
return len(s) == 1 && strings.ContainsAny(s, "xy:")
}
// Return the min/max frames from an unsorted list
func minMaxFrame(frames []int) (int, int) {
srcframes := make([]int, len(frames), len(frames))
copy(srcframes, frames)
sort.Ints(srcframes)
min, max := srcframes[0], srcframes[len(srcframes)-1]
return min, max
}