-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathos.go
More file actions
450 lines (399 loc) · 12.3 KB
/
Copy pathos.go
File metadata and controls
450 lines (399 loc) · 12.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
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
// SPDX-License-Identifier: EUPL-1.2
// Base OS primitives for the Core framework.
//
// Re-exports stdlib os value types and the standard streams so consumer
// packages declare FileMode parameters and reach Stdin/Stdout/Stderr
// without importing os directly.
//
// File operations live on c.Fs() (sandbox-aware). Environment lookups
// live on core.Env. Process control lives on c.Process() / go-process.
// What's here is the connecting tissue: types, constants, and the
// canonical stdio streams that boundary code can't avoid.
//
// Usage:
//
// func writeMode(p string, mode core.FileMode) { ... }
//
// core.WriteString(core.Stderr(), "diagnostic\n")
//
// if mode.Perm()&core.ModePerm == 0o600 { ... }
package core
import "os"
// OSFile is an alias for os.File.
//
// r := core.Create("agent.log")
// if r.OK { file := r.Value.(*core.OSFile); _ = file }
type OSFile = os.File
// FileMode is an alias for os.FileMode — file mode bits and permissions.
//
// mode := core.FileMode(0o600)
// core.Println(mode.Perm())
type FileMode = os.FileMode
// File mode bits exposed at core scope. These are the same values as
// os.ModeDir etc., re-exported so consumers don't need to import os.
//
// mode := core.ModeDir | core.ModePerm
// if mode&core.ModeDir != 0 { core.Println("directory") }
const (
ModeDir = os.ModeDir
ModeAppend = os.ModeAppend
ModeExclusive = os.ModeExclusive
ModeTemporary = os.ModeTemporary
ModeSymlink = os.ModeSymlink
ModeDevice = os.ModeDevice
ModeNamedPipe = os.ModeNamedPipe
ModeSocket = os.ModeSocket
ModeSetuid = os.ModeSetuid
ModeSetgid = os.ModeSetgid
ModeCharDevice = os.ModeCharDevice
ModeSticky = os.ModeSticky
ModeIrregular = os.ModeIrregular
ModeType = os.ModeType
ModePerm = os.ModePerm // 0o777 — Unix permission bits
)
// File open flags exposed at core scope.
//
// r := core.OpenFile("agent.log", core.O_CREATE|core.O_WRONLY, 0o644)
// if !r.OK { return r }
const (
O_APPEND = os.O_APPEND
O_CREATE = os.O_CREATE
O_EXCL = os.O_EXCL
O_RDONLY = os.O_RDONLY
O_RDWR = os.O_RDWR
O_SYNC = os.O_SYNC
O_TRUNC = os.O_TRUNC
O_WRONLY = os.O_WRONLY
// O_NOFOLLOW (refuse a symlinked final path component) is declared in
// os_nofollow_{unix,windows}.go — it aliases syscall.O_NOFOLLOW on unix
// (banned import, sanctioned there per #1681) and 0 on Windows.
)
// Path separators exposed at core scope.
//
// parts := core.Split("a/b", string(core.PathSeparator))
const (
PathSeparator = os.PathSeparator
PathListSeparator = os.PathListSeparator
)
// (Note: core.Signal is the existing Core primitive in signal.go for
// signal-event handling — distinct from os.Signal the interface. Use
// c.Signal() for the action-based signal surface.)
// Stdin returns the canonical standard input stream as an io.Reader.
//
// scanner := core.NewLineScanner(core.Stdin())
func Stdin() Reader {
return os.Stdin
}
// Stdout returns the canonical standard output stream as an io.Writer.
//
// core.WriteString(core.Stdout(), "ready\n")
func Stdout() Writer {
return os.Stdout
}
// Stderr returns the canonical standard error stream as an io.Writer.
//
// core.WriteString(core.Stderr(), "warning\n")
func Stderr() Writer {
return os.Stderr
}
// ReadFile reads the named file and returns its bytes.
//
// r := core.ReadFile("config/agent.json")
// if r.OK { data := r.Value.([]byte); _ = data }
func ReadFile(p string) Result {
data, err := os.ReadFile(p)
if err != nil {
return Result{err, false}
}
return Result{data, true}
}
// WriteFile writes data to the named file with mode.
//
// r := core.WriteFile("config/agent.json", []byte("{}"), 0o644)
func WriteFile(p string, data []byte, mode FileMode) Result {
if err := os.WriteFile(p, data, mode); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// MkdirAll creates a directory path and all missing parents.
//
// r := core.MkdirAll("logs/agent", 0o755)
func MkdirAll(p string, mode FileMode) Result {
if err := os.MkdirAll(p, mode); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// Mkdir creates one directory.
//
// r := core.Mkdir("logs", 0o755)
func Mkdir(p string, mode FileMode) Result {
if err := os.Mkdir(p, mode); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// Create creates or truncates the named file.
//
// r := core.Create("logs/agent.log")
// if r.OK { file := r.Value.(*core.OSFile); _ = file }
func Create(p string) Result {
return Result{}.New(os.Create(p))
}
// Open opens the named file for reading.
//
// r := core.Open("config/agent.json")
func Open(p string) Result {
return Result{}.New(os.Open(p))
}
// OpenFile opens the named file with explicit flags and mode.
//
// r := core.OpenFile("logs/agent.log", core.O_APPEND|core.O_CREATE|core.O_WRONLY, 0o644)
func OpenFile(p string, flag int, mode FileMode) Result {
return Result{}.New(os.OpenFile(p, flag, mode))
}
// Stat returns file information for p.
//
// r := core.Stat("config/agent.json")
func Stat(p string) Result {
return Result{}.New(os.Stat(p))
}
// Lstat returns file information for p without following a final symlink.
//
// r := core.Lstat("config/current")
func Lstat(p string) Result {
return Result{}.New(os.Lstat(p))
}
// Remove removes the named file or empty directory.
//
// r := core.Remove("logs/old-agent.log")
func Remove(p string) Result {
if err := os.Remove(p); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// RemoveAll removes a path and any children.
//
// r := core.RemoveAll("tmp/session-42")
func RemoveAll(p string) Result {
if err := os.RemoveAll(p); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// Rename renames oldPath to newPath.
//
// r := core.Rename("config.tmp", "config.json")
func Rename(oldPath, newPath string) Result {
if err := os.Rename(oldPath, newPath); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// Chmod changes the mode of the named file. Unlike c.Fs() operations
// this is unsandboxed boundary I/O — reach for it only when extracting
// archives or fixing up permissions outside a workspace root.
//
// r := core.Chmod("bin/agent", 0o755)
func Chmod(p string, mode FileMode) Result {
if err := os.Chmod(p, mode); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// Symlink creates newPath as a symbolic link to oldPath.
//
// r := core.Symlink("releases/v2", "current")
func Symlink(oldPath, newPath string) Result {
if err := os.Symlink(oldPath, newPath); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// Readlink returns the destination of the named symbolic link. To
// resolve a whole chain to its final target use core.PathEvalSymlinks;
// Readlink reads only the single link's stored value.
//
// r := core.Readlink("current")
// if r.OK { target := r.Value.(string); _ = target }
func Readlink(p string) Result {
return Result{}.New(os.Readlink(p))
}
// MkdirTemp creates a new temporary directory.
//
// r := core.MkdirTemp("", "agent-*")
func MkdirTemp(dir, pattern string) Result {
return Result{}.New(os.MkdirTemp(dir, pattern))
}
// CreateTemp creates and opens a new temporary file. A "*" in pattern
// is replaced by a random string; an empty dir uses TempDir(). The
// file-form sibling of MkdirTemp — close and remove it when done.
//
// r := core.CreateTemp("", "openapi-*.json")
// if r.OK { f := r.Value.(*core.OSFile); defer core.Remove(f.Name()) }
func CreateTemp(dir, pattern string) Result {
return Result{}.New(os.CreateTemp(dir, pattern))
}
// TempDir returns the default directory for temporary files.
//
// dir := core.TempDir()
func TempDir() string {
return os.TempDir()
}
// IsNotExist reports whether err indicates a missing path.
//
// if core.IsNotExist(err) { core.Println("missing") }
func IsNotExist(err error) bool {
return os.IsNotExist(err)
}
// IsExist reports whether err indicates an existing path.
//
// if core.IsExist(err) { core.Println("exists") }
func IsExist(err error) bool {
return os.IsExist(err)
}
// IsPermission reports whether err indicates a permission failure.
//
// if core.IsPermission(err) { core.Println("denied") }
func IsPermission(err error) bool {
return os.IsPermission(err)
}
// Sentinel errors for the OS boundary, re-exported so consumers can
// match against them with core.Is (errors.Is) without importing os.
// These pair with the IsNotExist / IsExist / IsPermission predicates
// above — use the predicate when wrapping an errno-bearing OS error,
// use the sentinel when comparing a value you produced or received
// directly.
//
// if core.Is(err, core.ErrNotExist) { core.Println("missing") }
var (
ErrNotExist = os.ErrNotExist // file or directory does not exist
ErrExist = os.ErrExist // file already exists
ErrPermission = os.ErrPermission // permission denied
ErrInvalid = os.ErrInvalid // invalid argument (e.g. nil *File method)
ErrClosed = os.ErrClosed // operation on an already-closed file
)
// DirFS returns an FS rooted at the given directory path.
//
// fsys := core.DirFS("/path/to/templates")
func DirFS(dir string) FS {
return os.DirFS(dir)
}
// Args returns the command-line arguments.
//
// args := core.Args()
func Args() []string {
return os.Args
}
// Hostname returns the kernel host name.
//
// r := core.Hostname()
func Hostname() Result {
return Result{}.New(os.Hostname())
}
// Executable returns the absolute path of the binary that started the
// current process. Use it to locate sibling assets shipped next to the
// binary; prefer Args()[0] only when the launch path itself matters.
//
// r := core.Executable()
// if r.OK { dir := core.PathDir(r.Value.(string)); _ = dir }
func Executable() Result {
return Result{}.New(os.Executable())
}
// Getpid returns the process id of the caller.
//
// pid := core.Getpid()
func Getpid() int {
return os.Getpid()
}
// Getppid returns the parent process id of the caller.
//
// ppid := core.Getppid()
func Getppid() int {
return os.Getppid()
}
// Getwd returns the current working directory.
//
// r := core.Getwd()
func Getwd() Result {
return Result{}.New(os.Getwd())
}
// Chdir changes the current working directory.
//
// r := core.Chdir("/tmp")
func Chdir(dir string) Result {
if err := os.Chdir(dir); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// UserHomeDir returns the current user's home directory.
//
// r := core.UserHomeDir()
func UserHomeDir() Result {
return Result{}.New(os.UserHomeDir())
}
// UserConfigDir returns the default root directory for user configuration.
//
// r := core.UserConfigDir()
func UserConfigDir() Result {
return Result{}.New(os.UserConfigDir())
}
// UserCacheDir returns the default root directory for user cache data.
//
// r := core.UserCacheDir()
func UserCacheDir() Result {
return Result{}.New(os.UserCacheDir())
}
// Environ returns a copy of strings representing the environment.
//
// env := core.Environ()
func Environ() []string {
return os.Environ()
}
// Getenv retrieves the value of the environment variable named by key.
//
// token := core.Getenv("FORGE_TOKEN")
func Getenv(key string) string {
return os.Getenv(key)
}
// Setenv sets an environment variable. Returns Result with OK=false +
// Code "env.invalid" when the OS rejects the assignment (e.g. key
// containing '=' or NUL).
//
// r := core.Setenv("FORGE_TOKEN", token)
// if !r.OK { return r }
func Setenv(key, value string) Result {
if err := os.Setenv(key, value); err != nil {
return Result{Value: WrapCode(err, "env.invalid", "Setenv", "OS rejected env assignment"), OK: false}
}
return Result{OK: true}
}
// Unsetenv removes an environment variable. Returns Result with
// OK=false + Code "env.invalid" when the OS rejects the removal.
//
// r := core.Unsetenv("FORGE_TOKEN")
// if !r.OK { return r }
func Unsetenv(key string) Result {
if err := os.Unsetenv(key); err != nil {
return Result{Value: WrapCode(err, "env.invalid", "Unsetenv", "OS rejected env removal"), OK: false}
}
return Result{OK: true}
}
// LookupEnv retrieves the value of the environment variable named by key.
//
// value, ok := core.LookupEnv("FORGE_TOKEN")
func LookupEnv(key string) (string, bool) {
return os.LookupEnv(key)
}
// osExit is the test hook for process termination. Production wires it to
// os.Exit here so os.go remains the sole production os owner.
var osExit = os.Exit
// Exit terminates the current process with code.
//
// core.Exit(1)
func Exit(code int) {
osExit(code)
}