github.com/avfs/avfs@v0.33.1-0.20240303173310-c6ba67c33eb7/ostype.go (about) 1 // 2 // Copyright 2023 The AVFS authors 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 17 package avfs 18 19 import ( 20 "errors" 21 "runtime" 22 ) 23 24 var ErrSetOSType = errors.New("can't set OS type, use build tag 'avfs_setostype' to set OS type") 25 26 // OSType defines the operating system type. 27 type OSType uint16 28 29 //go:generate stringer -type OSType -linecomment -output ostype_string.go 30 31 const ( 32 OsUnknown OSType = iota // Unknown 33 OsLinux // Linux 34 OsWindows // Windows 35 OsDarwin // Darwin 36 ) 37 38 // CurrentOSType returns the current OSType. 39 func CurrentOSType() OSType { 40 return currentOSType 41 } 42 43 // currentOSType is the current OSType. 44 var currentOSType = func() OSType { //nolint:gochecknoglobals // Store the current OS Type. 45 switch runtime.GOOS { 46 case "linux": 47 return OsLinux 48 case "darwin": 49 return OsDarwin 50 case "windows": 51 return OsWindows 52 default: 53 return OsUnknown 54 } 55 }() 56 57 // OSTyper is the interface that wraps the OS type related methods. 58 type OSTyper interface { 59 // OSType returns the operating system type of the file system. 60 OSType() OSType 61 } 62 63 // OSTypeFn provides OS type functions to a file system or an identity manager. 64 type OSTypeFn struct { 65 osType OSType // OSType defines the operating system type. 66 pathSeparator uint8 // pathSeparator is the OS-specific path separator. 67 } 68 69 // OSType returns the operating system type of the file system. 70 func (osf *OSTypeFn) OSType() OSType { 71 return osf.osType 72 } 73 74 // PathSeparator return the OS-specific path separator. 75 func (osf *OSTypeFn) PathSeparator() uint8 { 76 return osf.pathSeparator 77 } 78 79 // SetOSType sets the operating system Type. 80 // If the OS type can't be changed it returns an error. 81 func (osf *OSTypeFn) SetOSType(osType OSType) error { 82 if osType == OsUnknown { 83 osType = CurrentOSType() 84 } 85 86 if BuildFeatures()&FeatSetOSType != 0 && osType != CurrentOSType() { 87 return ErrSetOSType 88 } 89 90 osf.osType = osType 91 92 sep := uint8('/') 93 if osType == OsWindows { 94 sep = '\\' 95 } 96 97 osf.pathSeparator = sep 98 99 return nil 100 }