func checkoutGit()

in scan/git.go [152:195]


func checkoutGit(root, ref, subdir string) (string, error) {
	// Try checking out by ref name first. This will work on branches and sets
	// .git/HEAD to the current branch name
	// If the reference format is "pull/{pull-request-number}/head" (for GitHub Repo)
	// or "pull/{pull-request-number}/merge" (for AzureDevOps Repo), then checkout to
	// FETCH_HEAD. Previous step has already fetched the reference explicitly, and
	// current step just needs to check out the head
	if (strings.HasPrefix(ref, "pull/") || strings.HasPrefix(ref, "refs/pull/")) &&
		(strings.HasSuffix(ref, "/head") || strings.HasSuffix(ref, "/merge")) {
		output, err := gitWithinDir(root, "checkout", "FETCH_HEAD")
		if err != nil {
			return "", errors.Wrapf(err, "error checking out %s: %s", ref, output)
		}
	} else if output, err := gitWithinDir(root, "checkout", ref); err != nil {
		// If the branch name is specified, then it means the branch does not exist,
		// so throw an error
		if ref != "" {
			return "", errors.Wrapf(err, "error checking out %s: %s", ref, output)
		}

		// If the branch name is not specified, check out the last fetched ref
		if output2, err2 := gitWithinDir(root, "checkout", "FETCH_HEAD"); err2 != nil {
			return "", errors.Wrapf(err, "error checking out (no specified branch): %s", output2)
		}
	}

	if subdir != "" {
		newCtx, err := symlink.FollowSymlinkInScope(filepath.Join(root, subdir), root)
		if err != nil {
			return "", errors.Wrapf(err, "error setting git context, %q not within git root", subdir)
		}

		fi, err := os.Stat(newCtx)
		if err != nil {
			return "", err
		}
		if !fi.IsDir() {
			return "", errors.Errorf("error setting git context, not a directory: %s", newCtx)
		}
		root = newCtx
	}

	return root, nil
}