<commit_before>package main

import (
	"crypto/sha1"
	"encoding/base64"
	"flag"
	"fmt"
	"io"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"

	"github.com/howeyc/gopass"
)

func checkinDefaults() {
	fmt.Printf("gojazz checkin [options]\n")
	flag.PrintDefaults()
}

func checkinOp() {
	sandboxPath := flag.String("sandbox", "", "Location of the sandbox to load the files")
	flag.Usage = checkinDefaults
	flag.Parse()

	if *sandboxPath == "" {
		path, err := os.Getwd()
		if err != nil {
			panic(err)
		}

		path = findSandbox(path)
		sandboxPath = &path
	}

	status, err := scmStatus(*sandboxPath, STAGE)
	if err != nil {
		panic(err)
	}

	if status.metaData.isstream {
		panic(simpleWarning("The sandbox is loaded from a stream, which doesn't support check-ins. Load again using a repository workspace."))
		return
	}

	if status.unchanged() {
		panic(simpleWarning("Sandbox is unchanged. Nothing was checked in."))
		return
	}

	fmt.Printf("Password: ")
	password := string(gopass.GetPasswd())

	client, err := NewClient(status.metaData.userId, password)
	if err != nil {
		panic(err)
	}

	scmCheckin(client, status, *sandboxPath)

	// Force a load/reload of the jazzhub sandbox to avoid out of sync when
	//  looking at the changes page
	err = loadWorkspace(client, status.metaData.projectName, status.metaData.workspaceId)
	if err != nil {
		panic(err)
	}
	fmt.Println("Visit the following URL to work with your changes, deliver them to the rest of the team and more:")
	redirect := fmt.Sprintf(jazzHubBaseUrl + "/code/jazzui/changes.html#" + "/code/jazz/Changes/_/file/" + client.GetJazzId() + "-OrionContent/" + status.metaData.projectName)
	fmt.Printf("https://login.jazz.net/psso/proxy/jazzlogin?redirect_uri=%v\n", url.QueryEscape(redirect))
}

func scmCheckin(client *Client, status *status, sandboxPath string) {
	// Get the workspace in order to force the authentication to happen
	//  and get the list of components.
	workspaceId := status.metaData.workspaceId
	ccmBaseUrl := status.metaData.ccmBaseUrl

	components, err := FindComponents(client, status.metaData.ccmBaseUrl, status.metaData.workspaceId)
	if err != nil {
		panic(err)
	}

	// TODO Probe the remote workspace to verify that it is in sync with this sandbox
	//   - Warn the user if they are out of sync
	//   - Tell them that check-in will make a best effort to find the correct places
	//      to attach the local changes
	//   - Ask them if they wish to proceed

	defaultComponentId := ""
	for idx, component := range components {
		if idx == 0 || strings.HasSuffix(component.Name, "Default Component") {
			defaultComponentId = component.ScmInfo.ItemId
			break
		}
	}
	if defaultComponentId == "" {
		panic(simpleWarning("There are no components in your repository workspace."))
	}

	for modifiedpath, _ := range status.Modified {
		fmt.Printf("%v (Modified)\n", modifiedpath)

		localpath := filepath.Join(sandboxPath, modifiedpath)
		stagepath := filepath.Join(sandboxPath, stageFolder, modifiedpath)

		meta, ok := status.metaData.get(localpath, sandboxPath)
		componentId := ""
		if !ok {
			// This shouldn't happen. Log the stack if it does.
			panic(&JazzError{Msg: "Metadata not found for file that was found in the metadata", Log: true})
		} else {
			componentId = meta.ComponentId
		}

		remoteFile, err := Open(client, ccmBaseUrl, workspaceId, componentId, modifiedpath)
		if err != nil {
			panic(err)
		}

		// TODO better checking and matching for the file, perhaps by item ID?
		if remoteFile.info.Directory {
			panic(simpleWarning(fmt.Sprintf("Cannot check-in file at path %v. There is a folder at this location on the remote.", modifiedpath)))
		}
		// Ooops, this is the wrong file
		if remoteFile.info.ScmInfo.ItemId != meta.ItemId {
			panic(simpleWarning(fmt.Sprintf("Cannot check-in file at path %v. It is not the same as the one that was originally loaded", modifiedpath)))
		}

		newmeta := checkinFile(client, stagepath, remoteFile)
		newmeta.Path = localpath

		status.metaData.simplePut(newmeta, sandboxPath)
	}<commit_msg>Avoid panicking prematurely during check-in.<commit_after>package main

import (
	"crypto/sha1"
	"encoding/base64"
	"flag"
	"fmt"
	"io"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"

	"github.com/howeyc/gopass"
)

func checkinDefaults() {
	fmt.Printf("gojazz checkin [options]\n")
	flag.PrintDefaults()
}

func checkinOp() {
	sandboxPath := flag.String("sandbox", "", "Location of the sandbox to load the files")
	flag.Usage = checkinDefaults
	flag.Parse()

	if *sandboxPath == "" {
		path, err := os.Getwd()
		if err != nil {
			panic(err)
		}

		path = findSandbox(path)
		sandboxPath = &path
	}

	status, err := scmStatus(*sandboxPath, STAGE)
	if err != nil {
		panic(err)
	}

	if status.metaData.isstream {
		panic(simpleWarning("The sandbox is loaded from a stream, which doesn't support check-ins. Load again using a repository workspace."))
		return
	}

	if status.unchanged() {
		panic(simpleWarning("Sandbox is unchanged. Nothing was checked in."))
		return
	}

	fmt.Printf("Password: ")
	password := string(gopass.GetPasswd())

	client, err := NewClient(status.metaData.userId, password)
	if err != nil {
		panic(err)
	}

	scmCheckin(client, status, *sandboxPath)

	// Force a load/reload of the jazzhub sandbox to avoid out of sync when
	//  looking at the changes page
	err = loadWorkspace(client, status.metaData.projectName, status.metaData.workspaceId)
	if err != nil {
		panic(err)
	}
	fmt.Println("Visit the following URL to work with your changes, deliver them to the rest of the team and more:")
	redirect := fmt.Sprintf(jazzHubBaseUrl + "/code/jazzui/changes.html#" + "/code/jazz/Changes/_/file/" + client.GetJazzId() + "-OrionContent/" + status.metaData.projectName)
	fmt.Printf("https://login.jazz.net/psso/proxy/jazzlogin?redirect_uri=%v\n", url.QueryEscape(redirect))
}

func scmCheckin(client *Client, status *status, sandboxPath string) {
	// Get the workspace in order to force the authentication to happen
	//  and get the list of components.
	workspaceId := status.metaData.workspaceId
	ccmBaseUrl := status.metaData.ccmBaseUrl

	components, err := FindComponents(client, status.metaData.ccmBaseUrl, status.metaData.workspaceId)
	if err != nil {
		panic(err)
	}

	// TODO Probe the remote workspace to verify that it is in sync with this sandbox
	//   - Warn the user if they are out of sync
	//   - Tell them that check-in will make a best effort to find the correct places
	//      to attach the local changes
	//   - Ask them if they wish to proceed

	defaultComponentId := ""
	for idx, component := range components {
		if idx == 0 || strings.HasSuffix(component.Name, "Default Component") {
			defaultComponentId = component.ScmInfo.ItemId
			break
		}
	}
	if defaultComponentId == "" {
		panic(simpleWarning("There are no components in your repository workspace."))
	}

	for modifiedpath, _ := range status.Modified {
		fmt.Printf("%v (Modified)\n", modifiedpath)

		localpath := filepath.Join(sandboxPath, modifiedpath)
		stagepath := filepath.Join(sandboxPath, stageFolder, modifiedpath)

		meta, ok := status.metaData.get(localpath, sandboxPath)
		componentId := ""
		if !ok {
			// This shouldn't happen. Log the stack if it does.
			panic(&JazzError{Msg: "Metadata not found for file that was found in the metadata", Log: true})
		} else {
			componentId = meta.ComponentId
		}

		remoteFile, err := Open(client, ccmBaseUrl, workspaceId, componentId, modifiedpath)
		if err != nil {
			panic(err)
		}

		// TODO better checking and matching for the file, perhaps by item ID?
		if remoteFile.info.Directory {
			fmt.Printf("Cannot check-in file at path %v. There is a folder at this location on the remote.\n", modifiedpath)
			fmt.Printf("The file has been temporarily backed up in the following location: %v\n", stagepath)
			continue
		}
		// Ooops, this is the wrong file
		if remoteFile.info.ScmInfo.ItemId != meta.ItemId {
			fmt.Printf("Cannot check-in file at path %v. It is not the same as the one that was originally loaded.\n", modifiedpath)
			fmt.Printf("The file has been temporarily backed up in the following location: %v\n", stagepath)
			continue
		}

		newmeta := checkinFile(client, stagepath, remoteFile)
		newmeta.Path = localpath

		status.metaData.simplePut(newmeta, sandboxPath)
	}
{'fraction_non_alphanumeric': 0.11690344329400433, 'fraction_numerical': 0.000963159162051529, 'mean_word_length': 3.9270462633451957, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5948037', 'n_tokens_mistral': 2853, 'n_tokens_neox': 2670, 'n_words': 816}