github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/pkg/localcommit/localcommit.go (about)

     1  package localcommit
     2  
     3  import (
     4  	"github.com/ActiveState/cli/internal/errs"
     5  	"github.com/ActiveState/cli/internal/locale"
     6  	"github.com/ActiveState/cli/pkg/project"
     7  	"github.com/go-openapi/strfmt"
     8  )
     9  
    10  // proj holds the project instance most recently accessed, if any.
    11  // Using globals in this way is an anti-pattern, but because the commit mechanic is going through a lot of changes
    12  // we're currently handling it this way to help further refactors. Once we've landed the go-forward mechanic we should
    13  // remove this anti-pattern.
    14  // https://activestatef.atlassian.net/browse/DX-2524
    15  var proj *project.Project
    16  
    17  type ErrInvalidCommitID struct {
    18  	error
    19  	CommitID string
    20  }
    21  
    22  func setupProject(pjpath string) error {
    23  	if proj != nil && proj.Dir() == pjpath {
    24  		return nil
    25  	}
    26  	var err error
    27  	proj, err = project.FromPath(pjpath)
    28  	if err != nil {
    29  		return errs.Wrap(err, "Could not get project info to set up project")
    30  	}
    31  	return nil
    32  }
    33  
    34  func Get(pjpath string) (strfmt.UUID, error) {
    35  	if err := setupProject(pjpath); err != nil {
    36  		return "", errs.Wrap(err, "Could not setup project")
    37  	}
    38  
    39  	commitID := proj.LegacyCommitID()
    40  	if !strfmt.IsUUID(commitID) {
    41  		return "", &ErrInvalidCommitID{errs.New("Invalid commit ID"), commitID}
    42  	}
    43  
    44  	return strfmt.UUID(commitID), nil
    45  }
    46  
    47  func Set(pjpath, commitID string) error {
    48  	if !strfmt.IsUUID(commitID) {
    49  		return locale.NewInputError("err_commit_id_invalid", commitID)
    50  	}
    51  
    52  	if err := setupProject(pjpath); err != nil {
    53  		return errs.Wrap(err, "Could not setup project")
    54  	}
    55  
    56  	if err := proj.SetLegacyCommit(commitID); err != nil {
    57  		return errs.Wrap(err, "Could not set commit ID")
    58  	}
    59  
    60  	return nil
    61  }