github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/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  	"fmt"
    19  	"path"
    20  	"strings"
    21  )
    22  
    23  // A WorkingSetRef is not a DoltRef, and doesn't live in the |refs/| namespace. But it functions similarly to DoltRefs
    24  type WorkingSetRef struct {
    25  	name string
    26  }
    27  
    28  const WorkingSetRefPrefix = "workingSets"
    29  
    30  // NewWorkingSetRef creates a working set ref from a name or a working set ref e.g. heads/master, or
    31  // workingSets/heads/master
    32  func NewWorkingSetRef(workingSetName string) WorkingSetRef {
    33  	prefix := WorkingSetRefPrefix + "/"
    34  	if strings.HasPrefix(workingSetName, prefix) {
    35  		workingSetName = workingSetName[len(prefix):]
    36  	}
    37  
    38  	return WorkingSetRef{workingSetName}
    39  }
    40  
    41  // WorkingSetRefForHead returns a new WorkingSetRef for the head ref given, or an error if the ref given doesn't
    42  // represent a head.
    43  func WorkingSetRefForHead(ref DoltRef) (WorkingSetRef, error) {
    44  	switch ref.GetType() {
    45  	case BranchRefType, WorkspaceRefType:
    46  		return NewWorkingSetRef(path.Join(string(ref.GetType()), ref.GetPath())), nil
    47  	default:
    48  		return WorkingSetRef{}, fmt.Errorf("unsupported type of ref for a working set: %s", ref.GetType())
    49  	}
    50  }
    51  
    52  // GetPath returns the name of the working set
    53  func (r WorkingSetRef) GetPath() string {
    54  	return r.name
    55  }
    56  
    57  func (r WorkingSetRef) ToHeadRef() (DoltRef, error) {
    58  	return Parse(r.GetPath())
    59  }
    60  
    61  // String returns the fully qualified reference name e.g.
    62  // refs/workingSets/my-branch
    63  func (r WorkingSetRef) String() string {
    64  	return path.Join(WorkingSetRefPrefix, r.name)
    65  }
    66  
    67  // IsWorkingSet returns whether the given ref is a working set
    68  func IsWorkingSet(ref string) bool {
    69  	return strings.HasPrefix(ref, WorkingSetRefPrefix)
    70  }