forked from alanjds/grumpy
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathfile.go
432 lines (404 loc) · 11.4 KB
/
file.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
// Copyright 2016 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 grumpy
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"strings"
"sync"
)
// File represents Python 'file' objects.
type File struct {
Object
// mutex synchronizes the state of the File struct, not access to the
// underlying os.File. So, for example, when doing file reads and
// writes we only acquire a read lock.
mutex sync.Mutex
mode string
open bool
Softspace int `attr:"softspace" attr_mode:"rw"`
reader *bufio.Reader
file *os.File
skipNextLF bool
univNewLine bool
close *Object
}
// NewFileFromFD creates a file object from the given file descriptor fd.
func NewFileFromFD(fd uintptr, close *Object) *File {
// TODO: Use fcntl or something to get the mode of the descriptor.
file := &File{
Object: Object{typ: FileType},
mode: "?",
open: true,
file: os.NewFile(fd, "<fdopen>"),
}
if close != None {
file.close = close
}
file.reader = bufio.NewReader(file.file)
return file
}
func toFileUnsafe(o *Object) *File {
return (*File)(o.toPointer())
}
func (f *File) name() string {
name := "<uninitialized file>"
if f.file != nil {
name = f.file.Name()
}
return name
}
// ToObject upcasts f to an Object.
func (f *File) ToObject() *Object {
return &f.Object
}
func (f *File) readLine(maxBytes int) (string, error) {
var buf bytes.Buffer
numBytesRead := 0
for maxBytes < 0 || numBytesRead < maxBytes {
b, err := f.reader.ReadByte()
if err == io.EOF {
break
}
if err != nil {
return "", err
}
if b == '\r' && f.univNewLine {
f.skipNextLF = true
buf.WriteByte('\n')
break
} else if b == '\n' {
if f.skipNextLF {
f.skipNextLF = false
continue // Do not increment numBytesRead.
} else {
buf.WriteByte(b)
break
}
} else {
buf.WriteByte(b)
}
numBytesRead++
}
return buf.String(), nil
}
func (f *File) writeString(s string) error {
f.mutex.Lock()
defer f.mutex.Unlock()
if !f.open {
return io.ErrClosedPipe
}
if _, err := f.file.Write([]byte(s)); err != nil {
return err
}
return nil
}
// FileType is the object representing the Python 'file' type.
var FileType = newBasisType("file", reflect.TypeOf(File{}), toFileUnsafe, ObjectType)
func fileInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object, *BaseException) {
argc := len(args)
expectedTypes := []*Type{StrType, StrType}
if argc == 1 {
expectedTypes = expectedTypes[:1]
}
if raised := checkFunctionArgs(f, "__init__", args, expectedTypes...); raised != nil {
return nil, raised
}
mode := "r"
if argc > 1 {
mode = toStrUnsafe(args[1]).Value()
}
// TODO: Do something with the binary mode flag.
var flag int
switch mode {
case "a", "ab":
flag = os.O_WRONLY | os.O_CREATE | os.O_APPEND
case "r", "rb", "rU", "U":
flag = os.O_RDONLY
case "r+", "r+b":
flag = os.O_RDWR
// Difference between r+ and a+ is that a+ automatically creates file.
case "a+":
flag = os.O_RDWR | os.O_CREATE | os.O_APPEND
case "w+":
flag = os.O_RDWR | os.O_CREATE
case "w", "wb":
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
default:
return nil, f.RaiseType(ValueErrorType, fmt.Sprintf("invalid mode string: %q", mode))
}
file := toFileUnsafe(o)
file.mutex.Lock()
defer file.mutex.Unlock()
osFile, err := os.OpenFile(toStrUnsafe(args[0]).Value(), flag, 0644)
if err != nil {
return nil, f.RaiseType(IOErrorType, err.Error())
}
file.mode = mode
file.open = true
file.file = osFile
file.reader = bufio.NewReader(osFile)
file.univNewLine = strings.HasSuffix(mode, "U")
return None, nil
}
func fileEnter(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "__enter__", args, FileType); raised != nil {
return nil, raised
}
return args[0], nil
}
func fileExit(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodVarArgs(f, "__exit__", args, FileType); raised != nil {
return nil, raised
}
closeFunc, raised := GetAttr(f, args[0], NewStr("close"), nil)
if raised != nil {
return nil, raised
}
_, raised = closeFunc.Call(f, nil, nil)
if raised != nil {
return nil, raised
}
return None, nil
}
func fileClose(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "close", args, FileType); raised != nil {
return nil, raised
}
file := toFileUnsafe(args[0])
file.mutex.Lock()
defer file.mutex.Unlock()
ret := None
if file.open {
var raised *BaseException
if file.close != nil {
ret, raised = file.close.Call(f, args, nil)
} else if file.file != nil {
if err := file.file.Close(); err != nil {
raised = f.RaiseType(IOErrorType, err.Error())
}
}
if raised != nil {
return nil, raised
}
}
file.open = false
return ret, nil
}
func fileClosed(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "closed", args, FileType); raised != nil {
return nil, raised
}
file := toFileUnsafe(args[0])
file.mutex.Lock()
c := !file.open
file.mutex.Unlock()
return GetBool(c).ToObject(), nil
}
func fileFileno(f *Frame, args Args, _ KWArgs) (ret *Object, raised *BaseException) {
if raised := checkMethodArgs(f, "fileno", args, FileType); raised != nil {
return nil, raised
}
file := toFileUnsafe(args[0])
file.mutex.Lock()
if file.open {
ret = NewInt(int(file.file.Fd())).ToObject()
} else {
raised = f.RaiseType(ValueErrorType, "I/O operation on closed file")
}
file.mutex.Unlock()
return ret, raised
}
func fileGetName(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "_get_name", args, FileType); raised != nil {
return nil, raised
}
file := toFileUnsafe(args[0])
file.mutex.Lock()
name := file.name()
file.mutex.Unlock()
return NewStr(name).ToObject(), nil
}
func fileIter(f *Frame, o *Object) (*Object, *BaseException) {
return o, nil
}
func fileNext(f *Frame, o *Object) (ret *Object, raised *BaseException) {
file := toFileUnsafe(o)
file.mutex.Lock()
defer file.mutex.Unlock()
if !file.open {
return nil, f.RaiseType(ValueErrorType, "I/O operation on closed file")
}
line, err := file.readLine(-1)
if err != nil {
return nil, f.RaiseType(IOErrorType, err.Error())
}
if line == "" {
return nil, f.Raise(StopIterationType.ToObject(), nil, nil)
}
return NewStr(line).ToObject(), nil
}
func fileRead(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
file, size, raised := fileParseReadArgs(f, "read", args)
if raised != nil {
return nil, raised
}
file.mutex.Lock()
defer file.mutex.Unlock()
if !file.open {
return nil, f.RaiseType(ValueErrorType, "I/O operation on closed file")
}
var data []byte
var err error
if size < 0 {
data, err = ioutil.ReadAll(file.file)
} else {
data = make([]byte, size)
var n int
n, err = file.reader.Read(data)
data = data[:n]
}
if err != nil && err != io.EOF {
return nil, f.RaiseType(IOErrorType, err.Error())
}
return NewStr(string(data)).ToObject(), nil
}
func fileReadLine(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
file, size, raised := fileParseReadArgs(f, "readline", args)
if raised != nil {
return nil, raised
}
file.mutex.Lock()
defer file.mutex.Unlock()
if !file.open {
return nil, f.RaiseType(ValueErrorType, "I/O operation on closed file")
}
line, err := file.readLine(size)
if err != nil {
return nil, f.RaiseType(IOErrorType, err.Error())
}
return NewStr(line).ToObject(), nil
}
func fileReadLines(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
// NOTE: The size hint behavior here is slightly different than
// CPython. Here we read no more lines than necessary. In CPython a
// minimum of 8KB or more will be read.
file, size, raised := fileParseReadArgs(f, "readlines", args)
if raised != nil {
return nil, raised
}
file.mutex.Lock()
defer file.mutex.Unlock()
if !file.open {
return nil, f.RaiseType(ValueErrorType, "I/O operation on closed file")
}
var lines []*Object
numBytesRead := 0
for size < 0 || numBytesRead < size {
line, err := file.readLine(-1)
if err != nil {
return nil, f.RaiseType(IOErrorType, err.Error())
}
if line != "" {
lines = append(lines, NewStr(line).ToObject())
}
if !strings.HasSuffix(line, "\n") {
break
}
numBytesRead += len(line)
}
return NewList(lines...).ToObject(), nil
}
func fileRepr(f *Frame, o *Object) (*Object, *BaseException) {
file := toFileUnsafe(o)
file.mutex.Lock()
defer file.mutex.Unlock()
var openState string
if file.open {
openState = "open"
} else {
openState = "closed"
}
var mode string
if file.mode != "" {
mode = file.mode
} else {
mode = "<uninitialized file>"
}
return NewStr(fmt.Sprintf("<%s file %q, mode %q at %p>", openState, file.name(), mode, file)).ToObject(), nil
}
func fileWrite(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "write", args, FileType, StrType); raised != nil {
return nil, raised
}
file := toFileUnsafe(args[0])
file.mutex.Lock()
defer file.mutex.Unlock()
if !file.open {
return nil, f.RaiseType(ValueErrorType, "I/O operation on closed file")
}
if _, err := file.file.Write([]byte(toStrUnsafe(args[1]).Value())); err != nil {
return nil, f.RaiseType(IOErrorType, err.Error())
}
return None, nil
}
func initFileType(dict map[string]*Object) {
// TODO: Make enter/exit into slots.
dict["__enter__"] = newBuiltinFunction("__enter__", fileEnter).ToObject()
dict["__exit__"] = newBuiltinFunction("__exit__", fileExit).ToObject()
dict["close"] = newBuiltinFunction("close", fileClose).ToObject()
dict["closed"] = newBuiltinFunction("closed", fileClosed).ToObject()
dict["fileno"] = newBuiltinFunction("fileno", fileFileno).ToObject()
dict["name"] = newProperty(newBuiltinFunction("_get_name", fileGetName).ToObject(), nil, nil).ToObject()
dict["read"] = newBuiltinFunction("read", fileRead).ToObject()
dict["readline"] = newBuiltinFunction("readline", fileReadLine).ToObject()
dict["readlines"] = newBuiltinFunction("readlines", fileReadLines).ToObject()
dict["write"] = newBuiltinFunction("write", fileWrite).ToObject()
FileType.slots.Init = &initSlot{fileInit}
FileType.slots.Iter = &unaryOpSlot{fileIter}
FileType.slots.Next = &unaryOpSlot{fileNext}
FileType.slots.Repr = &unaryOpSlot{fileRepr}
}
func fileParseReadArgs(f *Frame, method string, args Args) (*File, int, *BaseException) {
expectedTypes := []*Type{FileType, ObjectType}
argc := len(args)
if argc == 1 {
expectedTypes = expectedTypes[:1]
}
if raised := checkMethodArgs(f, method, args, expectedTypes...); raised != nil {
return nil, 0, raised
}
size := -1
if argc > 1 {
o, raised := IntType.Call(f, args[1:], nil)
if raised != nil {
return nil, 0, raised
}
size = toIntUnsafe(o).Value()
}
return toFileUnsafe(args[0]), size, nil
}
var (
// Stdin is an alias for sys.stdin.
Stdin = NewFileFromFD(os.Stdin.Fd(), nil)
// Stdout is an alias for sys.stdout.
Stdout = NewFileFromFD(os.Stdout.Fd(), nil)
// Stderr is an alias for sys.stderr.
Stderr = NewFileFromFD(os.Stderr.Fd(), nil)
)