Merge pull request #102 from lsmoura/sergio/no-ctx-ptr

Remove context pointers since there is no need to pass around a pointer to an interface
This commit is contained in:
David Dworken 2023-09-06 19:58:08 -07:00 committed by GitHub
commit c5bdee9ad5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 58 additions and 52 deletions

View File

@ -28,13 +28,13 @@ var disableCmd = &cobra.Command{
},
}
func Enable(ctx *context.Context) error {
func Enable(ctx context.Context) error {
config := hctx.GetConf(ctx)
config.IsEnabled = true
return hctx.SetConfig(config)
}
func Disable(ctx *context.Context) error {
func Disable(ctx context.Context) error {
config := hctx.GetConf(ctx)
config.IsEnabled = false
return hctx.SetConfig(config)

View File

@ -475,7 +475,7 @@ func copyFile(src, dst string) error {
return destination.Close()
}
func uninstall(ctx *context.Context) error {
func uninstall(ctx context.Context) error {
homedir := hctx.GetHome(ctx)
err := stripLines(path.Join(homedir, ".bashrc"), getBashConfigFragment(homedir))
if err != nil {

View File

@ -60,7 +60,7 @@ var exportCmd = &cobra.Command{
},
}
func export(ctx *context.Context, query string) {
func export(ctx context.Context, query string) {
db := hctx.GetDb(ctx)
err := lib.RetrieveAdditionalEntriesFromRemote(ctx)
if err != nil {
@ -77,7 +77,7 @@ func export(ctx *context.Context, query string) {
}
}
func query(ctx *context.Context, query string) {
func query(ctx context.Context, query string) {
db := hctx.GetDb(ctx)
err := lib.RetrieveAdditionalEntriesFromRemote(ctx)
if err != nil {
@ -94,7 +94,7 @@ func query(ctx *context.Context, query string) {
lib.CheckFatalError(lib.DisplayResults(ctx, data, numResults))
}
func displayBannerIfSet(ctx *context.Context) error {
func displayBannerIfSet(ctx context.Context) error {
respBody, err := lib.GetBanner(ctx)
if lib.IsOfflineError(err) {
return nil

View File

@ -33,7 +33,7 @@ var redactCmd = &cobra.Command{
},
}
func redact(ctx *context.Context, query string, force bool) error {
func redact(ctx context.Context, query string, force bool) error {
tx, err := lib.MakeWhereQueryFromSearch(ctx, hctx.GetDb(ctx), query)
if err != nil {
return err
@ -75,7 +75,7 @@ func redact(ctx *context.Context, query string, force bool) error {
return nil
}
func deleteOnRemoteInstances(ctx *context.Context, historyEntries []*data.HistoryEntry) error {
func deleteOnRemoteInstances(ctx context.Context, historyEntries []*data.HistoryEntry) error {
config := hctx.GetConf(ctx)
if config.IsOffline {
return nil

View File

@ -44,7 +44,7 @@ var presaveHistoryEntryCmd = &cobra.Command{
},
}
func maybeUploadSkippedHistoryEntries(ctx *context.Context) error {
func maybeUploadSkippedHistoryEntries(ctx context.Context) error {
config := hctx.GetConf(ctx)
if !config.HaveMissedUploads {
return nil
@ -81,7 +81,7 @@ func maybeUploadSkippedHistoryEntries(ctx *context.Context) error {
return nil
}
func presaveHistoryEntry(ctx *context.Context) {
func presaveHistoryEntry(ctx context.Context) {
config := hctx.GetConf(ctx)
if !config.IsEnabled {
return
@ -122,7 +122,7 @@ func presaveHistoryEntry(ctx *context.Context) {
// TODO: Consider improving this
}
func saveHistoryEntry(ctx *context.Context) {
func saveHistoryEntry(ctx context.Context) {
config := hctx.GetConf(ctx)
if !config.IsEnabled {
hctx.GetLogger().Infof("Skipping saving a history entry because hishtory is disabled\n")
@ -218,7 +218,7 @@ func init() {
rootCmd.AddCommand(presaveHistoryEntryCmd)
}
func buildPreArgsHistoryEntry(ctx *context.Context) (*data.HistoryEntry, error) {
func buildPreArgsHistoryEntry(ctx context.Context) (*data.HistoryEntry, error) {
var entry data.HistoryEntry
// user
@ -257,7 +257,7 @@ func buildPreArgsHistoryEntry(ctx *context.Context) (*data.HistoryEntry, error)
return &entry, nil
}
func buildHistoryEntry(ctx *context.Context, args []string) (*data.HistoryEntry, error) {
func buildHistoryEntry(ctx context.Context, args []string) (*data.HistoryEntry, error) {
if len(args) < 6 {
hctx.GetLogger().Warnf("buildHistoryEntry called with args=%#v, which has too few entries! This can happen in specific edge cases for newly opened terminals and is likely not a problem.", args)
return nil, nil
@ -327,7 +327,7 @@ func trimTrailingWhitespace(s string) string {
return strings.TrimSuffix(strings.TrimSuffix(s, "\n"), " ")
}
func buildCustomColumns(ctx *context.Context) (data.CustomColumns, error) {
func buildCustomColumns(ctx context.Context) (data.CustomColumns, error) {
ccs := data.CustomColumns{}
config := hctx.GetConf(ctx)
for _, cc := range config.CustomColumns {
@ -465,7 +465,7 @@ func getLastCommand(history string) (string, error) {
return split[1], nil
}
func shouldSkipHiddenCommand(ctx *context.Context, historyLine string) (bool, error) {
func shouldSkipHiddenCommand(ctx context.Context, historyLine string) (bool, error) {
config := hctx.GetConf(ctx)
if config.LastSavedHistoryLine == historyLine {
return true, nil
@ -478,7 +478,7 @@ func shouldSkipHiddenCommand(ctx *context.Context, historyLine string) (bool, er
return false, nil
}
func getCwd(ctx *context.Context) (string, string, error) {
func getCwd(ctx context.Context) (string, string, error) {
cwd, err := getCwdWithoutSubstitution()
if err != nil {
return "", "", fmt.Errorf("failed to get cwd for last command: %w", err)

View File

@ -108,44 +108,50 @@ func OpenLocalSqliteDb() (*gorm.DB, error) {
type hishtoryContextKey string
func MakeContext() *context.Context {
const (
configCtxKey hishtoryContextKey = "config"
dbCtxKey hishtoryContextKey = "db"
homedirCtxKey hishtoryContextKey = "homedir"
)
func MakeContext() context.Context {
ctx := context.Background()
config, err := GetConfig()
if err != nil {
panic(fmt.Errorf("failed to retrieve config: %w", err))
}
ctx = context.WithValue(ctx, hishtoryContextKey("config"), config)
ctx = context.WithValue(ctx, configCtxKey, config)
db, err := OpenLocalSqliteDb()
if err != nil {
panic(fmt.Errorf("failed to open local DB: %w", err))
}
ctx = context.WithValue(ctx, hishtoryContextKey("db"), db)
ctx = context.WithValue(ctx, dbCtxKey, db)
homedir, err := os.UserHomeDir()
if err != nil {
panic(fmt.Errorf("failed to get homedir: %w", err))
}
ctx = context.WithValue(ctx, hishtoryContextKey("homedir"), homedir)
return &ctx
ctx = context.WithValue(ctx, homedirCtxKey, homedir)
return ctx
}
func GetConf(ctx *context.Context) ClientConfig {
v := (*ctx).Value(hishtoryContextKey("config"))
func GetConf(ctx context.Context) ClientConfig {
v := ctx.Value(configCtxKey)
if v != nil {
return v.(ClientConfig)
}
panic(fmt.Errorf("failed to find config in ctx"))
}
func GetDb(ctx *context.Context) *gorm.DB {
v := (*ctx).Value(hishtoryContextKey("db"))
func GetDb(ctx context.Context) *gorm.DB {
v := ctx.Value(dbCtxKey)
if v != nil {
return v.(*gorm.DB)
}
panic(fmt.Errorf("failed to find db in ctx"))
}
func GetHome(ctx *context.Context) string {
v := (*ctx).Value(hishtoryContextKey("homedir"))
func GetHome(ctx context.Context) string {
v := ctx.Value(homedirCtxKey)
if v != nil {
return v.(string)
}

View File

@ -123,7 +123,7 @@ func AddToDbIfNew(db *gorm.DB, entry data.HistoryEntry) {
}
}
func getCustomColumnValue(ctx *context.Context, header string, entry data.HistoryEntry) (string, error) {
func getCustomColumnValue(ctx context.Context, header string, entry data.HistoryEntry) (string, error) {
for _, c := range entry.CustomColumns {
if strings.EqualFold(c.Name, header) {
return c.Val, nil
@ -138,7 +138,7 @@ func getCustomColumnValue(ctx *context.Context, header string, entry data.Histor
return "", fmt.Errorf("failed to find a column matching the column name %#v (is there a typo?)", header)
}
func buildTableRow(ctx *context.Context, columnNames []string, entry data.HistoryEntry) ([]string, error) {
func buildTableRow(ctx context.Context, columnNames []string, entry data.HistoryEntry) ([]string, error) {
row := make([]string, 0)
for _, header := range columnNames {
switch header {
@ -180,7 +180,7 @@ func stringArrayToAnyArray(arr []string) []any {
return ret
}
func DisplayResults(ctx *context.Context, results []*data.HistoryEntry, numResults int) error {
func DisplayResults(ctx context.Context, results []*data.HistoryEntry, numResults int) error {
config := hctx.GetConf(ctx)
headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc()
@ -213,7 +213,7 @@ func DisplayResults(ctx *context.Context, results []*data.HistoryEntry, numResul
return nil
}
func IsEnabled(ctx *context.Context) (bool, error) {
func IsEnabled(ctx context.Context) (bool, error) {
return hctx.GetConf(ctx).IsEnabled, nil
}
@ -243,7 +243,7 @@ func isBashWeirdness(cmd string) bool {
return firstCommandBugRegex.MatchString(cmd)
}
func ImportHistory(ctx *context.Context, shouldReadStdin, force bool) (int, error) {
func ImportHistory(ctx context.Context, shouldReadStdin, force bool) (int, error) {
config := hctx.GetConf(ctx)
if config.HaveCompletedInitialImport && !force {
// Don't run an import if we already have run one. This avoids importing the same entry multiple times.
@ -405,7 +405,7 @@ func getTmpClientPath() string {
return path.Join(tmpDir, "hishtory-client")
}
func Update(ctx *context.Context) error {
func Update(ctx context.Context) error {
// Download the binary
downloadData, err := GetDownloadData()
if err != nil {
@ -465,7 +465,7 @@ func Update(ctx *context.Context) error {
return nil
}
func verifyBinaryMac(ctx *context.Context, binaryPath string, downloadData shared.UpdateInfo) error {
func verifyBinaryMac(ctx context.Context, binaryPath string, downloadData shared.UpdateInfo) error {
// On Mac, binary verification is a bit more complicated since mac binaries are code
// signed. To verify a signed binary, we:
// 1. Download the unsigned binary
@ -747,7 +747,7 @@ func EncryptAndMarshal(config hctx.ClientConfig, entries []*data.HistoryEntry) (
return jsonValue, nil
}
func Reupload(ctx *context.Context) error {
func Reupload(ctx context.Context) error {
config := hctx.GetConf(ctx)
if config.IsOffline {
return nil
@ -769,7 +769,7 @@ func Reupload(ctx *context.Context) error {
return nil
}
func RetrieveAdditionalEntriesFromRemote(ctx *context.Context) error {
func RetrieveAdditionalEntriesFromRemote(ctx context.Context) error {
db := hctx.GetDb(ctx)
config := hctx.GetConf(ctx)
if config.IsOffline {
@ -797,7 +797,7 @@ func RetrieveAdditionalEntriesFromRemote(ctx *context.Context) error {
return ProcessDeletionRequests(ctx)
}
func ProcessDeletionRequests(ctx *context.Context) error {
func ProcessDeletionRequests(ctx context.Context) error {
config := hctx.GetConf(ctx)
if config.IsOffline {
return nil
@ -826,7 +826,7 @@ func ProcessDeletionRequests(ctx *context.Context) error {
return nil
}
func GetBanner(ctx *context.Context) ([]byte, error) {
func GetBanner(ctx context.Context) ([]byte, error) {
config := hctx.GetConf(ctx)
if config.IsOffline {
return []byte{}, nil
@ -840,7 +840,7 @@ func parseTimeGenerously(input string) (time.Time, error) {
return dateparse.ParseLocal(input)
}
func MakeWhereQueryFromSearch(ctx *context.Context, db *gorm.DB, query string) (*gorm.DB, error) {
func MakeWhereQueryFromSearch(ctx context.Context, db *gorm.DB, query string) (*gorm.DB, error) {
tokens, err := tokenize(query)
if err != nil {
return nil, fmt.Errorf("failed to tokenize query: %w", err)
@ -883,7 +883,7 @@ func MakeWhereQueryFromSearch(ctx *context.Context, db *gorm.DB, query string) (
return tx, nil
}
func Search(ctx *context.Context, db *gorm.DB, query string, limit int) ([]*data.HistoryEntry, error) {
func Search(ctx context.Context, db *gorm.DB, query string, limit int) ([]*data.HistoryEntry, error) {
if ctx == nil && query != "" {
return nil, fmt.Errorf("lib.Search called with a nil context and a non-empty query (this should never happen)")
}
@ -913,7 +913,7 @@ func parseNonAtomizedToken(token string) (string, interface{}, interface{}, inte
return "(command LIKE ? OR hostname LIKE ? OR current_working_directory LIKE ?)", wildcardedToken, wildcardedToken, wildcardedToken, nil
}
func parseAtomizedToken(ctx *context.Context, token string) (string, interface{}, interface{}, error) {
func parseAtomizedToken(ctx context.Context, token string) (string, interface{}, interface{}, error) {
splitToken := splitEscaped(token, ':', 2)
field := unescape(splitToken[0])
val := unescape(splitToken[1])
@ -978,7 +978,7 @@ func parseAtomizedToken(ctx *context.Context, token string) (string, interface{}
}
}
func getAllCustomColumnNames(ctx *context.Context) ([]string, error) {
func getAllCustomColumnNames(ctx context.Context) ([]string, error) {
db := hctx.GetDb(ctx)
query := `
SELECT DISTINCT json_extract(value, '$.name') as cc_name

View File

@ -15,7 +15,7 @@ import (
"github.com/slsa-framework/slsa-verifier/verifiers"
)
func verify(ctx *context.Context, provenance []byte, artifactHash, source, branch, versionTag string) error {
func verify(ctx context.Context, provenance []byte, artifactHash, source, branch, versionTag string) error {
provenanceOpts := &options.ProvenanceOpts{
ExpectedSourceURI: source,
ExpectedBranch: &branch,
@ -23,7 +23,7 @@ func verify(ctx *context.Context, provenance []byte, artifactHash, source, branc
ExpectedVersionedTag: &versionTag,
}
builderOpts := &options.BuilderOpts{}
_, _, err := verifiers.Verify(*ctx, provenance, artifactHash, provenanceOpts, builderOpts)
_, _, err := verifiers.Verify(ctx, provenance, artifactHash, provenanceOpts, builderOpts)
return err
}
@ -42,7 +42,7 @@ func checkForDowngrade(currentVersionS, newVersionS string) error {
return nil
}
func verifyBinary(ctx *context.Context, binaryPath, attestationPath, versionTag string) error {
func verifyBinary(ctx context.Context, binaryPath, attestationPath, versionTag string) error {
if os.Getenv("HISHTORY_DISABLE_SLSA_ATTESTATION") == "true" {
return nil
}

View File

@ -136,7 +136,7 @@ const (
type model struct {
// context
ctx *context.Context
ctx context.Context
// Model for the loading spinner.
spinner spinner.Model
@ -187,7 +187,7 @@ type asyncQueryFinishedMsg struct {
maintainCursor bool
}
func initialModel(ctx *context.Context, t table.Model, tableEntries []*data.HistoryEntry, initialQuery string) model {
func initialModel(ctx context.Context, t table.Model, tableEntries []*data.HistoryEntry, initialQuery string) model {
s := spinner.New()
s.Spinner = spinner.Dot
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
@ -362,7 +362,7 @@ func (m model) View() string {
return fmt.Sprintf("\n%s%s%s\nSearch Query: %s\n\n%s\n", loadingMessage, warning, m.banner, m.queryInput.View(), baseStyle.Render(m.table.View())) + helpView
}
func getRows(ctx *context.Context, columnNames []string, query string, numEntries int) ([]table.Row, []*data.HistoryEntry, error) {
func getRows(ctx context.Context, columnNames []string, query string, numEntries int) ([]table.Row, []*data.HistoryEntry, error) {
db := hctx.GetDb(ctx)
config := hctx.GetConf(ctx)
searchResults, err := Search(ctx, db, query, numEntries)
@ -409,7 +409,7 @@ func getTerminalSize() (int, int, error) {
var bigQueryResults []table.Row
func makeTableColumns(ctx *context.Context, columnNames []string, rows []table.Row) ([]table.Column, error) {
func makeTableColumns(ctx context.Context, columnNames []string, rows []table.Row) ([]table.Column, error) {
// Handle an initial query with no results
if len(rows) == 0 || len(rows[0]) == 0 {
allRows, _, err := getRows(ctx, columnNames, "", 25)
@ -499,7 +499,7 @@ func min(a, b int) int {
return b
}
func makeTable(ctx *context.Context, rows []table.Row) (table.Model, error) {
func makeTable(ctx context.Context, rows []table.Row) (table.Model, error) {
config := hctx.GetConf(ctx)
columns, err := makeTableColumns(ctx, config.DisplayedColumns, rows)
if err != nil {
@ -549,7 +549,7 @@ func makeTable(ctx *context.Context, rows []table.Row) (table.Model, error) {
return t, nil
}
func deleteHistoryEntry(ctx *context.Context, entry data.HistoryEntry) error {
func deleteHistoryEntry(ctx context.Context, entry data.HistoryEntry) error {
db := hctx.GetDb(ctx)
// Delete locally
r := db.Model(&data.HistoryEntry{}).Where("device_id = ? AND end_time = ?", entry.DeviceId, entry.EndTime).Delete(&data.HistoryEntry{})
@ -570,7 +570,7 @@ func deleteHistoryEntry(ctx *context.Context, entry data.HistoryEntry) error {
return SendDeletionRequest(dr)
}
func TuiQuery(ctx *context.Context, initialQuery string) error {
func TuiQuery(ctx context.Context, initialQuery string) error {
lipgloss.SetColorProfile(termenv.ANSI)
rows, entries, err := getRows(ctx, hctx.GetConf(ctx).DisplayedColumns, initialQuery, PADDED_NUM_ENTRIES)
if err != nil {