github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/doltcore/ref/workingset_ref.go (about)

     1  // Copyright 2021 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package ref
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  	"path"
    21  	"strings"
    22  )
    23  
    24  // A WorkingSetRef is not a DoltRef, and doesn't live in the |refs/| namespace. But it functions similarly to DoltRefs
    25  type WorkingSetRef struct {
    26  	name string
    27  }
    28  
    29  const WorkingSetRefPrefix = "workingSets"
    30  
    31  // NewWorkingSetRef creates a working set ref from a name or a working set ref e.g. heads/main, or
    32  // workingSets/heads/main
    33  func NewWorkingSetRef(workingSetName string) WorkingSetRef {
    34  	prefix := WorkingSetRefPrefix + "/"
    35  	if strings.HasPrefix(workingSetName, prefix) {
    36  		workingSetName = workingSetName[len(prefix):]
    37  	}
    38  
    39  	return WorkingSetRef{workingSetName}
    40  }
    41  
    42  var ErrWorkingSetUnsupported = errors.New("unsupported type of ref for a working set")
    43  
    44  // WorkingSetRefForHead returns a new WorkingSetRef for the head ref given, or an error if the ref given doesn't
    45  // represent a head.
    46  func WorkingSetRefForHead(ref DoltRef) (WorkingSetRef, error) {
    47  	switch ref.GetType() {
    48  	case BranchRefType, WorkspaceRefType:
    49  		return NewWorkingSetRef(path.Join(string(ref.GetType()), ref.GetPath())), nil
    50  	default:
    51  		return WorkingSetRef{}, fmt.Errorf("%w: %s", ErrWorkingSetUnsupported, ref.GetType())
    52  	}
    53  }
    54  
    55  // GetPath returns the name of the working set
    56  func (r WorkingSetRef) GetPath() string {
    57  	return r.name
    58  }
    59  
    60  func (r WorkingSetRef) ToHeadRef() (DoltRef, error) {
    61  	return Parse(refPrefix + r.GetPath())
    62  }
    63  
    64  // String returns the fully qualified reference name e.g.
    65  // refs/workingSets/my-branch
    66  func (r WorkingSetRef) String() string {
    67  	return path.Join(WorkingSetRefPrefix, r.name)
    68  }
    69  
    70  // IsWorkingSet returns whether the given ref is a working set
    71  func IsWorkingSet(ref string) bool {
    72  	return strings.HasPrefix(ref, WorkingSetRefPrefix)
    73  }