github.com/avfs/avfs@v0.33.1-0.20240303173310-c6ba67c33eb7/vfs/basepathfs/basepathfs_internal.go (about)

     1  //
     2  //  Copyright 2020 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 basepathfs
    18  
    19  import (
    20  	"io/fs"
    21  	"os"
    22  	"strings"
    23  
    24  	"github.com/avfs/avfs"
    25  )
    26  
    27  // toBasePath transforms a BasePathFS path to a BaseFS path.
    28  func (vfs *BasePathFS) toBasePath(path string) string {
    29  	if vfs.IsAbs(path) {
    30  		vl := avfs.VolumeNameLen(vfs, path)
    31  
    32  		return vfs.basePath + path[vl:]
    33  	}
    34  
    35  	return path
    36  }
    37  
    38  // fromBasePath returns a BasePathFS path from a BaseFs path.
    39  func (vfs *BasePathFS) fromBasePath(path string) string {
    40  	if strings.HasPrefix(path, vfs.basePath) {
    41  		vl := avfs.VolumeNameLen(vfs, path)
    42  
    43  		return path[:vl] + path[len(vfs.basePath):]
    44  	}
    45  
    46  	return path
    47  }
    48  
    49  // restoreError restore paths in errors if necessary.
    50  func (vfs *BasePathFS) restoreError(err error) error {
    51  	if err == nil {
    52  		return nil
    53  	}
    54  
    55  	switch e := err.(type) {
    56  	case *fs.PathError:
    57  		return &fs.PathError{
    58  			Op:   e.Op,
    59  			Path: vfs.fromBasePath(e.Path),
    60  			Err:  e.Err,
    61  		}
    62  	case *os.LinkError:
    63  		return &os.LinkError{
    64  			Op:  e.Op,
    65  			Old: vfs.fromBasePath(e.Old),
    66  			New: vfs.fromBasePath(e.New),
    67  			Err: e.Err,
    68  		}
    69  	default:
    70  		return err
    71  	}
    72  }