go.fuchsia.dev/jiri@v0.0.0-20240502161911-b66513b29486/cmd/jiri/cmd_util.go (about)

     1  // Copyright 2017 The Fuchsia Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  	"path"
    11  	"path/filepath"
    12  
    13  	"go.fuchsia.dev/jiri"
    14  	"go.fuchsia.dev/jiri/project"
    15  )
    16  
    17  // currentProject returns the Project containing the current working directory.
    18  // The current working directory must be inside root.
    19  func currentProject(jirix *jiri.X) (project.Project, error) {
    20  	dir, err := os.Getwd()
    21  	if err != nil {
    22  		return project.Project{}, fmt.Errorf("os.Getwd() failed: %s", err)
    23  	}
    24  
    25  	// Walk up the path until we find a project at that path, or hit the jirix.Root parent.
    26  	// Note that we can't just compare path prefixes because of soft links.
    27  	for dir != path.Dir(jirix.Root) && dir != string(filepath.Separator) {
    28  		if isLocal, err := project.IsLocalProject(jirix, dir); err != nil {
    29  			return project.Project{}, fmt.Errorf("Error while checking for local project at path %q: %s", dir, err)
    30  		} else if !isLocal {
    31  			dir = filepath.Dir(dir)
    32  			continue
    33  		}
    34  		p, err := project.ProjectAtPath(jirix, dir)
    35  		if err != nil {
    36  			return project.Project{}, fmt.Errorf("Error while getting project at path %q: %s", dir, err)
    37  		}
    38  		return p, nil
    39  	}
    40  	return project.Project{}, fmt.Errorf("directory %q is not contained in a project", dir)
    41  }