hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 1,
"code_window": [
"\t\"github.com/cockroachdb/cockroach/pkg/security/username\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/testutils/serverutils\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/util/leaktest\"\n",
"\t\"github.com/stretchr/testify/require\"\n",
")\n",
"\n",
"func TestShowTransferState(t *testing.T) {\n",
"\tdefer leaktest.AfterTest(t)()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/jackc/pgx/v5\"\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 22
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.9955123066902161,
0.17716218531131744,
0.00016547263658139855,
0.00017009329167194664,
0.3744238615036011
] |
{
"id": 1,
"code_window": [
"\t\"github.com/cockroachdb/cockroach/pkg/security/username\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/testutils/serverutils\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/util/leaktest\"\n",
"\t\"github.com/stretchr/testify/require\"\n",
")\n",
"\n",
"func TestShowTransferState(t *testing.T) {\n",
"\tdefer leaktest.AfterTest(t)()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/jackc/pgx/v5\"\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 22
} | // Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package roachpb
import "github.com/cockroachdb/cockroach/pkg/util/interval"
// A SpanGroup is a specialization of interval.RangeGroup which deals
// with key spans. The zero-value of a SpanGroup can be used immediately.
//
// A SpanGroup does not support concurrent use.
type SpanGroup struct {
rg interval.RangeGroup
}
func (g *SpanGroup) checkInit() {
if g.rg == nil {
g.rg = interval.NewRangeTree()
}
}
// Add will attempt to add the provided Spans to the SpanGroup,
// returning whether the addition increased the span of the group
// or not.
func (g *SpanGroup) Add(spans ...Span) bool {
if len(spans) == 0 {
return false
}
ret := false
g.checkInit()
for _, span := range spans {
ret = g.rg.Add(s2r(span)) || ret
}
return ret
}
// Sub will attempt to subtract the provided Spans from the SpanGroup,
// returning whether the subtraction increased the span of the group
// or not.
func (g *SpanGroup) Sub(spans ...Span) bool {
if len(spans) == 0 {
return false
}
ret := false
g.checkInit()
for _, span := range spans {
ret = g.rg.Sub(s2r(span)) || ret
}
return ret
}
// Contains returns whether or not the provided Key is contained
// within the group of Spans in the SpanGroup.
func (g *SpanGroup) Contains(k Key) bool {
if g.rg == nil {
return false
}
return g.rg.Encloses(interval.Range{
Start: interval.Comparable(k),
// Use the next key since range-ends are exclusive.
End: interval.Comparable(k.Next()),
})
}
// Encloses returns whether the provided Span is fully conained within the group
// of Spans in the SpanGroup
func (g *SpanGroup) Encloses(spans ...Span) bool {
if g.rg == nil {
return false
}
for _, span := range spans {
if !g.rg.Encloses(s2r(span)) {
return false
}
}
return true
}
// Len returns the number of Spans currently within the SpanGroup.
// This will always be equal to or less than the number of spans added,
// as spans that overlap will merge to produce a single larger span.
func (g *SpanGroup) Len() int {
if g.rg == nil {
return 0
}
return g.rg.Len()
}
var _ = (*SpanGroup).Len
// Slice will return the contents of the SpanGroup as a slice of Spans.
func (g *SpanGroup) Slice() []Span {
rg := g.rg
if rg == nil {
return nil
}
n := rg.Len()
if n == 0 {
return nil
}
ret := make([]Span, 0, n)
it := rg.Iterator()
for {
rng, next := it.Next()
if !next {
break
}
ret = append(ret, r2s(rng))
}
return ret
}
// ForEach calls the provided function for each span stored in the group.
func (g *SpanGroup) ForEach(op func(span Span) error) error {
return g.rg.ForEach(func(r interval.Range) error {
return op(r2s(r))
})
}
// s2r converts a Span to an interval.Range. Since the Key and
// interval.Comparable types are both just aliases of []byte,
// we don't have to perform any other conversion.
func s2r(s Span) interval.Range {
// Per docs on Span, if the span represents only a single key,
// the EndKey value may be empty. We'll handle this case by
// ensuring we always have an exclusive end key value.
var end = s.EndKey
if len(end) == 0 || s.Key.Equal(s.EndKey) {
end = s.Key.Next()
}
return interval.Range{
Start: interval.Comparable(s.Key),
End: interval.Comparable(end),
}
}
// r2s converts a Range to a Span
func r2s(r interval.Range) Span {
return Span{
Key: Key(r.Start),
EndKey: Key(r.End),
}
}
| pkg/roachpb/span_group.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0002602335880510509,
0.00018082991300616413,
0.00016641172987874597,
0.00017305955407209694,
0.000023625902031199075
] |
{
"id": 1,
"code_window": [
"\t\"github.com/cockroachdb/cockroach/pkg/security/username\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/testutils/serverutils\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/util/leaktest\"\n",
"\t\"github.com/stretchr/testify/require\"\n",
")\n",
"\n",
"func TestShowTransferState(t *testing.T) {\n",
"\tdefer leaktest.AfterTest(t)()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/jackc/pgx/v5\"\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 22
} | statement ok
SET CLUSTER SETTING spanconfig.reconciliation_job.enabled = true;
# Ensure there's a single auto span config reconciliation job in the system,
# and that it's running.
query ITT colnames,retry
SELECT count(*), job_type, status FROM [SHOW AUTOMATIC JOBS] WHERE job_type = 'AUTO SPAN CONFIG RECONCILIATION' GROUP BY (job_type, status)
----
count job_type status
1 AUTO SPAN CONFIG RECONCILIATION running
let $job_id
SELECT job_id FROM [SHOW AUTOMATIC JOBS] WHERE job_type = 'AUTO SPAN CONFIG RECONCILIATION'
# Ensure that the reconciliation job does not appear in SHOW JOBS.
query I colnames
SELECT count(*) FROM [SHOW JOBS] WHERE job_id = $job_id
----
count
0
# Ensure that the job is not cancelable.
statement error not cancelable
CANCEL JOB $job_id
# The job should still be running.
query T colnames
SELECT status FROM [SHOW AUTOMATIC JOBS] WHERE job_id = $job_id
----
status
running
| pkg/sql/logictest/testdata/logic_test/auto_span_config_reconciliation_job | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017343346553388983,
0.00017176147957798094,
0.00016969285206869245,
0.00017195980763062835,
0.0000013393876088230172
] |
{
"id": 1,
"code_window": [
"\t\"github.com/cockroachdb/cockroach/pkg/security/username\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/testutils/serverutils\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils\"\n",
"\t\"github.com/cockroachdb/cockroach/pkg/util/leaktest\"\n",
"\t\"github.com/stretchr/testify/require\"\n",
")\n",
"\n",
"func TestShowTransferState(t *testing.T) {\n",
"\tdefer leaktest.AfterTest(t)()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/jackc/pgx/v5\"\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 22
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package schematelemetrycontroller
import (
"context"
"time"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/scheduledjobs"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
pbtypes "github.com/gogo/protobuf/types"
"github.com/robfig/cron/v3"
)
// SchemaTelemetryScheduleName is the name of the schema telemetry schedule.
const SchemaTelemetryScheduleName = "sql-schema-telemetry"
// SchemaTelemetryRecurrence is the cron-tab string specifying the recurrence
// for schema telemetry job.
var SchemaTelemetryRecurrence = settings.RegisterValidatedStringSetting(
settings.TenantReadOnly,
"sql.schema.telemetry.recurrence",
"cron-tab recurrence for SQL schema telemetry job",
"@weekly", /* defaultValue */
func(_ *settings.Values, s string) error {
if _, err := cron.ParseStandard(s); err != nil {
return errors.Wrap(err, "invalid cron expression")
}
return nil
},
).WithPublic()
// ErrDuplicatedSchedules indicates that there is already a schedule for SQL
// schema telemetry jobs existing in the system.scheduled_jobs table.
var ErrDuplicatedSchedules = errors.New("creating multiple schema telemetry schedules is disallowed")
// ErrVersionGate indicates that SQL schema telemetry jobs or schedules are
// not supported by the current cluster version.
var ErrVersionGate = errors.New("SQL schema telemetry jobs or schedules not supported by current cluster version")
// Controller implements the SQL Schema telemetry subsystem control plane.
// This exposes administrative interfaces that can be consumed by other parts
// of the database (e.g. status server, builtins) to control the behavior of the
// SQL schema telemetry subsystem.
type Controller struct {
db isql.DB
mon *mon.BytesMonitor
st *cluster.Settings
jr *jobs.Registry
clusterID func() uuid.UUID
}
// NewController is a constructor for *Controller.
//
// This constructor needs to be called in the sql package when creating a new
// sql.Server. This is the reason why it and the definition of the Controller
// object live in their own package separate from schematelemetry.
func NewController(
db isql.DB,
mon *mon.BytesMonitor,
st *cluster.Settings,
jr *jobs.Registry,
clusterID func() uuid.UUID,
) *Controller {
return &Controller{
db: db,
mon: mon,
st: st,
jr: jr,
clusterID: clusterID,
}
}
// Start kicks off the async task which acts on schedule update notifications
// and registers the change hook on the schedule recurrence cluster setting.
func (c *Controller) Start(ctx context.Context, stopper *stop.Stopper) {
// ch is used to notify a goroutine to ensure the schedule exists and
// update its recurrence.
ch := make(chan struct{}, 1)
stopper.AddCloser(stop.CloserFn(func() { c.mon.Stop(ctx) }))
// Start a goroutine that ensures the presence of the schema telemetry
// schedule and updates its recurrence.
_ = stopper.RunAsyncTask(ctx, "schema-telemetry-schedule-updater", func(ctx context.Context) {
stopCtx, cancel := stopper.WithCancelOnQuiesce(ctx)
defer cancel()
for {
select {
case <-stopper.ShouldQuiesce():
return
case <-ch:
updateSchedule(stopCtx, c.db, c.st, c.clusterID())
}
}
})
notify := func(name string) {
_ = stopper.RunAsyncTask(ctx, "schema-telemetry-schedule-"+name, func(ctx context.Context) {
// Notify only if the channel is empty, don't bother if another update
// is already pending.
select {
case ch <- struct{}{}:
default:
}
})
}
// Trigger a schedule update to ensure it exists at startup.
notify("ensure-at-startup")
// Add a change hook on the recurrence cluster setting that will notify
// a schedule update.
SchemaTelemetryRecurrence.SetOnChange(&c.st.SV, func(ctx context.Context) {
notify("notify-recurrence-change")
})
}
func updateSchedule(ctx context.Context, db isql.DB, st *cluster.Settings, clusterID uuid.UUID) {
retryOptions := retry.Options{
InitialBackoff: time.Second,
MaxBackoff: 10 * time.Minute,
}
for r := retry.StartWithCtx(ctx, retryOptions); r.Next(); {
if err := db.Txn(ctx, func(ctx context.Context, txn isql.Txn) error {
// Ensure schedule exists.
var sj *jobs.ScheduledJob
{
id, err := GetSchemaTelemetryScheduleID(ctx, txn)
if err != nil {
return err
}
if id == 0 {
sj, err = CreateSchemaTelemetrySchedule(ctx, txn, st)
} else {
sj, err = jobs.ScheduledJobTxn(txn).Load(ctx, scheduledjobs.ProdJobSchedulerEnv, id)
}
if err != nil {
return err
}
}
// Update schedule with new recurrence, if different.
cronExpr := scheduledjobs.MaybeRewriteCronExpr(
clusterID, SchemaTelemetryRecurrence.Get(&st.SV),
)
if sj.ScheduleExpr() == cronExpr {
return nil
}
if err := sj.SetSchedule(cronExpr); err != nil {
return err
}
sj.SetScheduleStatus(string(jobs.StatusPending))
return jobs.ScheduledJobTxn(txn).Update(ctx, sj)
}); err != nil && ctx.Err() == nil {
log.Warningf(ctx, "failed to update SQL schema telemetry schedule: %s", err)
} else {
return
}
}
}
// CreateSchemaTelemetryJob is part of the eval.SchemaTelemetryController
// interface.
func (c *Controller) CreateSchemaTelemetryJob(
ctx context.Context, createdByName string, createdByID int64,
) (id int64, _ error) {
var j *jobs.Job
if err := c.db.Txn(ctx, func(ctx context.Context, txn isql.Txn) (err error) {
r := CreateSchemaTelemetryJobRecord(createdByName, createdByID)
j, err = c.jr.CreateJobWithTxn(ctx, r, c.jr.MakeJobID(), txn)
return err
}); err != nil {
return 0, err
}
return int64(j.ID()), nil
}
// CreateSchemaTelemetryJobRecord creates a record for a schema telemetry job.
func CreateSchemaTelemetryJobRecord(createdByName string, createdByID int64) jobs.Record {
return jobs.Record{
Description: "SQL schema telemetry",
Username: username.NodeUserName(),
Details: jobspb.SchemaTelemetryDetails{},
Progress: jobspb.SchemaTelemetryProgress{},
CreatedBy: &jobs.CreatedByInfo{
ID: createdByID,
Name: createdByName,
},
}
}
// CreateSchemaTelemetrySchedule registers the schema telemetry job with
// the scheduled job subsystem so that the schema telemetry job can be run
// periodically. This is done during the cluster startup upgrade.
func CreateSchemaTelemetrySchedule(
ctx context.Context, txn isql.Txn, st *cluster.Settings,
) (*jobs.ScheduledJob, error) {
id, err := GetSchemaTelemetryScheduleID(ctx, txn)
if err != nil {
return nil, err
}
if id != 0 {
return nil, ErrDuplicatedSchedules
}
scheduledJob := jobs.NewScheduledJob(scheduledjobs.ProdJobSchedulerEnv)
schedule := SchemaTelemetryRecurrence.Get(&st.SV)
if err := scheduledJob.SetSchedule(schedule); err != nil {
return nil, err
}
scheduledJob.SetScheduleDetails(jobspb.ScheduleDetails{
Wait: jobspb.ScheduleDetails_SKIP,
OnError: jobspb.ScheduleDetails_RETRY_SCHED,
})
scheduledJob.SetScheduleLabel(SchemaTelemetryScheduleName)
scheduledJob.SetOwner(username.NodeUserName())
args, err := pbtypes.MarshalAny(&ScheduledSchemaTelemetryExecutionArgs{})
if err != nil {
return nil, err
}
scheduledJob.SetExecutionDetails(
tree.ScheduledSchemaTelemetryExecutor.InternalName(),
jobspb.ExecutionArguments{Args: args},
)
scheduledJob.SetScheduleStatus(string(jobs.StatusPending))
if err = jobs.ScheduledJobTxn(txn).Create(ctx, scheduledJob); err != nil {
return nil, err
}
return scheduledJob, nil
}
// GetSchemaTelemetryScheduleID returns the ID of the schema telemetry schedule
// if it exists, 0 if it does not exist yet.
func GetSchemaTelemetryScheduleID(ctx context.Context, txn isql.Txn) (id int64, _ error) {
row, err := txn.QueryRowEx(
ctx,
"check-existing-schema-telemetry-schedule",
txn.KV(),
sessiondata.NodeUserSessionDataOverride,
`SELECT schedule_id FROM system.scheduled_jobs WHERE schedule_name = $1 ORDER BY schedule_id ASC LIMIT 1`,
SchemaTelemetryScheduleName,
)
if err != nil || row == nil {
return 0, err
}
if len(row) != 1 {
return 0, errors.AssertionFailedf("unexpectedly received %d columns", len(row))
}
// Defensively check the type.
v, ok := tree.AsDInt(row[0])
if !ok {
return 0, errors.AssertionFailedf("unexpectedly received non-integer value %v", row[0])
}
return int64(v), nil
}
| pkg/sql/catalog/schematelemetry/schematelemetrycontroller/controller.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0012754682684317231,
0.00022762040316592902,
0.00016232431516982615,
0.00017195320106111467,
0.00022041176271159202
] |
{
"id": 2,
"code_window": [
"\t_, err := tenantDB.Exec(\"CREATE USER testuser WITH PASSWORD 'hunter2'\")\n",
"\trequire.NoError(t, err)\n",
"\t_, err = mainDB.Exec(\"ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true\")\n",
"\trequire.NoError(t, err)\n",
"\n",
"\ttestUserConn := tenant.SQLConnForUser(t, username.TestUser, \"\")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t_, err = tenantDB.Exec(\"CREATE TYPE typ AS ENUM ('foo', 'bar')\")\n",
"\trequire.NoError(t, err)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 42
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.9982794523239136,
0.14176155626773834,
0.00016197118384297937,
0.0015247565461322665,
0.3401142656803131
] |
{
"id": 2,
"code_window": [
"\t_, err := tenantDB.Exec(\"CREATE USER testuser WITH PASSWORD 'hunter2'\")\n",
"\trequire.NoError(t, err)\n",
"\t_, err = mainDB.Exec(\"ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true\")\n",
"\trequire.NoError(t, err)\n",
"\n",
"\ttestUserConn := tenant.SQLConnForUser(t, username.TestUser, \"\")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t_, err = tenantDB.Exec(\"CREATE TYPE typ AS ENUM ('foo', 'bar')\")\n",
"\trequire.NoError(t, err)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 42
} | // Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package kvnemesis
import (
"context"
gosql "database/sql"
"regexp"
"strings"
"testing"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/isolation"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/testutils/datapathutils"
"github.com/cockroachdb/cockroach/pkg/testutils/echotest"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
func TestApplier(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 1, base.TestClusterArgs{
// Disable replication to avoid AdminChangeReplicas complaining about
// replication queues being active.
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
db := tc.Server(0).DB()
sqlDB := tc.ServerConn(0)
env := &Env{SQLDBs: []*gosql.DB{sqlDB}}
type testCase struct {
name string
step Step
}
var sstValueHeader enginepb.MVCCValueHeader
sstValueHeader.KVNemesisSeq.Set(1)
sstSpan := roachpb.Span{Key: roachpb.Key(k1), EndKey: roachpb.Key(k4)}
sstTS := hlc.Timestamp{WallTime: 1}
sstFile := &storage.MemObject{}
{
st := cluster.MakeTestingClusterSettings()
storage.ValueBlocksEnabled.Override(ctx, &st.SV, true)
w := storage.MakeIngestionSSTWriter(ctx, st, sstFile)
defer w.Close()
require.NoError(t, w.PutMVCC(storage.MVCCKey{Key: roachpb.Key(k1), Timestamp: sstTS},
storage.MVCCValue{MVCCValueHeader: sstValueHeader, Value: roachpb.MakeValueFromString("v1")}))
require.NoError(t, w.PutMVCC(storage.MVCCKey{Key: roachpb.Key(k2), Timestamp: sstTS},
storage.MVCCValue{MVCCValueHeader: sstValueHeader}))
require.NoError(t, w.PutMVCCRangeKey(
storage.MVCCRangeKey{StartKey: roachpb.Key(k3), EndKey: roachpb.Key(k4), Timestamp: sstTS},
storage.MVCCValue{MVCCValueHeader: sstValueHeader}))
require.NoError(t, w.Finish())
}
a := MakeApplier(env, db, db)
tests := []testCase{
{
"get", step(get(k1)),
},
{
"scan", step(scan(k1, k3)),
},
{
"put", step(put(k1, 1)),
},
{
"get-for-update", step(getForUpdate(k1)),
},
{
"scan-for-update", step(scanForUpdate(k1, k3)),
},
{
"batch", step(batch(put(k1, 21), delRange(k2, k3, 22))),
},
{
"rscan", step(reverseScan(k1, k3)),
},
{
"rscan-for-update", step(reverseScanForUpdate(k1, k2)),
},
{
"del", step(del(k2, 1)),
},
{
"delrange", step(delRange(k1, k3, 6)),
},
{
"txn-ssi-delrange", step(closureTxn(ClosureTxnType_Commit, isolation.Serializable, delRange(k2, k4, 1))),
},
{
"txn-si-delrange", step(closureTxn(ClosureTxnType_Commit, isolation.Snapshot, delRange(k2, k4, 1))),
},
{
"get-err", step(get(k1)),
},
{
"put-err", step(put(k1, 1)),
},
{
"scan-for-update-err", step(scanForUpdate(k1, k3)),
},
{
"rscan-err", step(reverseScan(k1, k3)),
},
{
"rscan-for-update-err", step(reverseScanForUpdate(k1, k3)),
},
{
"del-err", step(del(k2, 1)),
},
{
"delrange-err", step(delRange(k2, k3, 12)),
},
{
"txn-ssi-err", step(closureTxn(ClosureTxnType_Commit, isolation.Serializable, delRange(k2, k4, 1))),
},
{
"txn-si-err", step(closureTxn(ClosureTxnType_Commit, isolation.Snapshot, delRange(k2, k4, 1))),
},
{
"batch-mixed", step(batch(put(k2, 2), get(k1), del(k2, 1), del(k3, 1), scan(k1, k3), reverseScanForUpdate(k1, k5))),
},
{
"batch-mixed-err", step(batch(put(k2, 2), getForUpdate(k1), scanForUpdate(k1, k3), reverseScan(k1, k3))),
},
{
"txn-ssi-commit-mixed", step(closureTxn(ClosureTxnType_Commit, isolation.Serializable, put(k5, 5), batch(put(k6, 6), delRange(k3, k5, 1)))),
},
{
"txn-si-commit-mixed", step(closureTxn(ClosureTxnType_Commit, isolation.Snapshot, put(k5, 5), batch(put(k6, 6), delRange(k3, k5, 1)))),
},
{
"txn-ssi-commit-batch", step(closureTxnCommitInBatch(isolation.Serializable, opSlice(get(k1), put(k6, 6)), put(k5, 5))),
},
{
"txn-si-commit-batch", step(closureTxnCommitInBatch(isolation.Snapshot, opSlice(get(k1), put(k6, 6)), put(k5, 5))),
},
{
"txn-ssi-rollback", step(closureTxn(ClosureTxnType_Rollback, isolation.Serializable, put(k5, 5))),
},
{
"txn-si-rollback", step(closureTxn(ClosureTxnType_Rollback, isolation.Snapshot, put(k5, 5))),
},
{
"split", step(split(k2)),
},
{
"merge", step(merge(k1)), // NB: this undoes the split at k2
},
{
"split-again", step(split(k2)),
},
{
"merge-again", step(merge(k1)), // ditto
},
{
"transfer", step(transferLease(k6, 1)),
},
{
"transfer-again", step(transferLease(k6, 1)),
},
{
"zcfg", step(changeZone(ChangeZoneType_ToggleGlobalReads)),
},
{
"zcfg-again", step(changeZone(ChangeZoneType_ToggleGlobalReads)),
},
{
"addsstable", step(addSSTable(sstFile.Data(), sstSpan, sstTS, sstValueHeader.KVNemesisSeq.Get(), true)),
},
{
"change-replicas", step(changeReplicas(k1, kvpb.ReplicationChange{ChangeType: roachpb.ADD_VOTER, Target: roachpb.ReplicationTarget{NodeID: 1, StoreID: 1}})),
},
}
w := echotest.NewWalker(t, datapathutils.TestDataPath(t, t.Name()))
defer w.Check(t)
for _, test := range tests {
s := test.step
t.Run(test.name, w.Run(t, test.name, func(t *testing.T) string {
isErr := strings.HasSuffix(test.name, "-err") || strings.HasSuffix(test.name, "-again")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if isErr {
cancel()
}
var buf strings.Builder
trace, err := a.Apply(ctx, &s)
require.NoError(t, err)
actual := strings.TrimLeft(s.String(), "\n")
if isErr {
// Trim out context canceled location, which can be non-deterministic.
// The wrapped string around the context canceled error depends on where
// the context cancellation was noticed.
actual = regexp.MustCompile(` (aborted .*|txn exec): context canceled`).ReplaceAllString(actual, ` context canceled`)
} else {
// Trim out the txn to avoid nondeterminism.
actual = regexp.MustCompile(` txnpb:\(.*\)`).ReplaceAllLiteralString(actual, ` txnpb:<txn>`)
// Replace timestamps.
actual = regexp.MustCompile(`[0-9]+\.[0-9]+,[0-9]+`).ReplaceAllLiteralString(actual, `<ts>`)
}
buf.WriteString(actual)
t.Log(buf.String())
t.Log(trace)
return buf.String()
}))
}
}
func TestUpdateZoneConfig(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
tests := []struct {
before zonepb.ZoneConfig
change ChangeZoneType
expAfter zonepb.ZoneConfig
}{
{
before: zonepb.ZoneConfig{NumReplicas: proto.Int32(3)},
change: ChangeZoneType_ToggleGlobalReads,
expAfter: zonepb.ZoneConfig{NumReplicas: proto.Int32(3), GlobalReads: proto.Bool(true)},
},
{
before: zonepb.ZoneConfig{NumReplicas: proto.Int32(3), GlobalReads: proto.Bool(false)},
change: ChangeZoneType_ToggleGlobalReads,
expAfter: zonepb.ZoneConfig{NumReplicas: proto.Int32(3), GlobalReads: proto.Bool(true)},
},
{
before: zonepb.ZoneConfig{NumReplicas: proto.Int32(3), GlobalReads: proto.Bool(true)},
change: ChangeZoneType_ToggleGlobalReads,
expAfter: zonepb.ZoneConfig{NumReplicas: proto.Int32(3), GlobalReads: proto.Bool(false)},
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
zone := test.before
updateZoneConfig(&zone, test.change)
require.Equal(t, test.expAfter, zone)
})
}
}
| pkg/kv/kvnemesis/applier_test.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0004752253298647702,
0.00018509001529309899,
0.00016466129454784095,
0.0001741288579069078,
0.000056376957218162715
] |
{
"id": 2,
"code_window": [
"\t_, err := tenantDB.Exec(\"CREATE USER testuser WITH PASSWORD 'hunter2'\")\n",
"\trequire.NoError(t, err)\n",
"\t_, err = mainDB.Exec(\"ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true\")\n",
"\trequire.NoError(t, err)\n",
"\n",
"\ttestUserConn := tenant.SQLConnForUser(t, username.TestUser, \"\")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t_, err = tenantDB.Exec(\"CREATE TYPE typ AS ENUM ('foo', 'bar')\")\n",
"\trequire.NoError(t, err)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 42
} | // Code generated by generate-staticcheck; DO NOT EDIT.
//go:build bazel
// +build bazel
package sa4021
import (
util "github.com/cockroachdb/cockroach/pkg/testutils/lint/passes/staticcheck"
"golang.org/x/tools/go/analysis"
"honnef.co/go/tools/staticcheck"
)
var Analyzer *analysis.Analyzer
func init() {
for _, analyzer := range staticcheck.Analyzers {
if analyzer.Analyzer.Name == "SA4021" {
Analyzer = analyzer.Analyzer
break
}
}
util.MungeAnalyzer(Analyzer)
}
| build/bazelutil/staticcheckanalyzers/sa4021/analyzer.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00025495269801467657,
0.00020034033514093608,
0.00017196396947838366,
0.000174104337929748,
0.00003862665835185908
] |
{
"id": 2,
"code_window": [
"\t_, err := tenantDB.Exec(\"CREATE USER testuser WITH PASSWORD 'hunter2'\")\n",
"\trequire.NoError(t, err)\n",
"\t_, err = mainDB.Exec(\"ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true\")\n",
"\trequire.NoError(t, err)\n",
"\n",
"\ttestUserConn := tenant.SQLConnForUser(t, username.TestUser, \"\")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t_, err = tenantDB.Exec(\"CREATE TYPE typ AS ENUM ('foo', 'bar')\")\n",
"\trequire.NoError(t, err)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 42
} | // Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package cmdutil
import (
"log"
"os"
)
// RequireEnv returns the value of the environment variable s. If s is unset or
// blank, RequireEnv prints an error message and exits.
func RequireEnv(s string) string {
v := os.Getenv(s)
if v == "" {
log.Fatalf("missing required environment variable %q", s)
}
return v
}
| pkg/cmd/cmdutil/env.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00021201043273322284,
0.00018828337488230318,
0.00017337658209726214,
0.00017946310981642455,
0.000016960570064838976
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tq := pgURL.Query()\n",
"\t\tq.Add(\"application_name\", \"carl\")\n",
"\t\tpgURL.RawQuery = q.Encode()\n",
"\t\tconn, err := gosql.Open(\"postgres\", pgURL.String())\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tconn, err := pgx.Connect(ctx, pgURL.String())\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 84
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.99815434217453,
0.3472767472267151,
0.00016619527013972402,
0.0022856900468468666,
0.4574880003929138
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tq := pgURL.Query()\n",
"\t\tq.Add(\"application_name\", \"carl\")\n",
"\t\tpgURL.RawQuery = q.Encode()\n",
"\t\tconn, err := gosql.Open(\"postgres\", pgURL.String())\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tconn, err := pgx.Connect(ctx, pgURL.String())\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 84
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package batcheval
import (
"context"
"fmt"
"math"
"testing"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/isolation"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/lockspanset"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/spanset"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
)
// TestDeleteRangeTombstone tests DeleteRange range tombstones and predicated based DeleteRange
// directly, using only a Pebble engine.
//
// MVCC range tombstone logic is tested exhaustively in the MVCC history tests,
// this just tests the RPC plumbing.
func TestDeleteRangeTombstone(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
storage.DisableMetamorphicSimpleValueEncoding(t)
// Initial data for each test. x is point tombstone, [] is intent,
// o---o is range tombstone.
//
// 5 [i5]
// 4 c4
// 3 x
// 2 b2 d2 o-------o
// 1
// a b c d e f g h i
//
// We also write two range tombstones abutting the Raft range a-z at [Z-a)@100
// and [z-|)@100. Writing a range tombstone should not merge with these.
writeInitialData := func(t *testing.T, ctx context.Context, rw storage.ReadWriter) {
t.Helper()
var localTS hlc.ClockTimestamp
txn := roachpb.MakeTransaction("test", nil /* baseKey */, isolation.Serializable, roachpb.NormalUserPriority, hlc.Timestamp{WallTime: 5e9}, 0, 0)
require.NoError(t, storage.MVCCPut(ctx, rw, roachpb.Key("b"), hlc.Timestamp{WallTime: 2e9}, roachpb.MakeValueFromString("b2"), storage.MVCCWriteOptions{}))
require.NoError(t, storage.MVCCPut(ctx, rw, roachpb.Key("c"), hlc.Timestamp{WallTime: 4e9}, roachpb.MakeValueFromString("c4"), storage.MVCCWriteOptions{}))
require.NoError(t, storage.MVCCPut(ctx, rw, roachpb.Key("d"), hlc.Timestamp{WallTime: 2e9}, roachpb.MakeValueFromString("d2"), storage.MVCCWriteOptions{}))
_, err := storage.MVCCDelete(ctx, rw, roachpb.Key("d"), hlc.Timestamp{WallTime: 3e9}, storage.MVCCWriteOptions{})
require.NoError(t, err)
require.NoError(t, storage.MVCCPut(ctx, rw, roachpb.Key("i"), hlc.Timestamp{WallTime: 5e9}, roachpb.MakeValueFromString("i5"), storage.MVCCWriteOptions{Txn: &txn}))
require.NoError(t, storage.MVCCDeleteRangeUsingTombstone(ctx, rw, nil, roachpb.Key("f"), roachpb.Key("h"), hlc.Timestamp{WallTime: 3e9}, localTS, nil, nil, false, 0, nil))
require.NoError(t, storage.MVCCDeleteRangeUsingTombstone(ctx, rw, nil, roachpb.Key("Z"), roachpb.Key("a"), hlc.Timestamp{WallTime: 100e9}, localTS, nil, nil, false, 0, nil))
require.NoError(t, storage.MVCCDeleteRangeUsingTombstone(ctx, rw, nil, roachpb.Key("z"), roachpb.Key("|"), hlc.Timestamp{WallTime: 100e9}, localTS, nil, nil, false, 0, nil))
}
now := hlc.ClockTimestamp{Logical: 9}
rangeStart, rangeEnd := roachpb.Key("a"), roachpb.Key("z")
testcases := map[string]struct {
start string
end string
ts int64
txn bool
inline bool
returnKeys bool
idempotent bool
expectNoWrite bool
expectErr interface{} // error type, substring, or true (any)
// The fields below test predicate based delete range rpc plumbing.
predicateStartTime int64 // if set, the test will only run with predicate based delete range
onlyPointKeys bool // if set UsingRangeTombstone arg is set to false
maxBatchSize int64 // if predicateStartTime is set, then MaxBatchSize must be set
}{
"above points succeed": {
start: "a",
end: "f",
ts: 10e9,
},
"above range tombstone succeed": {
start: "f",
end: "h",
ts: 10e9,
expectErr: nil,
},
"idempotent above range tombstone does not write": {
start: "f",
end: "h",
ts: 10e9,
idempotent: true,
expectErr: nil,
expectNoWrite: true,
},
"merging succeeds": {
start: "e",
end: "f",
ts: 3e9,
},
"adjacent to external LHS range key": {
start: "a",
end: "f",
ts: 100e9,
},
"adjacent to external RHS range key": {
start: "q",
end: "z",
ts: 100e9,
},
"transaction errors": {
start: "a",
end: "f",
ts: 10e9,
txn: true,
expectErr: ErrTransactionUnsupported,
},
"inline errors": {
start: "a",
end: "f",
ts: 10e9,
inline: true,
expectErr: "Inline can't be used with range tombstones",
},
"returnKeys errors": {
start: "a",
end: "f",
ts: 10e9,
returnKeys: true,
expectErr: "ReturnKeys can't be used with range tombstones",
},
"intent errors with WriteIntentError": {
start: "i",
end: "j",
ts: 10e9,
expectErr: &kvpb.WriteIntentError{},
},
"below point errors with WriteTooOldError": {
start: "a",
end: "d",
ts: 1e9,
expectErr: &kvpb.WriteTooOldError{},
},
"below range tombstone errors with WriteTooOldError": {
start: "f",
end: "h",
ts: 1e9,
expectErr: &kvpb.WriteTooOldError{},
},
"predicate without UsingRangeTombstone error": {
start: "a",
end: "f",
ts: 10e9,
predicateStartTime: 1,
maxBatchSize: maxDeleteRangeBatchBytes,
onlyPointKeys: true,
expectErr: "UseRangeTombstones must be passed with predicate based Delete Range",
},
"predicate maxBatchSize error": {
start: "a",
end: "f",
ts: 10e9,
predicateStartTime: 1,
maxBatchSize: 0,
expectErr: "MaxSpanRequestKeys must be greater than zero when using predicated based DeleteRange",
},
}
for name, tc := range testcases {
t.Run(name, func(t *testing.T) {
for _, runWithPredicates := range []bool{false, true} {
if tc.predicateStartTime > 0 && !runWithPredicates {
continue
}
if runWithPredicates && tc.idempotent {
continue
}
t.Run(fmt.Sprintf("Predicates=%v", runWithPredicates), func(t *testing.T) {
ctx := context.Background()
st := cluster.MakeTestingClusterSettings()
engine := storage.NewDefaultInMemForTesting()
defer engine.Close()
writeInitialData(t, ctx, engine)
rangeKey := storage.MVCCRangeKey{
StartKey: roachpb.Key(tc.start),
EndKey: roachpb.Key(tc.end),
Timestamp: hlc.Timestamp{WallTime: tc.ts},
}
// Prepare the request and environment.
evalCtx := &MockEvalCtx{
ClusterSettings: st,
Desc: &roachpb.RangeDescriptor{
StartKey: roachpb.RKey(rangeStart),
EndKey: roachpb.RKey(rangeEnd),
},
}
h := kvpb.Header{
Timestamp: rangeKey.Timestamp,
}
if tc.txn {
txn := roachpb.MakeTransaction(
"txn", nil, isolation.Serializable, roachpb.NormalUserPriority, rangeKey.Timestamp, 0, 0)
h.Txn = &txn
}
var predicates kvpb.DeleteRangePredicates
if runWithPredicates {
predicates = kvpb.DeleteRangePredicates{
StartTime: hlc.Timestamp{WallTime: 1},
}
h.MaxSpanRequestKeys = math.MaxInt64
}
if tc.predicateStartTime > 0 {
predicates = kvpb.DeleteRangePredicates{
StartTime: hlc.Timestamp{WallTime: tc.predicateStartTime},
}
h.MaxSpanRequestKeys = tc.maxBatchSize
}
req := &kvpb.DeleteRangeRequest{
RequestHeader: kvpb.RequestHeader{
Key: rangeKey.StartKey,
EndKey: rangeKey.EndKey,
},
UseRangeTombstone: !tc.onlyPointKeys,
IdempotentTombstone: tc.idempotent,
Inline: tc.inline,
ReturnKeys: tc.returnKeys,
Predicates: predicates,
}
ms := computeStats(t, engine, rangeStart, rangeEnd, rangeKey.Timestamp.WallTime)
// Use a spanset batch to assert latching of all accesses. In particular,
// the additional seeks necessary to check for adjacent range keys that we
// may merge with (for stats purposes) which should not cross the range
// bounds.
var latchSpans spanset.SpanSet
var lockSpans lockspanset.LockSpanSet
declareKeysDeleteRange(evalCtx.Desc, &h, req, &latchSpans, &lockSpans, 0)
batch := spanset.NewBatchAt(engine.NewBatch(), &latchSpans, h.Timestamp)
defer batch.Close()
// Run the request.
resp := &kvpb.DeleteRangeResponse{}
_, err := DeleteRange(ctx, batch, CommandArgs{
EvalCtx: evalCtx.EvalContext(),
Stats: &ms,
Now: now,
Header: h,
Args: req,
}, resp)
// Check the error.
if tc.expectErr != nil {
require.Error(t, err)
if b, ok := tc.expectErr.(bool); ok && b {
// any error is fine
} else if expectMsg, ok := tc.expectErr.(string); ok {
require.Contains(t, err.Error(), expectMsg)
} else if e, ok := tc.expectErr.(error); ok {
require.True(t, errors.HasType(err, e), "expected %T, got %v", e, err)
} else {
require.Fail(t, "invalid expectErr", "expectErr=%v", tc.expectErr)
}
return
}
require.NoError(t, err)
require.NoError(t, batch.Commit(true))
if runWithPredicates {
checkPredicateDeleteRange(t, engine, rangeKey)
} else {
checkDeleteRangeTombstone(t, engine, rangeKey, !tc.expectNoWrite, now)
}
// Check that range tombstone stats were updated correctly.
require.Equal(t, computeStats(t, engine, rangeStart, rangeEnd, rangeKey.Timestamp.WallTime), ms)
})
}
})
}
}
// checkDeleteRangeTombstone checks that the span targeted by the predicate
// based delete range operation only has point tombstones, as the size of the
// spans in this test are below rangeTombstoneThreshold
//
// the passed in rangekey contains info on the span PredicateDeleteRange
// operated on. The command should not have written an actual rangekey!
func checkPredicateDeleteRange(t *testing.T, engine storage.Reader, rKeyInfo storage.MVCCRangeKey) {
iter := engine.NewMVCCIterator(storage.MVCCKeyAndIntentsIterKind, storage.IterOptions{
KeyTypes: storage.IterKeyTypePointsAndRanges,
LowerBound: rKeyInfo.StartKey,
UpperBound: rKeyInfo.EndKey,
})
defer iter.Close()
for iter.SeekGE(storage.MVCCKey{Key: rKeyInfo.StartKey}); ; iter.NextKey() {
ok, err := iter.Valid()
require.NoError(t, err)
if !ok {
break
}
hasPoint, hashRange := iter.HasPointAndRange()
if !hasPoint && hashRange {
// PredicateDeleteRange should not have written any delete tombstones;
// therefore, any range key tombstones in the span should have been
// written before the request was issued.
for _, v := range iter.RangeKeys().Versions {
require.True(t, v.Timestamp.Less(rKeyInfo.Timestamp))
}
continue
}
value, err := storage.DecodeMVCCValueAndErr(iter.UnsafeValue())
require.NoError(t, err)
require.True(t, value.IsTombstone())
}
}
// checkDeleteRangeTombstone checks that the range tombstone was written successfully.
func checkDeleteRangeTombstone(
t *testing.T,
engine storage.Reader,
rangeKey storage.MVCCRangeKey,
written bool,
now hlc.ClockTimestamp,
) {
iter := engine.NewMVCCIterator(storage.MVCCKeyAndIntentsIterKind, storage.IterOptions{
KeyTypes: storage.IterKeyTypeRangesOnly,
LowerBound: rangeKey.StartKey,
UpperBound: rangeKey.EndKey,
})
defer iter.Close()
iter.SeekGE(storage.MVCCKey{Key: rangeKey.StartKey})
var seen storage.MVCCRangeKeyValue
for {
ok, err := iter.Valid()
require.NoError(t, err)
if !ok {
break
}
require.True(t, ok)
rangeKeys := iter.RangeKeys()
for _, v := range rangeKeys.Versions {
if v.Timestamp.Equal(rangeKey.Timestamp) {
if len(seen.RangeKey.StartKey) == 0 {
seen = rangeKeys.AsRangeKeyValue(v).Clone()
} else {
seen.RangeKey.EndKey = rangeKeys.Bounds.EndKey.Clone()
require.Equal(t, seen.Value, v.Value)
}
break
}
}
iter.Next()
}
if written {
require.Equal(t, rangeKey, seen.RangeKey)
value, err := storage.DecodeMVCCValue(seen.Value)
require.NoError(t, err)
require.True(t, value.IsTombstone())
require.Equal(t, now, value.LocalTimestamp)
} else {
require.Empty(t, seen)
}
}
// computeStats computes MVCC stats for the given range.
//
// TODO(erikgrinaker): This, storage.computeStats(), and engineStats() should be
// moved into a testutils package, somehow avoiding import cycles with storage
// tests.
func computeStats(
t *testing.T, reader storage.Reader, from, to roachpb.Key, nowNanos int64,
) enginepb.MVCCStats {
t.Helper()
if len(from) == 0 {
from = keys.LocalMax
}
if len(to) == 0 {
to = keys.MaxKey
}
ms, err := storage.ComputeStats(reader, from, to, nowNanos)
require.NoError(t, err)
return ms
}
| pkg/kv/kvserver/batcheval/cmd_delete_range_test.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.04093973711133003,
0.0012034369865432382,
0.00016404602502007037,
0.00017040596867445856,
0.0062850601971149445
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tq := pgURL.Query()\n",
"\t\tq.Add(\"application_name\", \"carl\")\n",
"\t\tpgURL.RawQuery = q.Encode()\n",
"\t\tconn, err := gosql.Open(\"postgres\", pgURL.String())\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tconn, err := pgx.Connect(ctx, pgURL.String())\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 84
} | /* setup */
CREATE TABLE t (i INT PRIMARY KEY, j INT, k INT DEFAULT 32 ON UPDATE 42, INDEX((j+1), k));
/* test */
ALTER TABLE t DROP COLUMN j CASCADE;
CREATE UNIQUE INDEX idx ON t(k);
EXPLAIN (DDL) rollback at post-commit stage 15 of 15;
----
Schema change plan for rolling back CREATE UNIQUE INDEX βΉidxβΊ ON βΉdefaultdbβΊ.public.βΉtβΊ (βΉkβΊ); following ALTER TABLE βΉdefaultdbβΊ.public.βΉtβΊ DROP COLUMN βΉjβΊ CASCADE;
βββ PostCommitNonRevertiblePhase
βββ Stage 1 of 3 in PostCommitNonRevertiblePhase
β βββ 7 elements transitioning toward PUBLIC
β β βββ WRITE_ONLY β PUBLIC Column:{DescID: 104 (t), ColumnID: 2 (j+)}
β β βββ WRITE_ONLY β PUBLIC Column:{DescID: 104 (t), ColumnID: 4 (crdb_internal_idx_expr+)}
β β βββ VALIDATED β PUBLIC PrimaryIndex:{DescID: 104 (t), IndexID: 1 (t_pkey+), ConstraintID: 1}
β β βββ ABSENT β PUBLIC IndexName:{DescID: 104 (t), Name: "t_pkey", IndexID: 1 (t_pkey+)}
β β βββ VALIDATED β PUBLIC SecondaryIndex:{DescID: 104 (t), IndexID: 2 (t_expr_k_idx+)}
β β βββ ABSENT β PUBLIC ColumnName:{DescID: 104 (t), Name: "j", ColumnID: 2 (j+)}
β β βββ ABSENT β PUBLIC ColumnName:{DescID: 104 (t), Name: "crdb_internal_idx_expr", ColumnID: 4 (crdb_internal_idx_expr+)}
β βββ 12 elements transitioning toward ABSENT
β β βββ PUBLIC β ABSENT IndexColumn:{DescID: 104 (t), ColumnID: 1 (i), IndexID: 4 (crdb_internal_index_4_name_placeholder)}
β β βββ PUBLIC β ABSENT IndexColumn:{DescID: 104 (t), ColumnID: 3 (k), IndexID: 4 (crdb_internal_index_4_name_placeholder)}
β β βββ PUBLIC β VALIDATED PrimaryIndex:{DescID: 104 (t), IndexID: 3 (t_pkey-), ConstraintID: 2, TemporaryIndexID: 4 (crdb_internal_index_4_name_placeholder), SourceIndexID: 1 (t_pkey+)}
β β βββ PUBLIC β ABSENT IndexName:{DescID: 104 (t), Name: "t_pkey", IndexID: 3 (t_pkey-)}
β β βββ TRANSIENT_DELETE_ONLY β ABSENT TemporaryIndex:{DescID: 104 (t), IndexID: 4 (crdb_internal_index_4_name_placeholder), ConstraintID: 3, SourceIndexID: 1 (t_pkey+)}
β β βββ WRITE_ONLY β DELETE_ONLY SecondaryIndex:{DescID: 104 (t), IndexID: 5 (idx-), ConstraintID: 4, TemporaryIndexID: 6, SourceIndexID: 3 (t_pkey-)}
β β βββ PUBLIC β ABSENT IndexColumn:{DescID: 104 (t), ColumnID: 3 (k), IndexID: 5 (idx-)}
β β βββ PUBLIC β ABSENT IndexColumn:{DescID: 104 (t), ColumnID: 1 (i), IndexID: 5 (idx-)}
β β βββ PUBLIC β ABSENT IndexName:{DescID: 104 (t), Name: "idx", IndexID: 5 (idx-)}
β β βββ TRANSIENT_DELETE_ONLY β ABSENT TemporaryIndex:{DescID: 104 (t), IndexID: 6, ConstraintID: 5, SourceIndexID: 3 (t_pkey-)}
β β βββ PUBLIC β ABSENT IndexColumn:{DescID: 104 (t), ColumnID: 3 (k), IndexID: 6}
β β βββ PUBLIC β ABSENT IndexColumn:{DescID: 104 (t), ColumnID: 1 (i), IndexID: 6}
β βββ 24 Mutation operations
β βββ SetIndexName {"IndexID":1,"Name":"t_pkey","TableID":104}
β βββ MakeValidatedSecondaryIndexPublic {"IndexID":2,"TableID":104}
β βββ RefreshStats {"TableID":104}
β βββ SetColumnName {"ColumnID":2,"Name":"j","TableID":104}
β βββ SetColumnName {"ColumnID":4,"Name":"crdb_internal_id...","TableID":104}
β βββ MakePublicPrimaryIndexWriteOnly {"IndexID":3,"TableID":104}
β βββ SetIndexName {"IndexID":3,"Name":"crdb_internal_in...","TableID":104}
β βββ MakeWriteOnlyIndexDeleteOnly {"IndexID":5,"TableID":104}
β βββ RemoveColumnFromIndex {"ColumnID":3,"IndexID":5,"TableID":104}
β βββ RemoveColumnFromIndex {"ColumnID":1,"IndexID":5,"Kind":1,"TableID":104}
β βββ SetIndexName {"IndexID":5,"Name":"crdb_internal_in...","TableID":104}
β βββ RemoveColumnFromIndex {"ColumnID":3,"IndexID":6,"TableID":104}
β βββ RemoveColumnFromIndex {"ColumnID":1,"IndexID":6,"Kind":1,"TableID":104}
β βββ MakeWriteOnlyColumnPublic {"ColumnID":2,"TableID":104}
β βββ RefreshStats {"TableID":104}
β βββ MakeWriteOnlyColumnPublic {"ColumnID":4,"TableID":104}
β βββ RefreshStats {"TableID":104}
β βββ MakeValidatedPrimaryIndexPublic {"IndexID":1,"TableID":104}
β βββ RemoveColumnFromIndex {"ColumnID":1,"IndexID":4,"TableID":104}
β βββ RemoveColumnFromIndex {"ColumnID":3,"IndexID":4,"Kind":2,"TableID":104}
β βββ MakeIndexAbsent {"IndexID":4,"TableID":104}
β βββ MakeIndexAbsent {"IndexID":6,"TableID":104}
β βββ SetJobStateOnDescriptor {"DescriptorID":104}
β βββ UpdateSchemaChangerJob {"IsNonCancelable":true,"RunningStatus":"PostCommitNonRev..."}
βββ Stage 2 of 3 in PostCommitNonRevertiblePhase
β βββ 4 elements transitioning toward ABSENT
β β βββ PUBLIC β ABSENT IndexColumn:{DescID: 104 (t), ColumnID: 1 (i), IndexID: 3 (t_pkey-)}
β β βββ PUBLIC β ABSENT IndexColumn:{DescID: 104 (t), ColumnID: 3 (k), IndexID: 3 (t_pkey-)}
β β βββ VALIDATED β DELETE_ONLY PrimaryIndex:{DescID: 104 (t), IndexID: 3 (t_pkey-), ConstraintID: 2, TemporaryIndexID: 4 (crdb_internal_index_4_name_placeholder), SourceIndexID: 1 (t_pkey+)}
β β βββ DELETE_ONLY β ABSENT SecondaryIndex:{DescID: 104 (t), IndexID: 5 (idx-), ConstraintID: 4, TemporaryIndexID: 6, SourceIndexID: 3 (t_pkey-)}
β βββ 6 Mutation operations
β βββ MakeIndexAbsent {"IndexID":5,"TableID":104}
β βββ MakeWriteOnlyIndexDeleteOnly {"IndexID":3,"TableID":104}
β βββ RemoveColumnFromIndex {"ColumnID":1,"IndexID":3,"TableID":104}
β βββ RemoveColumnFromIndex {"ColumnID":3,"IndexID":3,"Kind":2,"TableID":104}
β βββ SetJobStateOnDescriptor {"DescriptorID":104}
β βββ UpdateSchemaChangerJob {"IsNonCancelable":true,"RunningStatus":"PostCommitNonRev..."}
βββ Stage 3 of 3 in PostCommitNonRevertiblePhase
βββ 5 elements transitioning toward ABSENT
β βββ PUBLIC β ABSENT IndexData:{DescID: 104 (t), IndexID: 3 (t_pkey-)}
β βββ PUBLIC β ABSENT IndexData:{DescID: 104 (t), IndexID: 4 (crdb_internal_index_4_name_placeholder)}
β βββ DELETE_ONLY β ABSENT PrimaryIndex:{DescID: 104 (t), IndexID: 3 (t_pkey-), ConstraintID: 2, TemporaryIndexID: 4 (crdb_internal_index_4_name_placeholder), SourceIndexID: 1 (t_pkey+)}
β βββ PUBLIC β ABSENT IndexData:{DescID: 104 (t), IndexID: 5 (idx-)}
β βββ PUBLIC β ABSENT IndexData:{DescID: 104 (t), IndexID: 6}
βββ 7 Mutation operations
βββ MakeIndexAbsent {"IndexID":3,"TableID":104}
βββ CreateGCJobForIndex {"IndexID":3,"TableID":104}
βββ CreateGCJobForIndex {"IndexID":4,"TableID":104}
βββ CreateGCJobForIndex {"IndexID":5,"TableID":104}
βββ CreateGCJobForIndex {"IndexID":6,"TableID":104}
βββ RemoveJobStateFromDescriptor {"DescriptorID":104}
βββ UpdateSchemaChangerJob {"IsNonCancelable":true,"RunningStatus":"all stages compl..."}
| pkg/sql/schemachanger/testdata/end_to_end/drop_column_create_index_separate_statements/drop_column_create_index_separate_statements__rollback_15_of_15.explain | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0031585581600666046,
0.0005010805325582623,
0.0001667201577220112,
0.00016829741070978343,
0.0009395618108101189
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tq := pgURL.Query()\n",
"\t\tq.Add(\"application_name\", \"carl\")\n",
"\t\tpgURL.RawQuery = q.Encode()\n",
"\t\tconn, err := gosql.Open(\"postgres\", pgURL.String())\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tconn, err := pgx.Connect(ctx, pgURL.String())\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 84
} | # Admission Control
Author: Sumeer Bhola
## Goals
Admission control for a system decides when work submitted to that
system begins executing, and is useful when there is some resource
(e.g. CPU) that is saturated. The high-level goals of admission
control in CockroachDB are to control resource overload such that it
(a) does not degrade throughput or cause node failures, (b) achieve
differentiation between work with different levels of importance
submitted by users, and (c) allow for load-balancing among data
replicas (when possible).
For CockroachDB Serverless, where the shared cluster only runs the KV
layer and below, admission control also encompasses achieving fairness
across tenants (fairness is defined as equally allocating resources,
e.g. CPU, across tenants that are competing for resources).
Multi-tenant isolation for the shared cluster is included in the scope
of admission control since many of the queuing and re-ordering
mechanisms for work prioritization overlap with those for inter-tenant
isolation.
Even though we do not discuss per-tenant SQL nodes in the remainder of
this document, the overload control mechanisms discussed below could
potentially be applied in that context, though the code for it is
incomplete. The scope of admission control excludes per-tenant cost
controls, since per-tenant cost is not a system resource.
The current implementation focuses on node-level admission control,
for CPU and storage IO (specifically writes) as the bottleneck
resources. The focus on node-level admission control is based on the
observation that large scale systems may be provisioned adequately at
the aggregate level, but since CockroachDB has stateful nodes,
individual node hotspots can develop that can last for some time
(until rebalancing). Such hotspots should not cause failures or
degrade service for important work (or unfairly for tenants that are
not responsible for the hotspot).
Specifically, for CPU the goal is to shift queueing from inside the
goroutine scheduler, where there is no differentiation, into various
admission queues, where we can differentiate. This must be done while
allowing the system to have high peak CPU utilization. For storage IO,
the goal is to prevent the log-structured merge (LSM) tree based
storage layer (Pebble) from getting into a situation with high read
amplification due to many files/sub-levels in level 0, which slows
down reads. This needs to be done while maintaining the ability to
absorb bursts of writes. Both CPU overload and high read amplification
in the LSM are areas where we have seen problems in real CockroachDB
clusters.
The notable omission here is memory as a bottleneck resource for
admission control. The difficulty is that memory is non-preemptible
(mostly, ignoring disk spilling), and is used in various layers of the
system, and so slowing down certain activities (like KV processing)
may make things worse by causing the SQL layer to hold onto memory it
has already allocated. We want forward progress so that memory can be
released, and we do not know what should make progress to release the
most memory. We also currently do not have predictions for how much
memory a SQL query will consume, so we cannot make reasonable
reservations to make up for the non-preemptibility.
## High-level Approach
### Ordering Tuple
Admission queues use the tuple **(tenant, priority, transaction start
time)**, to order items that are waiting to be admitted. There is
coarse-grained fair sharing across tenants (for the multi-tenant
shared cluster). Priority is used within a tenant, and allows for
starvation, in that if higher priority work is always consuming all
resources, the lower priority work would wait forever. The transaction
start time is used within a priority, and gives preference to earlier
transactions. We currently do not have a way for end-users to assign
priority to their SQL transactions. We also currently do not support
multi-tenancy in dedicated clusters, even though many such customers
would like to distinguish between different internal tenants. Both
these limitations could be addressed by adding the requisite
plumbing/integration code.
### Possible solution for CPU Resource with scheduler change
Let us consider the case of CPU as a bottleneck resource. If we had
the ability to change the goroutine scheduler we could associate the
above ordering tuple with each goroutine and could allocate the CPU
(P) slots to the runnable goroutine that should be next according to
that tuple. Such a scheme does not need to make any guesses about
whether some admitted work is currently doing useful work or blocked
on IO, since there is visibility into that state inside the
scheduler. And if we are concerned about starting too much work, and
not finishing already started work, one could add a **started**
boolean as the first element of the tuple and first give preference to
goroutines that had already started doing some work (there is a draft
Cockroach Labs [internal
doc](https://docs.google.com/document/d/18S4uE8O1nRxULhSg9Z1Zt4jUPBiLJgMh7X1I6shsbug/edit#heading=h.ssc9exx0epqo)
that provides more details). However, we currently do not have the
ability to make such scheduler changes. So we resort to more indirect
control as outlined in the next section.
### Admission for CPU Resource
#### Kinds of Work and Queues
There are various kinds of work that consume CPU, and we add admission
interception points in various places where we expect the
post-admission CPU consumption to be significant and (somewhat)
bounded. Note that there is still extreme heterogeneity in work size,
that we are not aware of at admission time, and we do not know the
CPU/IO ratio for a work unit. Specifically, the interception points
are:
- **KV**: KV work admission, specifically the
`roachpb.InternalServer.Batch` API implemented by
[`Node`](https://github.com/cockroachdb/cockroach/blob/d10b3a5badf25c9e19ca84037f2426b03196b2ac/pkg/server/node.go#L938). This
includes work submitted by SQL, and internal operations like
garbage collection and node heartbeats.
- **SQL-KV**: Admission of SQL processing for a response provided by
KV. For example, consider a distributed SQL scan of a large table
that is being executed at N nodes, where the SQL layer is issuing
local requests to the KV layer. The response from KV is subject to
admission control at each node, before processing by the SQL layer.
- **SQL-SQL**: Distributed SQL runs as a two-level tree where the
lower level sends back responses to the root for further
processing. Admission control applies to the response processing
at the root.
Each of these kinds of work has its own admission queue. Work is
queued until admitted or the work deadline is exceeded. Currently
there is no early rejection when encountering long queues. Under
aggressive user-specified deadlines throughput may collapse because
everything exceeds the deadline after doing part of the work. This is
no different than what will likely happen without admission control,
due to undifferentiated queueing inside the goroutine scheduler, but
we note that this is a behavior that is not currently improved by
admission control.
The above list of kinds are ordered from lower level to higher level,
and also serves as a hard-wired ordering from most important to least
important. The high importance of KV work reduces the likelihood that
non-SQL KV work will be starved. SQL-KV (response) work is prioritized
over SQL-SQL since the former includes leaf DistSQL processing and we
would like to release memory used up in RPC responses at lower layers
of RPC tree. We expect that if SQL-SQL (response) work is delayed, it
will eventually reduce new work being issued, which is a desirable
form of natural backpressure. Note that this hard prioritization
across kinds of work is orthogonal to the priority specified in the
ordering tuple, and would ideally not be needed (one reason for
introducing it is due to our inability to change the goroutine
scheduler).
Consider the example of a lower priority long-running OLAP query
competing with higher priority small OLTP queries in a single node
setting. Say the OLAP query starts first and uses up all the CPU
resource such that the OLTP queries queue up in the KV work
queue. When the OLAP query's KV work completes, it will queue up for
SQL-KV work, which will not start because the OLTP queries are now
using up all available CPU for KV work. When this OLTP KV work
completes, their SQL-KV work will queue up. The queue for SQL-KV will
first admit those for the higher priority OLTP queries. This will
prevent or slow down admission of further work by the OLAP query.
One weakness of this prioritization across kinds of work is that it
can result in priority inversion: lower importance KV work, not
derived from SQL, like GC of MVCC versions, will happen before
user-facing SQL-KV work. This is because the backpressure via SQL-SQL,
mentioned earlier, does not apply to work generated from within the KV
layer. This could be addressed by introducing a **KV-background** work
kind and placing it last in the above ordering.
#### Slots and Tokens
The above kinds of work behave differently in whether we know a work
unit is completed or not. For KV work we know when the admitted work
completes, but this is not possible to know for SQL-KV and SQL-SQL
work because of the way the execution code is structured. Knowing
about completion is advantageous since it allows for better control
over resource consumption, sine we do not know how big each work unit
actually is.
We model these two different situations with different ways of
granting admission: for KV work we grant a slot that is occupied while
the work executes and becomes available when the work completes, and
for SQL-KV and SQL-SQL we grant a token that is consumed. The slot
terminology is akin to a scheduler, where a scheduling slot must be
free for a thread to run. But unlike a scheduler, we do not have
visibility into the fact that work execution may be blocked on IO. So
a slot can also be viewed as a limit on concurrency of ongoing
work. The token terminology is inspired by token buckets. Unlike a
token bucket, which shapes the rate, the current implementation limits
burstiness and does not do rate shaping -- this is because it is hard
to predict what rate is appropriate given the difference in sizes of
the work.
#### Slot Adjustment for KV
The current implementation makes no dynamic adjustments to token burst
sizes since the lack of a completion indicator and heterogeneity in
size makes it hard to figure out how to adjust these tokens. In
contrast, the slots that limit KV work concurrency are adjusted. And
because KV work must be admitted (and have no waiting requests) before
admission of SQL-KV and SQL-SQL work, the slot adjustment also
throttles the latter kinds of work.
We monitor the following state of the goroutine scheduler: the number
of processors, and the number of goroutines that are runnable (i.e.,
they are ready to run, but not running). The latter represents
queueing inside the goroutine scheduler, since these goroutines are
waiting to be scheduled. KV work concurrency slots are adjusted by
gradually decreasing or increasing the total slots (additive
decrements or increments), when the runnable count, normalized by the
number of processors, is too high or too low. The adjustment also
takes into account current usage of slots. The exact heuristic can be
found in `admission.kvSlotAdjuster`. It monitors the runnable count at
1ms intervals. The motivation for this high frequency is that sudden
shifts in CPU/IO ratio or lock contention can cause the current slot
count to be inadequate, while leaving the CPU underutilized, which is
undesirable.
#### Instantaneous CPU feedback and limiting bursts
Tokens are granted (up to the burst size) for SQL-KV when the KV work
queue is empty and the CPU is not overloaded. For SQL-SQL the
additional requirement is that the SQL-KV work queue must also be
empty. It turns out that using the runnable goroutine count at 1ms
intervals, as a signal for CPU load, is insufficient time granularity
to properly control token grants. So we use two instantaneous
indicators:
- CPU is considered overloaded if all the KV slots are utilized.
- Tokens are not directly granted to waiting requests up to the burst
size. Instead we setup a "grant chaining" system where the goroutine
that is granted a token has to run and grant the next token. This
gives instantaneous feedback into the overload state. In an
experiment, using such grant chains reduced burstiness of grants by
5x and shifted ~2s of latency (at p99) from the goroutine scheduler
into admission control (which is desirable since the latter is where
we can differentiate between work).
### Admission for IO Resource
KV work that involves writing to a store is additionally subject to a
per-store admission queue. Admission in this queue uses tokens
(discussed below), and happens before the KV work is subject to the KV
CPU admission queue (which uses slots), so that we do not have a
situation where a KV slot is taken up by work that is now waiting for
IO admission.
KV work completion is not a good indicator of write work being
complete in the LSM tree. This is because flushes of memtables, and
compactions of sstables, which are the costly side-effect of writes,
happen later. We use "IO tokens" to constrain how many KV work items
are admitted. There is no limit on tokens when the LSM is healthy. Bad
health is indicated using thresholds on two level 0 metrics: the
sub-level count and file count. We do not consider other metrics for
health (compaction backlog, high compaction scores on other levels
etc.) since we are primarily concerned with increasing
read-amplification, which is what will impact user-facing traffic. It
is acceptable for the LSM to deteriorate in terms of compaction scores
etc. as long as the read-amplification does not explode, because
absorbing write bursts is important, and write bursts are often
followed by long enough intervals of low activity that restore the LSM
compaction scores to good health.
When the LSM is considered overloaded, tokens are calculated by
estimating the average bytes added per KV work, and using the outgoing
compaction bytes to estimate how many KV work items it is acceptable
to admit. This detailed logic can be found in
`admission.ioLoadListener` which generates a new token estimate every
15s. The 15s duration is based on experimental observations of
compaction durations in level 0 when the number of sub-levels
increases beyond the overload threshold. We want a duration that is
larger than most compactions, but not too large (for
responsiveness). These tokens are given out in 1s intervals (for
smoothing). The code has comments with experimental details that
guided some of the settings.
### Priority adjustments and Bypassing admission control
KV work that is not directly issued by SQL is never queued, though it
does consume a slot, which means the available slots can become
negative. This is a simple hack to prevent distributed deadlock that
can happen if we queue KV work issued due to other KV work. This will
need to be changed in the future to also queue low priority KV
operations (e.g. GC can be considered lower priority than user facing
work).
Transactions that are holding locks, or have ongoing requests to
acquire locks, have their subsequent work requests bumped to higher
priority. This is a crude way to limit priority inversion where a
transaction holding locks could be waiting in an admission queue while
admitted requests are waiting in the lock table queues for this
transaction to make progress and release locks. Such prioritization
can also fare better than a system with no admission control, since
work from transactions holding locks will get prioritized, versus no
prioritization in the goroutine scheduler. A TPCC run with 3000
warehouses showed 2x reduction in lock waiters and 10+% improvement in
transaction throughput with this priority adjustment compared to no
priority adjustment. See
https://github.com/cockroachdb/cockroach/pull/69337#issue-978534871
for comparison graphs.
### Tuning Knobs
Enabling admission control is done via cluster settings. It is
currently disabled by default. There are three boolean settings,
`admission.kv.enabled`, `admission.sql_kv_response.enabled`,
`admission.sql_sql_response.enabled` and we have only experimented
with all of them turned on.
There are also some advanced tuning cluster settings, that adjust the
CPU overload threshold and the level 0 store overload thresholds.
### Results
There are certain TPCC-bench and KV roachtests running regularly with
admission control enabled (they have "admission" in the test name
suffix). The TPCC performance is roughly equivalent to admission
control disabled. Certain KV roachtests that used to overload IO, but
were not running long enough to show the bad effects, are worse with
admission control enabled when comparing the mean throughput. However
the runs with admission control enabled are arguably better since they
do not have a steadily worsening throughput over the course of the
experimental run.
For some graphs showing before and after effects of enabling admission control see:
- CPU overload:
https://github.com/cockroachdb/cockroach/pull/65614#issue-651424608
and
https://github.com/cockroachdb/cockroach/pull/66891#issue-930351128
- IO overload:
https://github.com/cockroachdb/cockroach/pull/65850#issue-656777155
and
https://github.com/cockroachdb/cockroach/pull/69311#issue-978297918
| docs/tech-notes/admission_control.md | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0001763966283760965,
0.00016716565005481243,
0.0001618978421902284,
0.00016675243386998773,
0.0000026687268928071717
] |
{
"id": 4,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer conn.Close()\n",
"\n",
"\t\t// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tdefer func() { _ = conn.Close(ctx) }()\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 86
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.16990678012371063,
0.01174857560545206,
0.00016586107085458934,
0.0022013781126588583,
0.035251591354608536
] |
{
"id": 4,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer conn.Close()\n",
"\n",
"\t\t// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tdefer func() { _ = conn.Close(ctx) }()\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 86
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package scmutationexec
import (
"context"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scop"
)
func (i *immediateVisitor) UpsertDatabaseComment(
_ context.Context, op scop.UpsertDatabaseComment,
) error {
i.AddComment(op.DatabaseID, 0, catalogkeys.DatabaseCommentType, op.Comment)
return nil
}
func (i *immediateVisitor) UpsertSchemaComment(
_ context.Context, op scop.UpsertSchemaComment,
) error {
i.AddComment(op.SchemaID, 0, catalogkeys.SchemaCommentType, op.Comment)
return nil
}
func (i *immediateVisitor) UpsertTableComment(_ context.Context, op scop.UpsertTableComment) error {
i.AddComment(op.TableID, 0, catalogkeys.TableCommentType, op.Comment)
return nil
}
func (i *immediateVisitor) UpsertColumnComment(
_ context.Context, op scop.UpsertColumnComment,
) error {
subID := int(op.ColumnID)
if op.PGAttributeNum != 0 {
// PGAttributeNum is only set if it differs from the ColumnID.
subID = int(op.PGAttributeNum)
}
i.AddComment(op.TableID, subID, catalogkeys.ColumnCommentType, op.Comment)
return nil
}
func (i *immediateVisitor) UpsertIndexComment(_ context.Context, op scop.UpsertIndexComment) error {
i.AddComment(op.TableID, int(op.IndexID), catalogkeys.IndexCommentType, op.Comment)
return nil
}
func (i *immediateVisitor) UpsertConstraintComment(
_ context.Context, op scop.UpsertConstraintComment,
) error {
i.AddComment(op.TableID, int(op.ConstraintID), catalogkeys.ConstraintCommentType, op.Comment)
return nil
}
| pkg/sql/schemachanger/scexec/scmutationexec/comment.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0003084362542722374,
0.00019017283921130002,
0.0001624204742256552,
0.00016940217756200582,
0.0000486068929603789
] |
{
"id": 4,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer conn.Close()\n",
"\n",
"\t\t// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tdefer func() { _ = conn.Close(ctx) }()\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 86
} | profile
virtual+noapp
----
canonical profile name: virtual+noapp
server started
system-sql
SELECT variable, value FROM [SHOW ALL CLUSTER SETTINGS]
WHERE variable IN (
'server.secondary_tenants.redact_trace.enabled',
'sql.zone_configs.allow_for_secondary_tenant.enabled',
'sql.multi_region.allow_abstractions_for_secondary_tenants.enabled',
'sql.multi_region.allow_abstractions_for_secondary_tenants.enabled',
'spanconfig.storage_coalesce_adjacent.enabled',
'spanconfig.tenant_coalesce_adjacent.enabled',
'sql.drop_virtual_cluster.enabled',
'sql.create_tenant.default_template',
'server.controller.default_tenant',
'kv.rangefeed.enabled',
'cross_cluster_replication.enabled'
)
ORDER BY variable
----
cross_cluster_replication.enabled false
kv.rangefeed.enabled false
server.controller.default_tenant system
server.secondary_tenants.redact_trace.enabled false
spanconfig.storage_coalesce_adjacent.enabled false
spanconfig.tenant_coalesce_adjacent.enabled false
sql.create_tenant.default_template template
sql.drop_virtual_cluster.enabled false
sql.multi_region.allow_abstractions_for_secondary_tenants.enabled true
sql.zone_configs.allow_for_secondary_tenant.enabled true
system-sql
SELECT tenant_id, name, value FROM system.tenant_settings
WHERE name IN (
'sql.scatter.allow_for_secondary_tenant.enabled',
'sql.split_at.allow_for_secondary_tenant.enabled'
)
ORDER BY tenant_id, name
----
2 sql.scatter.allow_for_secondary_tenant.enabled true
2 sql.split_at.allow_for_secondary_tenant.enabled true
system-sql
SHOW TENANTS WITH CAPABILITIES
----
1 system ready shared can_admin_relocate_range true
1 system ready shared can_admin_scatter true
1 system ready shared can_admin_split true
1 system ready shared can_admin_unsplit true
1 system ready shared can_check_consistency true
1 system ready shared can_debug_process true
1 system ready shared can_use_nodelocal_storage true
1 system ready shared can_view_node_info true
1 system ready shared can_view_tsdb_metrics true
1 system ready shared exempt_from_rate_limiting true
1 system ready shared span_config_bounds {}
2 template ready none can_admin_relocate_range true
2 template ready none can_admin_scatter true
2 template ready none can_admin_split true
2 template ready none can_admin_unsplit true
2 template ready none can_check_consistency true
2 template ready none can_debug_process true
2 template ready none can_use_nodelocal_storage true
2 template ready none can_view_node_info true
2 template ready none can_view_tsdb_metrics true
2 template ready none exempt_from_rate_limiting true
2 template ready none span_config_bounds {}
system-sql
CREATE TENANT application LIKE template
----
<no rows>
system-sql
ALTER TENANT application START SERVICE SHARED
----
<no rows>
connect-tenant
application
----
ok
| pkg/configprofiles/testdata/virtual-noapp | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0007092451560311019,
0.00026522474945522845,
0.00016370491357520223,
0.00016627516015432775,
0.000176765417563729
] |
{
"id": 4,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer conn.Close()\n",
"\n",
"\t\t// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tdefer func() { _ = conn.Close(ctx) }()\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 86
} | // Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package constraint
import (
"bytes"
"fmt"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
)
// EmptyKey has zero values. If it's a start key, then it sorts before all
// other keys. If it's an end key, then it sorts after all other keys.
var EmptyKey = Key{}
// Key is a composite of N typed datum values that are ordered from most
// significant to least significant for purposes of sorting. The datum values
// correspond to a set of columns; it is the responsibility of the calling code
// to keep track of them.
// Key is immutable; it cannot be changed once created.
type Key struct {
// firstVal stores the first value in the key. Subsequent values are stored
// in otherVals. Inlining the first value avoids an extra allocation in the
// common case of a single value in the key.
firstVal tree.Datum
// otherVals is an ordered list of typed datum values. It only stores values
// after the first, and is nil if there is <= 1 value.
otherVals tree.Datums
}
// MakeKey constructs a simple one dimensional key having the given value. If
// val is nil, then MakeKey returns an empty key.
func MakeKey(val tree.Datum) Key {
return Key{firstVal: val}
}
// MakeCompositeKey constructs an N-dimensional key from the given slice of
// values.
func MakeCompositeKey(vals ...tree.Datum) Key {
switch len(vals) {
case 0:
return Key{}
case 1:
return Key{firstVal: vals[0]}
}
return Key{firstVal: vals[0], otherVals: vals[1:]}
}
// IsEmpty is true if this key has zero values.
func (k Key) IsEmpty() bool {
return k.firstVal == nil
}
// IsNull is true if this key is the NULL value.
func (k Key) IsNull() bool {
return k.Length() == 1 && k.firstVal == tree.DNull
}
// Length returns the number of values in the key. If the count is zero, then
// this is an empty key.
func (k Key) Length() int {
if k.IsEmpty() {
return 0
}
return 1 + len(k.otherVals)
}
// Value returns the nth value of the key. If the index is out-of-range, then
// Value will panic.
func (k Key) Value(nth int) tree.Datum {
if k.firstVal != nil && nth == 0 {
return k.firstVal
}
return k.otherVals[nth-1]
}
// Compare returns an integer indicating the ordering of the two keys. The
// result will be 0 if the keys are equal, -1 if this key is less than the
// given key, or 1 if this key is greater.
//
// Comparisons between keys where one key is a prefix of the other have special
// handling which can be controlled via the key extension parameters. Key
// extensions specify whether each key is conceptually suffixed with negative
// or positive infinity for purposes of comparison. For example, if k is /1/2,
// then:
//
// k (kExt = ExtendLow) : /1/2/Low
// k (kExt = ExtendHigh): /1/2/High
//
// These extensions have no effect if one key is not a prefix of the other,
// since the comparison would already have concluded in previous values. But
// if comparison proceeds all the way to the end of one of the keys, then the
// extension determines which key is greater. This enables correct comparison
// of start and end keys in spans which may be either inclusive or exclusive.
// Here is the mapping:
//
// [/1/2 - ...] (inclusive start key): ExtendLow : /1/2/Low
// (/1/2 - ...] (exclusive start key): ExtendHigh: /1/2/High
// [... - /1/2] (inclusive end key) : ExtendHigh: /1/2/High
// [... - /1/2) (exclusive end key) : ExtendLow : /1/2/Low
func (k Key) Compare(keyCtx *KeyContext, l Key, kext, lext KeyExtension) int {
klen := k.Length()
llen := l.Length()
for i := 0; i < klen && i < llen; i++ {
if cmp := keyCtx.Compare(i, k.Value(i), l.Value(i)); cmp != 0 {
return cmp
}
}
if klen < llen {
// k matches a prefix of l:
// k = /1
// l = /1/2
// Which of these is "smaller" depends on whether k is extended with
// -inf or with +inf:
// k (ExtendLow) = /1/Low < /1/2 -> k is smaller (-1)
// k (ExtendHigh) = /1/High > /1/2 -> k is bigger (1)
return kext.ToCmp()
} else if klen > llen {
// Inverse case of above.
return -lext.ToCmp()
}
// Equal keys:
// k (ExtendLow) vs. l (ExtendLow) -> equal (0)
// k (ExtendLow) vs. l (ExtendHigh) -> smaller (-1)
// k (ExtendHigh) vs. l (ExtendLow) -> bigger (1)
// k (ExtendHigh) vs. l (ExtendHigh) -> equal (0)
if kext == lext {
return 0
}
return kext.ToCmp()
}
// Concat creates a new composite key by extending this key's values with the
// values of the given key. The new key's length is len(k) + len(l).
func (k Key) Concat(l Key) Key {
klen := k.Length()
llen := l.Length()
if klen == 0 {
return l
}
if llen == 0 {
return k
}
vals := make(tree.Datums, klen+llen-1)
copy(vals, k.otherVals)
vals[klen-1] = l.firstVal
copy(vals[klen:], l.otherVals)
return Key{firstVal: k.firstVal, otherVals: vals}
}
// CutFront returns the key with the first numCols values removed.
// Example:
//
// [/1/2 - /1/3].CutFront(1) = [/2 - /3]
func (k Key) CutFront(numCols int) Key {
if numCols == 0 {
return k
}
if len(k.otherVals) < numCols {
return EmptyKey
}
return Key{
firstVal: k.otherVals[numCols-1],
otherVals: k.otherVals[numCols:],
}
}
// CutBack returns the key with the last numCols values removed.
// Example:
//
// '/1/2'.CutBack(1) = '/1'
func (k Key) CutBack(numCols int) Key {
if numCols == 0 {
return k
}
if len(k.otherVals) < numCols {
return EmptyKey
}
return Key{
firstVal: k.firstVal,
otherVals: k.otherVals[:len(k.otherVals)-numCols],
}
}
// IsNextKey returns true if:
// - k and other have the same length;
// - on all but the last column, k and other have the same values;
// - on the last column, k has the datum that follows other's datum (for
// types that support it).
//
// For example: /2.IsNextKey(/1) is true.
func (k Key) IsNextKey(keyCtx *KeyContext, other Key) bool {
n := k.Length()
if n != other.Length() {
return false
}
// All the datums up to the last one must be equal.
for i := 0; i < n-1; i++ {
if keyCtx.Compare(i, k.Value(i), other.Value(i)) != 0 {
return false
}
}
next, ok := keyCtx.Next(n-1, other.Value(n-1))
return ok && keyCtx.Compare(n-1, k.Value(n-1), next) == 0
}
// Next returns the next key; this only works for discrete types like integers.
// It is guaranteed that there are no possible keys in the span
//
// ( key, Next(keu) ).
//
// Examples:
//
// Next(/1/2) = /1/3
// Next(/1/false) = /1/true
// Next(/1/true) returns !ok
// Next(/'foo') = /'foo\x00'
//
// If a column is descending, the values on that column go backwards:
//
// Next(/2) = /1
//
// The key cannot be empty.
func (k Key) Next(keyCtx *KeyContext) (_ Key, ok bool) {
// TODO(radu): here we could do a better job: if we know the last value is the
// maximum possible value, we could shorten the key; for example
// Next(/1/true) -> /2
// This is a bit tricky to implement because of NULL values (e.g. on a
// descending nullable column, "false" is not the minimum value, NULL is).
col := k.Length() - 1
nextVal, ok := keyCtx.Next(col, k.Value(col))
if !ok {
return Key{}, false
}
if col == 0 {
return Key{firstVal: nextVal}, true
}
// Keep the key up to col, and replace the value for col with nextVal.
vals := make([]tree.Datum, col)
copy(vals[:col-1], k.otherVals)
vals[col-1] = nextVal
return Key{firstVal: k.firstVal, otherVals: vals}, true
}
// Prev returns the next key; this only works for discrete types like integers.
//
// Examples:
//
// Prev(/1/2) = /1/1
// Prev(/1/true) = /1/false
// Prev(/1/false) returns !ok.
// Prev(/'foo') returns !ok.
//
// If a column is descending, the values on that column go backwards:
//
// Prev(/1) = /2
//
// If this is the minimum possible key, returns EmptyKey.
func (k Key) Prev(keyCtx *KeyContext) (_ Key, ok bool) {
col := k.Length() - 1
prevVal, ok := keyCtx.Prev(col, k.Value(col))
if !ok {
return Key{}, false
}
if col == 0 {
return Key{firstVal: prevVal}, true
}
// Keep the key up to col, and replace the value for col with prevVal.
vals := make([]tree.Datum, col)
copy(vals[:col-1], k.otherVals)
vals[col-1] = prevVal
return Key{firstVal: k.firstVal, otherVals: vals}, true
}
// String formats a key like this:
//
// EmptyKey : empty string
// Key with 1 value : /2
// Key with 2 values: /5/1
// Key with 3 values: /3/6/4
func (k Key) String() string {
var buf bytes.Buffer
for i := 0; i < k.Length(); i++ {
fmt.Fprintf(&buf, "/%s", k.Value(i))
}
return buf.String()
}
// KeyContext contains the necessary metadata for comparing Keys.
type KeyContext struct {
Columns Columns
EvalCtx *eval.Context
}
// MakeKeyContext initializes a KeyContext.
func MakeKeyContext(cols *Columns, evalCtx *eval.Context) KeyContext {
return KeyContext{Columns: *cols, EvalCtx: evalCtx}
}
// Compare two values for a given column.
// Returns 0 if the values are equal, -1 if a is less than b, or 1 if b is less
// than a.
func (c *KeyContext) Compare(colIdx int, a, b tree.Datum) int {
// Fast path when the datums are the same.
if a == b {
return 0
}
cmp := a.Compare(c.EvalCtx, b)
if c.Columns.Get(colIdx).Descending() {
cmp = -cmp
}
return cmp
}
// Next returns the next value on a given column (for discrete types like
// integers). See Datum.Next/Prev.
func (c *KeyContext) Next(colIdx int, val tree.Datum) (_ tree.Datum, ok bool) {
if c.Columns.Get(colIdx).Ascending() {
if val.IsMax(c.EvalCtx) {
return nil, false
}
return val.Next(c.EvalCtx)
}
if val.IsMin(c.EvalCtx) {
return nil, false
}
return val.Prev(c.EvalCtx)
}
// Prev returns the previous value on a given column (for discrete types like
// integers). See Datum.Next/Prev.
func (c *KeyContext) Prev(colIdx int, val tree.Datum) (_ tree.Datum, ok bool) {
if c.Columns.Get(colIdx).Ascending() {
if val.IsMin(c.EvalCtx) {
return nil, false
}
return val.Prev(c.EvalCtx)
}
if val.IsMax(c.EvalCtx) {
return nil, false
}
return val.Next(c.EvalCtx)
}
| pkg/sql/opt/constraint/key.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0008474107016809285,
0.00018925963377114385,
0.000162963115144521,
0.0001696258841548115,
0.00011136168177472427
] |
{
"id": 5,
"code_window": [
"\n",
"\t\t// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.\n",
"\t\t// Since lib/pq doesn't tell us the name of the prepared statement, we won't\n",
"\t\t// be able to test that we can use it after deserializing the session, but\n",
"\t\t// there are other tests for that.\n",
"\t\tstmt, err := conn.Prepare(\"SELECT 1 WHERE 1 = 1\")\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t_, err = conn.Prepare(ctx, \"prepared_stmt\", \"SELECT $1::INT4, 'foo'::typ WHERE 1 = 1\")\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\tvar intResult int\n",
"\t\tvar enumResult string\n",
"\t\terr = conn.QueryRow(ctx, \"prepared_stmt\", 1).Scan(&intResult, &enumResult)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 89
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.9972973465919495,
0.08844605833292007,
0.0001683031878201291,
0.002587579656392336,
0.27011704444885254
] |
{
"id": 5,
"code_window": [
"\n",
"\t\t// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.\n",
"\t\t// Since lib/pq doesn't tell us the name of the prepared statement, we won't\n",
"\t\t// be able to test that we can use it after deserializing the session, but\n",
"\t\t// there are other tests for that.\n",
"\t\tstmt, err := conn.Prepare(\"SELECT 1 WHERE 1 = 1\")\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t_, err = conn.Prepare(ctx, \"prepared_stmt\", \"SELECT $1::INT4, 'foo'::typ WHERE 1 = 1\")\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\tvar intResult int\n",
"\t\tvar enumResult string\n",
"\t\terr = conn.QueryRow(ctx, \"prepared_stmt\", 1).Scan(&intResult, &enumResult)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 89
} | // Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package rttanalysis
import "testing"
func BenchmarkAudit(b *testing.B) { reg.Run(b) }
func init() {
reg.Register("Audit", []RoundTripBenchTestCase{
{
Name: "select from an audit table",
Setup: `CREATE TABLE audit_table(a INT);
ALTER TABLE audit_table EXPERIMENTAL_AUDIT SET READ WRITE;`,
Stmt: "SELECT * from audit_table",
},
})
}
| pkg/bench/rttanalysis/audit_bench_test.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0005385805270634592,
0.00029807668761350214,
0.00017510561156086624,
0.00018054388056043535,
0.0001700763968983665
] |
{
"id": 5,
"code_window": [
"\n",
"\t\t// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.\n",
"\t\t// Since lib/pq doesn't tell us the name of the prepared statement, we won't\n",
"\t\t// be able to test that we can use it after deserializing the session, but\n",
"\t\t// there are other tests for that.\n",
"\t\tstmt, err := conn.Prepare(\"SELECT 1 WHERE 1 = 1\")\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t_, err = conn.Prepare(ctx, \"prepared_stmt\", \"SELECT $1::INT4, 'foo'::typ WHERE 1 = 1\")\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\tvar intResult int\n",
"\t\tvar enumResult string\n",
"\t\terr = conn.QueryRow(ctx, \"prepared_stmt\", 1).Scan(&intResult, &enumResult)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 89
} | create_schedule_for_changefeed_stmt ::=
'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' changefeed_target ( ( ',' changefeed_target ) )* ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'RECURRING' crontab 'WITH' 'SCHEDULE' 'OPTIONS' schedule_option
| 'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' changefeed_target ( ( ',' changefeed_target ) )* ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'RECURRING' crontab 'WITH' 'SCHEDULE' 'OPTIONS' '(' schedule_option ')'
| 'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' changefeed_target ( ( ',' changefeed_target ) )* ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'RECURRING' crontab
| 'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'AS' 'SELECT' target_list 'FROM' insert_target where_clause 'RECURRING' crontab 'WITH' 'SCHEDULE' 'OPTIONS' schedule_option
| 'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'AS' 'SELECT' target_list 'FROM' insert_target where_clause 'RECURRING' crontab 'WITH' 'SCHEDULE' 'OPTIONS' '(' schedule_option ')'
| 'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'AS' 'SELECT' target_list 'FROM' insert_target where_clause 'RECURRING' crontab
| 'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'AS' 'SELECT' target_list 'FROM' insert_target 'RECURRING' crontab 'WITH' 'SCHEDULE' 'OPTIONS' schedule_option
| 'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'AS' 'SELECT' target_list 'FROM' insert_target 'RECURRING' crontab 'WITH' 'SCHEDULE' 'OPTIONS' '(' schedule_option ')'
| 'CREATE' 'SCHEDULE' ( 'IF NOT EXISTS' | ) schedule_label 'FOR' 'CHANGEFEED' ( 'INTO' changefeed_sink ) ( | 'WITH' changefeed_option ( ',' changefeed_option )* ) 'AS' 'SELECT' target_list 'FROM' insert_target 'RECURRING' crontab
| docs/generated/sql/bnf/create_schedule_for_changefeed_stmt.bnf | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.9073797464370728,
0.45377591252326965,
0.00017209847283083946,
0.45377591252326965,
0.4536038339138031
] |
{
"id": 5,
"code_window": [
"\n",
"\t\t// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.\n",
"\t\t// Since lib/pq doesn't tell us the name of the prepared statement, we won't\n",
"\t\t// be able to test that we can use it after deserializing the session, but\n",
"\t\t// there are other tests for that.\n",
"\t\tstmt, err := conn.Prepare(\"SELECT 1 WHERE 1 = 1\")\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t_, err = conn.Prepare(ctx, \"prepared_stmt\", \"SELECT $1::INT4, 'foo'::typ WHERE 1 = 1\")\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\tvar intResult int\n",
"\t\tvar enumResult string\n",
"\t\terr = conn.QueryRow(ctx, \"prepared_stmt\", 1).Scan(&intResult, &enumResult)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 89
} | // Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
// Package catalogkeys describes keys used by the SQL catalog.
package catalogkeys
import (
"strings"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catenumpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
)
const (
// DefaultDatabaseName is the name ofthe default CockroachDB database used
// for connections without a current db set.
DefaultDatabaseName = "defaultdb"
// PgDatabaseName is the name of the default postgres system database.
PgDatabaseName = "postgres"
)
// DefaultUserDBs is a set of the databases which are present in a new cluster.
var DefaultUserDBs = []string{
DefaultDatabaseName, PgDatabaseName,
}
// CommentType the type of the schema object on which a comment has been
// applied.
type CommentType int
//go:generate stringer --type CommentType
// Note: please add the new comment types to AllCommentTypes as well.
// Note: do not change the numeric values of this enum -- they correspond
// to stored values in system.comments.
const (
// DatabaseCommentType comment on a database.
DatabaseCommentType CommentType = 0
// TableCommentType comment on a table/view/sequence.
TableCommentType CommentType = 1
// ColumnCommentType comment on a column.
ColumnCommentType CommentType = 2
// IndexCommentType comment on an index.
IndexCommentType CommentType = 3
// SchemaCommentType comment on a schema.
SchemaCommentType CommentType = 4
// ConstraintCommentType comment on a constraint.
ConstraintCommentType CommentType = 5
// FunctionCommentType comment on a function.
FunctionCommentType CommentType = 6
// MaxCommentTypeValue is the max possible integer of CommentType type.
// Update this whenever a new comment type is added.
MaxCommentTypeValue = FunctionCommentType
)
// AllCommentTypes is a slice of all valid schema comment types.
var AllCommentTypes = []CommentType{
DatabaseCommentType,
TableCommentType,
ColumnCommentType,
IndexCommentType,
SchemaCommentType,
ConstraintCommentType,
FunctionCommentType,
}
// IsValidCommentType checks if a given comment type is in the valid value
// range.
func IsValidCommentType(t CommentType) bool {
return t >= 0 && t <= MaxCommentTypeValue
}
func init() {
if len(AllCommentTypes) != int(MaxCommentTypeValue+1) {
panic("AllCommentTypes should contains all comment types.")
}
}
// AllTableCommentTypes is a slice of all valid comment types on table elements.
var AllTableCommentTypes = []CommentType{
TableCommentType,
ColumnCommentType,
IndexCommentType,
ConstraintCommentType,
}
// CommentKey represents the primary index key of system.comments table.
type CommentKey struct {
// ObjectID is the id of a schema object (e.g. database, schema and table)
ObjectID uint32
// SubID is the id of child element of a schema object. For example, in
// tables, this can be column id, index id or constraints id. CommentType is
// used to distinguish different sub element types. Some objects, for example
// database and schema, don't have child elements and SubID is zero for them.
SubID uint32
// CommentType represents which type of object or subelement the comment is
// for.
CommentType CommentType
}
// MakeCommentKey returns a new CommentKey.
func MakeCommentKey(objID uint32, subID uint32, cmtType CommentType) CommentKey {
return CommentKey{
ObjectID: objID,
SubID: subID,
CommentType: cmtType,
}
}
// IndexColumnEncodingDirection converts a direction from the proto to an
// encoding.Direction.
func IndexColumnEncodingDirection(dir catenumpb.IndexColumn_Direction) (encoding.Direction, error) {
switch dir {
case catenumpb.IndexColumn_ASC:
return encoding.Ascending, nil
case catenumpb.IndexColumn_DESC:
return encoding.Descending, nil
default:
return 0, errors.Errorf("invalid direction: %s", dir)
}
}
// IndexKeyValDirs returns the corresponding encoding.Directions for all the
// encoded values in index's "fullest" possible index key, including directions
// for table/index IDs and the index column values.
func IndexKeyValDirs(index catalog.Index) []encoding.Direction {
if index == nil {
return nil
}
dirs := make([]encoding.Direction, 0, 2+index.NumKeyColumns())
// The index's table/index ID.
dirs = append(dirs, encoding.Ascending, encoding.Ascending)
for colIdx := 0; colIdx < index.NumKeyColumns(); colIdx++ {
d, err := IndexColumnEncodingDirection(index.GetKeyColumnDirection(colIdx))
if err != nil {
panic(err)
}
dirs = append(dirs, d)
}
return dirs
}
// PrettyKey pretty-prints the specified key, skipping over the first `skip`
// fields. The pretty printed key looks like:
//
// /Table/<tableID>/<indexID>/...
//
// We always strip off the /Table prefix and then `skip` more fields. Note that
// this assumes that the fields themselves do not contain '/', but that is
// currently true for the fields we care about stripping (the table and index
// ID).
func PrettyKey(valDirs []encoding.Direction, key roachpb.Key, skip int) string {
var buf redact.StringBuilder
key.StringWithDirs(&buf, valDirs)
p := buf.String()
for i := 0; i <= skip; i++ {
n := strings.IndexByte(p[1:], '/')
if n == -1 {
return ""
}
p = p[n+1:]
}
return p
}
// PrettySpan returns a human-readable representation of a span.
func PrettySpan(valDirs []encoding.Direction, span roachpb.Span, skip int) string {
var b strings.Builder
b.WriteString(PrettyKey(valDirs, span.Key, skip))
if span.EndKey != nil {
b.WriteByte('-')
b.WriteString(PrettyKey(valDirs, span.EndKey, skip))
}
return b.String()
}
// PrettySpans returns a human-readable description of the spans.
// If index is nil, then pretty print subroutines will use their default
// settings.
func PrettySpans(index catalog.Index, spans []roachpb.Span, skip int) string {
if len(spans) == 0 {
return ""
}
valDirs := IndexKeyValDirs(index)
var b strings.Builder
for i, span := range spans {
if i > 0 {
b.WriteString(" ")
}
b.WriteString(PrettySpan(valDirs, span, skip))
}
return b.String()
}
// MakeDatabaseChildrenNameKeyPrefix constructs a key which is a prefix to all
// namespace entries for children of the requested database.
func MakeDatabaseChildrenNameKeyPrefix(codec keys.SQLCodec, parentID descpb.ID) roachpb.Key {
r := codec.IndexPrefix(keys.NamespaceTableID, catconstants.NamespaceTablePrimaryIndexID)
return encoding.EncodeUvarintAscending(r, uint64(parentID))
}
// EncodeNameKey encodes nameKey using codec.
func EncodeNameKey(codec keys.SQLCodec, nameKey catalog.NameKey) roachpb.Key {
r := MakeDatabaseChildrenNameKeyPrefix(codec, nameKey.GetParentID())
r = encoding.EncodeUvarintAscending(r, uint64(nameKey.GetParentSchemaID()))
if nameKey.GetName() != "" {
r = encoding.EncodeBytesAscending(r, []byte(nameKey.GetName()))
r = keys.MakeFamilyKey(r, catconstants.NamespaceTableFamilyID)
}
return r
}
// DecodeNameMetadataKey is the reciprocal of EncodeNameKey.
func DecodeNameMetadataKey(
codec keys.SQLCodec, k roachpb.Key,
) (nameKey descpb.NameInfo, err error) {
k, _, err = codec.DecodeTablePrefix(k)
if err != nil {
return nameKey, err
}
var buf uint64
k, buf, err = encoding.DecodeUvarintAscending(k)
if err != nil {
return nameKey, err
}
if buf != uint64(catconstants.NamespaceTablePrimaryIndexID) {
return nameKey, errors.Newf("tried get table %d, but got %d", catconstants.NamespaceTablePrimaryIndexID, buf)
}
k, buf, err = encoding.DecodeUvarintAscending(k)
if err != nil {
return nameKey, err
}
nameKey.ParentID = descpb.ID(buf)
k, buf, err = encoding.DecodeUvarintAscending(k)
if err != nil {
return nameKey, err
}
nameKey.ParentSchemaID = descpb.ID(buf)
var bytesBuf []byte
_, bytesBuf, err = encoding.DecodeBytesAscending(k, nil)
if err != nil {
return nameKey, err
}
nameKey.Name = string(bytesBuf)
return nameKey, nil
}
// MakeAllDescsMetadataKey returns the key for all descriptors.
func MakeAllDescsMetadataKey(codec keys.SQLCodec) roachpb.Key {
return codec.DescMetadataPrefix()
}
// MakeDescMetadataKey returns the key for the descriptor.
func MakeDescMetadataKey(codec keys.SQLCodec, descID descpb.ID) roachpb.Key {
return codec.DescMetadataKey(uint32(descID))
}
// CommentsMetadataPrefix returns the key prefix for all comments in the
// system.comments table.
func CommentsMetadataPrefix(codec keys.SQLCodec) roachpb.Key {
return codec.IndexPrefix(keys.CommentsTableID, keys.CommentsTablePrimaryKeyIndexID)
}
// MakeObjectCommentsMetadataPrefix returns the key prefix for a type of comments
// of a descriptor.
func MakeObjectCommentsMetadataPrefix(
codec keys.SQLCodec, cmtKey CommentType, descID descpb.ID,
) roachpb.Key {
k := CommentsMetadataPrefix(codec)
k = encoding.EncodeUvarintAscending(k, uint64(cmtKey))
return encoding.EncodeUvarintAscending(k, uint64(descID))
}
// MakeSubObjectCommentsMetadataPrefix returns the key
func MakeSubObjectCommentsMetadataPrefix(
codec keys.SQLCodec, cmtKey CommentType, descID descpb.ID, subID uint32,
) roachpb.Key {
k := MakeObjectCommentsMetadataPrefix(codec, cmtKey, descID)
return encoding.EncodeUvarintAscending(k, uint64(subID))
}
// DecodeCommentMetadataID decodes a CommentKey from comments metadata key.
func DecodeCommentMetadataID(codec keys.SQLCodec, key roachpb.Key) ([]byte, CommentKey, error) {
remaining, tableID, indexID, err := codec.DecodeIndexPrefix(key)
if err != nil {
return nil, CommentKey{}, err
}
if tableID != keys.CommentsTableID || indexID != keys.CommentsTablePrimaryKeyIndexID {
return nil, CommentKey{}, errors.Errorf("key is not a comments table entry: %v", key)
}
remaining, cmtType, err := encoding.DecodeUvarintAscending(remaining)
if err != nil {
return nil, CommentKey{}, err
}
remaining, objID, err := encoding.DecodeUvarintAscending(remaining)
if err != nil {
return nil, CommentKey{}, err
}
remaining, subID, err := encoding.DecodeUvarintAscending(remaining)
if err != nil {
return nil, CommentKey{}, err
}
return remaining, MakeCommentKey(uint32(objID), uint32(subID), CommentType(cmtType)), nil
}
| pkg/sql/catalog/catalogkeys/keys.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.002169832121580839,
0.0003834873787127435,
0.0001638049870962277,
0.00017570203635841608,
0.0004529102589003742
] |
{
"id": 6,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer stmt.Close()\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\trequire.Equal(t, 1, intResult)\n",
"\t\trequire.Equal(t, \"foo\", enumResult)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 94
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.4172253906726837,
0.02151872031390667,
0.00016771764785517007,
0.0013011556584388018,
0.0864216759800911
] |
{
"id": 6,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer stmt.Close()\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\trequire.Equal(t, 1, intResult)\n",
"\t\trequire.Equal(t, \"foo\", enumResult)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 94
} | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sql
import (
"bytes"
"context"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/fetchpb"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
)
// deleteRangeNode implements DELETE on a primary index satisfying certain
// conditions that permit the direct use of the DeleteRange kv operation,
// instead of many point deletes.
//
// Note: deleteRangeNode can't autocommit in the general case, because it has to
// delete in batches, and it won't know whether or not there is more work to do
// until after a batch is returned. This property precludes using auto commit.
// However, if the optimizer can prove that only a small number of rows will
// be deleted, it'll enable autoCommit for delete range.
type deleteRangeNode struct {
// spans are the spans to delete.
spans roachpb.Spans
// desc is the table descriptor the delete is operating on.
desc catalog.TableDescriptor
// fetcher is around to decode the returned keys from the DeleteRange, so that
// we can count the number of rows deleted.
fetcher row.Fetcher
// autoCommitEnabled is set to true if the optimizer proved that we can safely
// use autocommit - so that the number of possible returned keys from this
// operation is low. If this is true, we won't attempt to run the delete in
// batches and will just send one big delete with a commit statement attached.
autoCommitEnabled bool
// rowCount will be set to the count of rows deleted.
rowCount int
}
var _ planNode = &deleteRangeNode{}
var _ planNodeFastPath = &deleteRangeNode{}
var _ batchedPlanNode = &deleteRangeNode{}
var _ mutationPlanNode = &deleteRangeNode{}
// BatchedNext implements the batchedPlanNode interface.
func (d *deleteRangeNode) BatchedNext(params runParams) (bool, error) {
return false, nil
}
// BatchedCount implements the batchedPlanNode interface.
func (d *deleteRangeNode) BatchedCount() int {
return d.rowCount
}
// BatchedValues implements the batchedPlanNode interface.
func (d *deleteRangeNode) BatchedValues(rowIdx int) tree.Datums {
panic("invalid")
}
// FastPathResults implements the planNodeFastPath interface.
func (d *deleteRangeNode) FastPathResults() (int, bool) {
return d.rowCount, true
}
func (d *deleteRangeNode) rowsWritten() int64 {
return int64(d.rowCount)
}
// startExec implements the planNode interface.
func (d *deleteRangeNode) startExec(params runParams) error {
if err := params.p.cancelChecker.Check(); err != nil {
return err
}
// Configure the fetcher, which is only used to decode the returned keys
// from the Del and the DelRange operations, and is never used to actually
// fetch kvs.
var spec fetchpb.IndexFetchSpec
if err := rowenc.InitIndexFetchSpec(
&spec, params.ExecCfg().Codec, d.desc, d.desc.GetPrimaryIndex(), nil, /* columnIDs */
); err != nil {
return err
}
if err := d.fetcher.Init(
params.ctx,
row.FetcherInitArgs{
WillUseKVProvider: true,
Alloc: &tree.DatumAlloc{},
Spec: &spec,
},
); err != nil {
return err
}
ctx := params.ctx
log.VEvent(ctx, 2, "fast delete: skipping scan")
spans := make([]roachpb.Span, len(d.spans))
copy(spans, d.spans)
if !d.autoCommitEnabled {
// Without autocommit, we're going to run each batch one by one, respecting
// a max span request keys size. We use spans as a queue of spans to delete.
// It'll be edited if there are any resume spans encountered (if any request
// hits the key limit).
for len(spans) != 0 {
b := params.p.txn.NewBatch()
b.Header.MaxSpanRequestKeys = row.TableTruncateChunkSize
b.Header.LockTimeout = params.SessionData().LockTimeout
d.deleteSpans(params, b, spans)
if err := params.p.txn.Run(ctx, b); err != nil {
return row.ConvertBatchError(ctx, d.desc, b)
}
spans = spans[:0]
var err error
if spans, err = d.processResults(b.Results, spans); err != nil {
return err
}
}
} else {
log.Event(ctx, "autocommit enabled")
// With autocommit, we're going to run the deleteRange in a single batch
// without a limit, since limits and deleteRange aren't compatible with 1pc
// transactions / autocommit. This isn't inherently safe, because without a
// limit, this command could technically use up unlimited memory. However,
// the optimizer only enables autoCommit if the maximum possible number of
// keys to delete in this command are low, so we're made safe.
b := params.p.txn.NewBatch()
b.Header.LockTimeout = params.SessionData().LockTimeout
d.deleteSpans(params, b, spans)
if err := params.p.txn.CommitInBatch(ctx, b); err != nil {
return row.ConvertBatchError(ctx, d.desc, b)
}
if resumeSpans, err := d.processResults(b.Results, nil /* resumeSpans */); err != nil {
return err
} else if len(resumeSpans) != 0 {
// This shouldn't ever happen - we didn't pass a limit into the batch.
return errors.AssertionFailedf("deleteRange without a limit unexpectedly returned resumeSpans")
}
}
// Possibly initiate a run of CREATE STATISTICS.
params.ExecCfg().StatsRefresher.NotifyMutation(d.desc, d.rowCount)
return nil
}
// deleteSpans adds each input span to a Del or a DelRange command in the given
// batch.
func (d *deleteRangeNode) deleteSpans(params runParams, b *kv.Batch, spans roachpb.Spans) {
ctx := params.ctx
traceKV := params.p.ExtendedEvalContext().Tracing.KVTracingEnabled()
for _, span := range spans {
if span.EndKey == nil {
if traceKV {
log.VEventf(ctx, 2, "Del %s", span.Key)
}
b.Del(span.Key)
} else {
if traceKV {
log.VEventf(ctx, 2, "DelRange %s - %s", span.Key, span.EndKey)
}
b.DelRange(span.Key, span.EndKey, true /* returnKeys */)
}
}
}
// processResults parses the results of a DelRangeResponse, incrementing the
// rowCount we're going to return for each row. If any resume spans are
// encountered during result processing, they're appended to the resumeSpans
// input parameter.
func (d *deleteRangeNode) processResults(
results []kv.Result, resumeSpans []roachpb.Span,
) (roachpb.Spans, error) {
for _, r := range results {
var prev []byte
for _, keyBytes := range r.Keys {
// If prefix is same, don't bother decoding key.
if len(prev) > 0 && bytes.HasPrefix(keyBytes, prev) {
continue
}
after, _, err := d.fetcher.DecodeIndexKey(keyBytes)
if err != nil {
return nil, err
}
k := keyBytes[:len(keyBytes)-len(after)]
if !bytes.Equal(k, prev) {
prev = k
d.rowCount++
}
}
if r.ResumeSpan != nil && r.ResumeSpan.Valid() {
resumeSpans = append(resumeSpans, *r.ResumeSpan)
}
}
return resumeSpans, nil
}
// Next implements the planNode interface.
func (*deleteRangeNode) Next(params runParams) (bool, error) {
// TODO(radu): this shouldn't be used, but it gets called when a cascade uses
// delete-range. Investigate this.
return false, nil
}
// Values implements the planNode interface.
func (*deleteRangeNode) Values() tree.Datums {
panic("invalid")
}
// Close implements the planNode interface.
func (*deleteRangeNode) Close(ctx context.Context) {}
| pkg/sql/delete_range.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0008590937359258533,
0.0002036633959505707,
0.0001618915266590193,
0.00016795947158243507,
0.00014102210116107017
] |
{
"id": 6,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer stmt.Close()\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\trequire.Equal(t, 1, intResult)\n",
"\t\trequire.Equal(t, \"foo\", enumResult)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 94
} | // Copyright 2017 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
//go:build race
// +build race
package util
import "runtime"
// RaceEnabled is true if CockroachDB was built with the race build tag.
const RaceEnabled = true
// racePreemptionPoints is set in EnableRacePreemptionPoints.
var racePreemptionPoints = false
// EnableRacePreemptionPoints enables goroutine preemption points declared with
// RacePreempt for builds using the race build tag.
func EnableRacePreemptionPoints() func() {
racePreemptionPoints = true
return func() {
racePreemptionPoints = false
}
}
// RacePreempt adds a goroutine preemption point if CockroachDB was built with
// the race build tag and preemption points have been enabled. The function is a
// no-op (and should be optimized out through dead code elimination) if the race
// build tag was not used.
func RacePreempt() {
if racePreemptionPoints {
runtime.Gosched()
}
}
| pkg/util/race_on.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00023383575899060816,
0.00019050943956244737,
0.0001698574924375862,
0.00018368785094935447,
0.000022615326088271104
] |
{
"id": 6,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer stmt.Close()\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\trequire.Equal(t, 1, intResult)\n",
"\t\trequire.Equal(t, \"foo\", enumResult)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 94
} | // Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package optbuilder
import (
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
)
// buildDelete builds a memo group for a DeleteOp expression, which deletes all
// rows projected by the input expression. All columns from the deletion table
// are projected, including mutation columns (the optimizer may later prune the
// columns if they are not needed).
//
// Note that the ORDER BY clause can only be used if the LIMIT clause is also
// present. In that case, the ordering determines which rows are included by the
// limit. The ORDER BY makes no additional guarantees about the order in which
// mutations are applied, or the order of any returned rows (i.e. it won't
// become a physical property required of the Delete operator).
func (b *Builder) buildDelete(del *tree.Delete, inScope *scope) (outScope *scope) {
// UX friendliness safeguard.
if del.Where == nil && b.evalCtx.SessionData().SafeUpdates {
panic(pgerror.DangerousStatementf("DELETE without WHERE clause"))
}
if del.OrderBy != nil && del.Limit == nil {
panic(pgerror.Newf(pgcode.Syntax,
"DELETE statement requires LIMIT when ORDER BY is used"))
}
batch := del.Batch
if batch != nil {
var hasSize bool
for i, param := range batch.Params {
switch param.(type) {
case *tree.SizeBatchParam:
if hasSize {
panic(pgerror.Newf(pgcode.Syntax, "invalid parameter at index %d, SIZE already specified", i))
}
hasSize = true
}
}
if hasSize {
// TODO(ecwall): remove when DELETE BATCH is supported
panic(pgerror.Newf(pgcode.Syntax,
"DELETE BATCH (SIZE <size>) not implemented"))
}
// TODO(ecwall): remove when DELETE BATCH is supported
panic(pgerror.Newf(pgcode.Syntax,
"DELETE BATCH not implemented"))
}
// Find which table we're working on, check the permissions.
tab, depName, alias, refColumns := b.resolveTableForMutation(del.Table, privilege.DELETE)
if refColumns != nil {
panic(pgerror.Newf(pgcode.Syntax,
"cannot specify a list of column IDs with DELETE"))
}
// Check Select permission as well, since existing values must be read.
b.checkPrivilege(depName, tab, privilege.SELECT)
// Check if this table has already been mutated in another subquery.
b.checkMultipleMutations(tab, generalMutation)
var mb mutationBuilder
mb.init(b, "delete", tab, alias)
// Build the input expression that selects the rows that will be deleted:
//
// WITH <with>
// SELECT <cols> FROM <table> WHERE <where>
// ORDER BY <order-by> LIMIT <limit>
//
// All columns from the delete table will be projected.
mb.buildInputForDelete(inScope, del.Table, del.Where, del.Using, del.Limit, del.OrderBy)
// Build the final delete statement, including any returned expressions.
if resultsNeeded(del.Returning) {
mb.buildDelete(del.Returning.(*tree.ReturningExprs))
} else {
mb.buildDelete(nil /* returning */)
}
return mb.outScope
}
// buildDelete constructs a Delete operator, possibly wrapped by a Project
// operator that corresponds to the given RETURNING clause.
func (mb *mutationBuilder) buildDelete(returning *tree.ReturningExprs) {
mb.buildFKChecksAndCascadesForDelete()
// Project partial index DEL boolean columns.
mb.projectPartialIndexDelCols()
private := mb.makeMutationPrivate(returning != nil)
for _, col := range mb.extraAccessibleCols {
if col.id != 0 {
private.PassthroughCols = append(private.PassthroughCols, col.id)
}
}
mb.outScope.expr = mb.b.factory.ConstructDelete(
mb.outScope.expr, mb.uniqueChecks, mb.fkChecks, private,
)
mb.buildReturning(returning)
}
| pkg/sql/opt/optbuilder/delete.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017600298451725394,
0.00016892014537006617,
0.0001653814542805776,
0.00016855719150044024,
0.0000026827349302038783
] |
{
"id": 7,
"code_window": [
"\n",
"\t\trows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)\n",
"\t\trequire.NoError(t, err, \"show transfer state failed\")\n",
"\t\tdefer rows.Close()\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\trows, err := conn.Query(ctx, `SHOW TRANSFER STATE WITH 'foobar'`, pgx.QueryExecModeSimpleProtocol)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 96
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.9981939196586609,
0.28188541531562805,
0.00017084067803807557,
0.00474148616194725,
0.43848368525505066
] |
{
"id": 7,
"code_window": [
"\n",
"\t\trows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)\n",
"\t\trequire.NoError(t, err, \"show transfer state failed\")\n",
"\t\tdefer rows.Close()\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\trows, err := conn.Query(ctx, `SHOW TRANSFER STATE WITH 'foobar'`, pgx.QueryExecModeSimpleProtocol)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 96
} | // Code generated by execgen; DO NOT EDIT.
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package colexecwindow
import (
"context"
"github.com/cockroachdb/cockroach/pkg/col/coldata"
"github.com/cockroachdb/cockroach/pkg/col/typeconv"
"github.com/cockroachdb/cockroach/pkg/sql/colexec/colexecutils"
"github.com/cockroachdb/cockroach/pkg/sql/colexecop"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/errors"
)
// NewLastValueOperator creates a new Operator that computes window
// function lastValue. outputColIdx specifies in which coldata.Vec the operator
// should put its output (if there is no such column, a new column is appended).
func NewLastValueOperator(
args *WindowArgs,
frame *execinfrapb.WindowerSpec_Frame,
ordering *execinfrapb.Ordering,
argIdxs []int,
) (colexecop.ClosableOperator, error) {
framer := newWindowFramer(args.EvalCtx, frame, ordering, args.InputTypes, args.PeersColIdx)
colsToStore := framer.getColsToStore([]int{argIdxs[0]})
// Allow the direct-access buffer 10% of the available memory. The rest will
// be given to the bufferedWindowOp queue. While it is somewhat more important
// for the direct-access buffer tuples to be kept in-memory, it only has to
// store a single column. TODO(drewk): play around with benchmarks to find a
// good empirically-supported fraction to use.
bufferMemLimit := int64(float64(args.MemoryLimit) * 0.10)
mainMemLimit := args.MemoryLimit - bufferMemLimit
buffer := colexecutils.NewSpillingBuffer(
args.BufferAllocator, bufferMemLimit, args.QueueCfg, args.FdSemaphore,
args.InputTypes, args.DiskAcc, args.ConverterMemAcc, colsToStore...,
)
base := lastValueBase{
partitionSeekerBase: partitionSeekerBase{
buffer: buffer,
partitionColIdx: args.PartitionColIdx,
},
framer: framer,
outputColIdx: args.OutputColIdx,
bufferArgIdx: 0, // The arg column is the first column in the buffer.
}
argType := args.InputTypes[argIdxs[0]]
switch typeconv.TypeFamilyToCanonicalTypeFamily(argType.Family()) {
case types.BoolFamily:
switch argType.Width() {
case -1:
default:
windower := &lastValueBoolWindow{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
case types.BytesFamily:
switch argType.Width() {
case -1:
default:
windower := &lastValueBytesWindow{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
case types.DecimalFamily:
switch argType.Width() {
case -1:
default:
windower := &lastValueDecimalWindow{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
case types.IntFamily:
switch argType.Width() {
case 16:
windower := &lastValueInt16Window{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
case 32:
windower := &lastValueInt32Window{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
case -1:
default:
windower := &lastValueInt64Window{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
case types.FloatFamily:
switch argType.Width() {
case -1:
default:
windower := &lastValueFloat64Window{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
case types.TimestampTZFamily:
switch argType.Width() {
case -1:
default:
windower := &lastValueTimestampWindow{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
case types.IntervalFamily:
switch argType.Width() {
case -1:
default:
windower := &lastValueIntervalWindow{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
case types.JsonFamily:
switch argType.Width() {
case -1:
default:
windower := &lastValueJSONWindow{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
case typeconv.DatumVecCanonicalTypeFamily:
switch argType.Width() {
case -1:
default:
windower := &lastValueDatumWindow{lastValueBase: base}
return newBufferedWindowOperator(args, windower, argType, mainMemLimit), nil
}
}
return nil, errors.Errorf("unsupported lastValue window operator type %s", argType.Name())
}
type lastValueBase struct {
partitionSeekerBase
colexecop.CloserHelper
framer windowFramer
outputColIdx int
bufferArgIdx int
}
type lastValueBoolWindow struct {
lastValueBase
}
var _ bufferedWindower = &lastValueBoolWindow{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueBoolWindow) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Bool()
outputNulls := outputVec.Nulls()
_, _ = outputCol.Get(startIdx), outputCol.Get(endIdx-1)
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Bool()
val := col.Get(idx)
//gcassert:bce
outputCol.Set(i, val)
}
}
type lastValueBytesWindow struct {
lastValueBase
}
var _ bufferedWindower = &lastValueBytesWindow{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueBytesWindow) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Bytes()
outputNulls := outputVec.Nulls()
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Bytes()
outputCol.Copy(col, i, idx)
}
}
type lastValueDecimalWindow struct {
lastValueBase
}
var _ bufferedWindower = &lastValueDecimalWindow{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueDecimalWindow) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Decimal()
outputNulls := outputVec.Nulls()
_, _ = outputCol.Get(startIdx), outputCol.Get(endIdx-1)
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Decimal()
val := col.Get(idx)
//gcassert:bce
outputCol.Set(i, val)
}
}
type lastValueInt16Window struct {
lastValueBase
}
var _ bufferedWindower = &lastValueInt16Window{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueInt16Window) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Int16()
outputNulls := outputVec.Nulls()
_, _ = outputCol.Get(startIdx), outputCol.Get(endIdx-1)
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Int16()
val := col.Get(idx)
//gcassert:bce
outputCol.Set(i, val)
}
}
type lastValueInt32Window struct {
lastValueBase
}
var _ bufferedWindower = &lastValueInt32Window{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueInt32Window) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Int32()
outputNulls := outputVec.Nulls()
_, _ = outputCol.Get(startIdx), outputCol.Get(endIdx-1)
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Int32()
val := col.Get(idx)
//gcassert:bce
outputCol.Set(i, val)
}
}
type lastValueInt64Window struct {
lastValueBase
}
var _ bufferedWindower = &lastValueInt64Window{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueInt64Window) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Int64()
outputNulls := outputVec.Nulls()
_, _ = outputCol.Get(startIdx), outputCol.Get(endIdx-1)
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Int64()
val := col.Get(idx)
//gcassert:bce
outputCol.Set(i, val)
}
}
type lastValueFloat64Window struct {
lastValueBase
}
var _ bufferedWindower = &lastValueFloat64Window{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueFloat64Window) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Float64()
outputNulls := outputVec.Nulls()
_, _ = outputCol.Get(startIdx), outputCol.Get(endIdx-1)
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Float64()
val := col.Get(idx)
//gcassert:bce
outputCol.Set(i, val)
}
}
type lastValueTimestampWindow struct {
lastValueBase
}
var _ bufferedWindower = &lastValueTimestampWindow{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueTimestampWindow) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Timestamp()
outputNulls := outputVec.Nulls()
_, _ = outputCol.Get(startIdx), outputCol.Get(endIdx-1)
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Timestamp()
val := col.Get(idx)
//gcassert:bce
outputCol.Set(i, val)
}
}
type lastValueIntervalWindow struct {
lastValueBase
}
var _ bufferedWindower = &lastValueIntervalWindow{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueIntervalWindow) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Interval()
outputNulls := outputVec.Nulls()
_, _ = outputCol.Get(startIdx), outputCol.Get(endIdx-1)
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Interval()
val := col.Get(idx)
//gcassert:bce
outputCol.Set(i, val)
}
}
type lastValueJSONWindow struct {
lastValueBase
}
var _ bufferedWindower = &lastValueJSONWindow{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueJSONWindow) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.JSON()
outputNulls := outputVec.Nulls()
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.JSON()
outputCol.Copy(col, i, idx)
}
}
type lastValueDatumWindow struct {
lastValueBase
}
var _ bufferedWindower = &lastValueDatumWindow{}
// processBatch implements the bufferedWindower interface.
func (w *lastValueDatumWindow) processBatch(batch coldata.Batch, startIdx, endIdx int) {
if startIdx >= endIdx {
// No processing needs to be done for this portion of the current partition.
return
}
outputVec := batch.ColVec(w.outputColIdx)
outputCol := outputVec.Datum()
outputNulls := outputVec.Nulls()
for i := startIdx; i < endIdx; i++ {
w.framer.next(w.Ctx)
requestedIdx := w.framer.frameLastIdx()
if requestedIdx == -1 {
// The requested row does not exist.
outputNulls.SetNull(i)
continue
}
vec, idx, _ := w.buffer.GetVecWithTuple(w.Ctx, w.bufferArgIdx, requestedIdx)
if vec.Nulls().MaybeHasNulls() && vec.Nulls().NullAt(idx) {
outputNulls.SetNull(i)
continue
}
col := vec.Datum()
val := col.Get(idx)
outputCol.Set(i, val)
}
}
// transitionToProcessing implements the bufferedWindower interface.
func (b *lastValueBase) transitionToProcessing() {
b.framer.startPartition(b.Ctx, b.partitionSize, b.buffer)
}
// startNewPartition implements the bufferedWindower interface.
func (b *lastValueBase) startNewPartition() {
b.partitionSize = 0
b.buffer.Reset(b.Ctx)
}
// Init implements the bufferedWindower interface.
func (b *lastValueBase) Init(ctx context.Context) {
if !b.InitHelper.Init(ctx) {
return
}
}
// Close implements the bufferedWindower interface.
func (b *lastValueBase) Close(ctx context.Context) {
if !b.CloserHelper.Close() {
return
}
b.buffer.Close(ctx)
}
| pkg/sql/colexec/colexecwindow/last_value.eg.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.001325911609455943,
0.00020053476328030229,
0.0001635100634302944,
0.0001689212949713692,
0.00016023663920350373
] |
{
"id": 7,
"code_window": [
"\n",
"\t\trows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)\n",
"\t\trequire.NoError(t, err, \"show transfer state failed\")\n",
"\t\tdefer rows.Close()\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\trows, err := conn.Query(ctx, `SHOW TRANSFER STATE WITH 'foobar'`, pgx.QueryExecModeSimpleProtocol)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 96
} | // Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package scexec
import (
"context"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scop"
"github.com/cockroachdb/errors"
)
// ExecuteStage executes the provided ops. The ops must all be of the same type.
func ExecuteStage(ctx context.Context, deps Dependencies, phase scop.Phase, ops []scop.Op) error {
if len(ops) == 0 {
return nil
}
typ := ops[0].Type()
switch typ {
case scop.MutationType:
return executeMutationOps(ctx, deps, phase, ops)
case scop.BackfillType:
return executeBackfillOps(ctx, deps, ops)
case scop.ValidationType:
return executeValidationOps(ctx, deps, ops)
default:
return errors.AssertionFailedf("unknown ops type %d", typ)
}
}
| pkg/sql/schemachanger/scexec/executor.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0001766908826539293,
0.00017118777032010257,
0.00016534033056814224,
0.0001713599485810846,
0.000004154664111410966
] |
{
"id": 7,
"code_window": [
"\n",
"\t\trows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)\n",
"\t\trequire.NoError(t, err, \"show transfer state failed\")\n",
"\t\tdefer rows.Close()\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\trows, err := conn.Query(ctx, `SHOW TRANSFER STATE WITH 'foobar'`, pgx.QueryExecModeSimpleProtocol)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 96
} | // Copyright 2017 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
import { AdminUIState } from "src/redux/state";
export function selectEnterpriseEnabled(state: AdminUIState) {
return (
state.cachedData.cluster.valid &&
state.cachedData.cluster.data.enterprise_enabled
);
}
| pkg/ui/workspaces/db-console/ccl/src/redux/license.ts | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017609127098694444,
0.00017294895951636136,
0.00016980664804577827,
0.00017294895951636136,
0.0000031423114705830812
] |
{
"id": 8,
"code_window": [
"\t\trequire.NoError(t, err, \"show transfer state failed\")\n",
"\t\tdefer rows.Close()\n",
"\n",
"\t\tresultColumns, err := rows.Columns()\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\trequire.Equal(t, []string{\n",
"\t\t\t\"error\",\n",
"\t\t\t\"session_state_base64\",\n",
"\t\t\t\"session_revival_token_base64\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tfieldDescriptions := rows.FieldDescriptions()\n",
"\t\tvar resultColumns []string\n",
"\t\tfor _, f := range fieldDescriptions {\n",
"\t\t\tresultColumns = append(resultColumns, f.Name)\n",
"\t\t}\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 100
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.997681736946106,
0.1759493499994278,
0.00017001126252580434,
0.0031048604287207127,
0.35789236426353455
] |
{
"id": 8,
"code_window": [
"\t\trequire.NoError(t, err, \"show transfer state failed\")\n",
"\t\tdefer rows.Close()\n",
"\n",
"\t\tresultColumns, err := rows.Columns()\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\trequire.Equal(t, []string{\n",
"\t\t\t\"error\",\n",
"\t\t\t\"session_state_base64\",\n",
"\t\t\t\"session_revival_token_base64\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tfieldDescriptions := rows.FieldDescriptions()\n",
"\t\tvar resultColumns []string\n",
"\t\tfor _, f := range fieldDescriptions {\n",
"\t\t\tresultColumns = append(resultColumns, f.Name)\n",
"\t\t}\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 100
} | # Generating the code for `sort_partitioner.eg.go` requires special handling
# because the template lives in a subpackage.
def gen_sort_partitioner_rule(name, target, visibility = ["//visibility:private"]):
native.genrule(
name = name,
srcs = ["//pkg/sql/colexec/colexecbase:distinct_tmpl.go"],
outs = [target],
tags = ["no-remote-exec"],
cmd = """\
GO_REL_PATH=`dirname $(location @go_sdk//:bin/go)`
GO_ABS_PATH=`cd $$GO_REL_PATH && pwd`
# Set GOPATH to something to workaround https://github.com/golang/go/issues/43938
export PATH=$$GO_ABS_PATH:$$PATH
export HOME=$(GENDIR)
export GOPATH=/nonexist-gopath
export COCKROACH_INTERNAL_DISABLE_METAMORPHIC_TESTING=true
export GOROOT=
$(location :execgen) -template $(SRCS) -fmt=false pkg/sql/colexec/$@ > $@
$(location :goimports) -w $@
""",
exec_tools = [
"@go_sdk//:bin/go",
":execgen",
":goimports",
],
visibility = [":__pkg__", "//pkg/gen:__pkg__"],
)
# Generating the code for `default_cmp_proj_const_op.eg.go` requires special
# handling because the template lives in a different package.
def gen_default_cmp_proj_const_rule(name, target, visibility = ["//visibility:private"]):
native.genrule(
name = name,
srcs = ["//pkg/sql/colexec/colexecproj:default_cmp_proj_ops_tmpl.go"],
outs = [target],
cmd = """\
GO_REL_PATH=`dirname $(location @go_sdk//:bin/go)`
GO_ABS_PATH=`cd $$GO_REL_PATH && pwd`
# Set GOPATH to something to workaround https://github.com/golang/go/issues/43938
export PATH=$$GO_ABS_PATH:$$PATH
export HOME=$(GENDIR)
export GOPATH=/nonexist-gopath
export COCKROACH_INTERNAL_DISABLE_METAMORPHIC_TESTING=true
$(location :execgen) -template $(SRCS) -fmt=false pkg/sql/colexec/colexecprojconst/$@ > $@
$(location :goimports) -w $@
""",
exec_tools = [
"@go_sdk//:bin/go",
":execgen",
":goimports",
],
visibility = [":__pkg__", "//pkg/gen:__pkg__"],
)
| pkg/sql/colexec/COLEXEC.bzl | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0001741026935633272,
0.0001706714538158849,
0.00016339457943104208,
0.00017186609329655766,
0.000003747393975572777
] |
{
"id": 8,
"code_window": [
"\t\trequire.NoError(t, err, \"show transfer state failed\")\n",
"\t\tdefer rows.Close()\n",
"\n",
"\t\tresultColumns, err := rows.Columns()\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\trequire.Equal(t, []string{\n",
"\t\t\t\"error\",\n",
"\t\t\t\"session_state_base64\",\n",
"\t\t\t\"session_revival_token_base64\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tfieldDescriptions := rows.FieldDescriptions()\n",
"\t\tvar resultColumns []string\n",
"\t\tfor _, f := range fieldDescriptions {\n",
"\t\t\tresultColumns = append(resultColumns, f.Name)\n",
"\t\t}\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 100
} | # Code generated by generate-staticcheck; DO NOT EDIT.
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "sa4015",
srcs = ["analyzer.go"],
importpath = "github.com/cockroachdb/cockroach/build/bazelutil/staticcheckanalyzers/sa4015",
visibility = ["//visibility:public"],
deps = [
"//pkg/testutils/lint/passes/staticcheck",
"@co_honnef_go_tools//staticcheck",
"@org_golang_x_tools//go/analysis",
],
)
| build/bazelutil/staticcheckanalyzers/sa4015/BUILD.bazel | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.000175602370291017,
0.00017387085244990885,
0.0001721393346088007,
0.00017387085244990885,
0.0000017315178411081433
] |
{
"id": 8,
"code_window": [
"\t\trequire.NoError(t, err, \"show transfer state failed\")\n",
"\t\tdefer rows.Close()\n",
"\n",
"\t\tresultColumns, err := rows.Columns()\n",
"\t\trequire.NoError(t, err)\n",
"\n",
"\t\trequire.Equal(t, []string{\n",
"\t\t\t\"error\",\n",
"\t\t\t\"session_state_base64\",\n",
"\t\t\t\"session_revival_token_base64\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tfieldDescriptions := rows.FieldDescriptions()\n",
"\t\tvar resultColumns []string\n",
"\t\tfor _, f := range fieldDescriptions {\n",
"\t\t\tresultColumns = append(resultColumns, f.Name)\n",
"\t\t}\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 100
} | # This file contains tests for handling of duplicate impure projections. See
# #44865.
query I
WITH cte (a, b) AS (SELECT random(), random())
SELECT count(*) FROM cte WHERE a = b
----
0
query I
WITH cte (x, a, b) AS (SELECT x, random(), random() FROM (VALUES (1), (2), (3)) AS v(x))
SELECT count(*) FROM cte WHERE a = b
----
0
statement ok
CREATE TABLE kab (k INT PRIMARY KEY, a UUID, b UUID)
statement ok
INSERT INTO kab VALUES (1, gen_random_uuid(), gen_random_uuid())
statement ok
INSERT INTO kab VALUES (2, gen_random_uuid(), gen_random_uuid())
statement ok
INSERT INTO kab VALUES (3, gen_random_uuid(), gen_random_uuid()),
(4, gen_random_uuid(), gen_random_uuid()),
(5, gen_random_uuid(), gen_random_uuid()),
(6, gen_random_uuid(), gen_random_uuid())
query I
SELECT count(*) FROM kab WHERE a=b
----
0
statement ok
CREATE TABLE kabc (k INT PRIMARY KEY, a UUID, b UUID)
statement ok
INSERT INTO kabc VALUES (1, uuid_generate_v4(), uuid_generate_v4())
statement ok
INSERT INTO kabc VALUES (2, uuid_generate_v4(), uuid_generate_v4())
statement ok
INSERT INTO kabc VALUES (3, uuid_generate_v4(), uuid_generate_v4()),
(4, uuid_generate_v4(), uuid_generate_v4()),
(5, uuid_generate_v4(), uuid_generate_v4()),
(6, uuid_generate_v4(), uuid_generate_v4())
query I
SELECT count(*) FROM kabc WHERE a=b
----
0
statement ok
CREATE TABLE kabcd (
k INT PRIMARY KEY,
a UUID,
b UUID,
c UUID DEFAULT gen_random_uuid(),
d UUID DEFAULT gen_random_uuid(),
e UUID DEFAULT uuid_generate_v4(),
f UUID DEFAULT uuid_generate_v4()
)
statement ok
INSERT INTO kabcd VALUES (1, gen_random_uuid(), uuid_generate_v4())
statement ok
INSERT INTO kabcd VALUES (2, gen_random_uuid(), uuid_generate_v4())
statement ok
INSERT INTO kabcd VALUES (3, gen_random_uuid(), uuid_generate_v4()),
(4, gen_random_uuid(), uuid_generate_v4()),
(5, gen_random_uuid(), uuid_generate_v4()),
(6, gen_random_uuid(), uuid_generate_v4())
query I
SELECT count(*) FROM kabcd WHERE a=b OR a=c OR a=d OR a=e OR a=f
OR b=c OR b=d OR b=e OR b=f OR c=d OR c=e OR c=f OR d=e OR d=f OR e=f
----
0
| pkg/sql/logictest/testdata/logic_test/impure | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017402617959305644,
0.0001686346367932856,
0.00016063232033047825,
0.00017205941549036652,
0.00000505290654473356
] |
{
"id": 9,
"code_window": [
"\t\tq := pgURL.Query()\n",
"\t\tq.Add(\"application_name\", \"someotherapp\")\n",
"\t\tq.Add(\"crdb:session_revival_token_base64\", token)\n",
"\t\tpgURL.RawQuery = q.Encode()\n",
"\t\tconn, err := gosql.Open(\"postgres\", pgURL.String())\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tconn, err := pgx.Connect(ctx, pgURL.String())\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 138
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.9980820417404175,
0.4230150282382965,
0.00016443486674688756,
0.08083070069551468,
0.4617653489112854
] |
{
"id": 9,
"code_window": [
"\t\tq := pgURL.Query()\n",
"\t\tq.Add(\"application_name\", \"someotherapp\")\n",
"\t\tq.Add(\"crdb:session_revival_token_base64\", token)\n",
"\t\tpgURL.RawQuery = q.Encode()\n",
"\t\tconn, err := gosql.Open(\"postgres\", pgURL.String())\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tconn, err := pgx.Connect(ctx, pgURL.String())\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 138
} | /* setup */
CREATE DATABASE db;
CREATE TABLE db.public.tbl (i INT PRIMARY KEY);
----
...
+database {0 0 db} -> 104
+schema {104 0 public} -> 105
+object {104 105 tbl} -> 106
/* test */
ALTER TABLE db.public.tbl ADD COLUMN j INT UNIQUE DEFAULT CAST(date_part('year', now()) AS INT);
----
begin transaction #1
# begin StatementPhase
checking for feature: ALTER TABLE
increment telemetry for sql.schema.alter_table
increment telemetry for sql.schema.alter_table.add_column
increment telemetry for sql.schema.qualifcation.default_expr
increment telemetry for sql.schema.new_column_type.int8
write *eventpb.AlterTable to event log:
mutationId: 1
sql:
descriptorId: 106
statement: ALTER TABLE βΉdbβΊ.βΉpublicβΊ.βΉtblβΊ ADD COLUMN βΉjβΊ INT8 UNIQUE DEFAULT CAST(date_part(βΉ'year'βΊ,
now()) AS INT8)
tag: ALTER TABLE
user: root
tableName: db.public.tbl
## StatementPhase stage 1 of 1 with 10 MutationType ops
upsert descriptor #106
...
- columnIds:
- 1
+ - 2
columnNames:
- i
+ - j
+ defaultColumnId: 2
name: primary
formatVersion: 3
id: 106
modificationTime: {}
+ mutations:
+ - column:
+ defaultExpr: CAST(date_part('year':::STRING, now():::TIMESTAMPTZ) AS INT8)
+ id: 2
+ name: j
+ nullable: true
+ type:
+ family: IntFamily
+ oid: 20
+ width: 64
+ direction: ADD
+ mutationId: 1
+ state: DELETE_ONLY
+ - direction: ADD
+ index:
+ constraintId: 4
+ createdExplicitly: true
+ encodingType: 1
+ foreignKey: {}
+ geoConfig: {}
+ id: 4
+ interleave: {}
+ keyColumnDirections:
+ - ASC
+ keyColumnIds:
+ - 1
+ keyColumnNames:
+ - i
+ name: crdb_internal_index_4_name_placeholder
+ partitioning: {}
+ sharded: {}
+ storeColumnIds:
+ - 2
+ storeColumnNames:
+ - j
+ unique: true
+ version: 4
+ mutationId: 1
+ state: BACKFILLING
+ - direction: ADD
+ index:
+ constraintId: 5
+ createdExplicitly: true
+ encodingType: 1
+ foreignKey: {}
+ geoConfig: {}
+ id: 5
+ interleave: {}
+ keyColumnDirections:
+ - ASC
+ keyColumnIds:
+ - 1
+ keyColumnNames:
+ - i
+ name: crdb_internal_index_5_name_placeholder
+ partitioning: {}
+ sharded: {}
+ storeColumnIds:
+ - 2
+ storeColumnNames:
+ - j
+ unique: true
+ useDeletePreservingEncoding: true
+ version: 4
+ mutationId: 1
+ state: DELETE_ONLY
name: tbl
- nextColumnId: 2
- nextConstraintId: 2
+ nextColumnId: 3
+ nextConstraintId: 6
nextFamilyId: 1
- nextIndexId: 2
+ nextIndexId: 6
nextMutationId: 1
parentId: 104
...
time: {}
unexposedParentSchemaId: 105
- version: "1"
+ version: "2"
# end StatementPhase
# begin PreCommitPhase
## PreCommitPhase stage 1 of 2 with 1 MutationType op
undo all catalog changes within txn #1
persist all catalog changes to storage
## PreCommitPhase stage 2 of 2 with 14 MutationType ops
upsert descriptor #106
...
createAsOfTime:
wallTime: "1640995200000000000"
+ declarativeSchemaChangerState:
+ authorization:
+ userName: root
+ currentStatuses: <redacted>
+ jobId: "1"
+ nameMapping:
+ columns:
+ "1": i
+ "2": j
+ "4294967294": tableoid
+ "4294967295": crdb_internal_mvcc_timestamp
+ families:
+ "0": primary
+ id: 106
+ indexes:
+ "2": tbl_j_key
+ "4": tbl_pkey
+ name: tbl
+ relevantStatements:
+ - statement:
+ redactedStatement: ALTER TABLE βΉdbβΊ.βΉpublicβΊ.βΉtblβΊ ADD COLUMN βΉjβΊ INT8 UNIQUE
+ DEFAULT CAST(date_part(βΉ'year'βΊ, now()) AS INT8)
+ statement: ALTER TABLE db.public.tbl ADD COLUMN j INT8 UNIQUE DEFAULT CAST(date_part('year',
+ now()) AS INT8)
+ statementTag: ALTER TABLE
+ revertible: true
+ targetRanks: <redacted>
+ targets: <redacted>
families:
- columnIds:
- 1
+ - 2
columnNames:
- i
+ - j
+ defaultColumnId: 2
name: primary
formatVersion: 3
id: 106
modificationTime: {}
+ mutations:
+ - column:
+ defaultExpr: CAST(date_part('year':::STRING, now():::TIMESTAMPTZ) AS INT8)
+ id: 2
+ name: j
+ nullable: true
+ type:
+ family: IntFamily
+ oid: 20
+ width: 64
+ direction: ADD
+ mutationId: 1
+ state: DELETE_ONLY
+ - direction: ADD
+ index:
+ constraintId: 4
+ createdExplicitly: true
+ encodingType: 1
+ foreignKey: {}
+ geoConfig: {}
+ id: 4
+ interleave: {}
+ keyColumnDirections:
+ - ASC
+ keyColumnIds:
+ - 1
+ keyColumnNames:
+ - i
+ name: crdb_internal_index_4_name_placeholder
+ partitioning: {}
+ sharded: {}
+ storeColumnIds:
+ - 2
+ storeColumnNames:
+ - j
+ unique: true
+ version: 4
+ mutationId: 1
+ state: BACKFILLING
+ - direction: ADD
+ index:
+ constraintId: 5
+ createdExplicitly: true
+ encodingType: 1
+ foreignKey: {}
+ geoConfig: {}
+ id: 5
+ interleave: {}
+ keyColumnDirections:
+ - ASC
+ keyColumnIds:
+ - 1
+ keyColumnNames:
+ - i
+ name: crdb_internal_index_5_name_placeholder
+ partitioning: {}
+ sharded: {}
+ storeColumnIds:
+ - 2
+ storeColumnNames:
+ - j
+ unique: true
+ useDeletePreservingEncoding: true
+ version: 4
+ mutationId: 1
+ state: DELETE_ONLY
name: tbl
- nextColumnId: 2
- nextConstraintId: 2
+ nextColumnId: 3
+ nextConstraintId: 6
nextFamilyId: 1
- nextIndexId: 2
+ nextIndexId: 6
nextMutationId: 1
parentId: 104
...
time: {}
unexposedParentSchemaId: 105
- version: "1"
+ version: "2"
persist all catalog changes to storage
create job #1 (non-cancelable: false): "ALTER TABLE db.public.tbl ADD COLUMN j INT8 UNIQUE DEFAULT CAST(date_part('year', now()) AS INT8)"
descriptor IDs: [106]
# end PreCommitPhase
commit transaction #1
notified job registry to adopt jobs: [1]
# begin PostCommitPhase
begin transaction #2
commit transaction #2
begin transaction #3
## PostCommitPhase stage 1 of 15 with 4 MutationType ops
upsert descriptor #106
...
direction: ADD
mutationId: 1
- state: DELETE_ONLY
+ state: WRITE_ONLY
- direction: ADD
index:
...
version: 4
mutationId: 1
- state: DELETE_ONLY
+ state: WRITE_ONLY
name: tbl
nextColumnId: 3
...
time: {}
unexposedParentSchemaId: 105
- version: "2"
+ version: "3"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 2 of 15 with 1 BackfillType op pending"
commit transaction #3
begin transaction #4
## PostCommitPhase stage 2 of 15 with 1 BackfillType op
backfill indexes [4] from index #1 in table #106
commit transaction #4
begin transaction #5
## PostCommitPhase stage 3 of 15 with 3 MutationType ops
upsert descriptor #106
...
version: 4
mutationId: 1
- state: BACKFILLING
+ state: DELETE_ONLY
- direction: ADD
index:
...
time: {}
unexposedParentSchemaId: 105
- version: "3"
+ version: "4"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 4 of 15 with 1 MutationType op pending"
commit transaction #5
begin transaction #6
## PostCommitPhase stage 4 of 15 with 3 MutationType ops
upsert descriptor #106
...
version: 4
mutationId: 1
- state: DELETE_ONLY
+ state: MERGING
- direction: ADD
index:
...
time: {}
unexposedParentSchemaId: 105
- version: "4"
+ version: "5"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 5 of 15 with 1 BackfillType op pending"
commit transaction #6
begin transaction #7
## PostCommitPhase stage 5 of 15 with 1 BackfillType op
merge temporary indexes [5] into backfilled indexes [4] in table #106
commit transaction #7
begin transaction #8
## PostCommitPhase stage 6 of 15 with 4 MutationType ops
upsert descriptor #106
...
version: 4
mutationId: 1
- state: MERGING
- - direction: ADD
+ state: WRITE_ONLY
+ - direction: DROP
index:
constraintId: 5
...
version: 4
mutationId: 1
- state: WRITE_ONLY
+ state: DELETE_ONLY
name: tbl
nextColumnId: 3
...
time: {}
unexposedParentSchemaId: 105
- version: "5"
+ version: "6"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 7 of 15 with 1 ValidationType op pending"
commit transaction #8
begin transaction #9
## PostCommitPhase stage 7 of 15 with 1 ValidationType op
validate forward indexes [4] in table #106
commit transaction #9
begin transaction #10
## PostCommitPhase stage 8 of 15 with 15 MutationType ops
upsert descriptor #106
...
mutationId: 1
state: WRITE_ONLY
- - direction: ADD
+ - direction: DROP
index:
- constraintId: 4
+ constraintId: 5
createdExplicitly: true
encodingType: 1
foreignKey: {}
geoConfig: {}
- id: 4
+ id: 5
interleave: {}
keyColumnDirections:
...
keyColumnNames:
- i
- name: crdb_internal_index_4_name_placeholder
+ name: crdb_internal_index_5_name_placeholder
partitioning: {}
sharded: {}
...
- j
unique: true
+ useDeletePreservingEncoding: true
version: 4
mutationId: 1
- state: WRITE_ONLY
+ state: DELETE_ONLY
- direction: DROP
index:
- constraintId: 5
- createdExplicitly: true
+ constraintId: 1
+ createdAtNanos: "1640995200000000000"
encodingType: 1
foreignKey: {}
geoConfig: {}
- id: 5
+ id: 1
interleave: {}
keyColumnDirections:
...
keyColumnNames:
- i
- name: crdb_internal_index_5_name_placeholder
+ name: crdb_internal_index_1_name_placeholder
partitioning: {}
sharded: {}
- storeColumnIds:
+ unique: true
+ version: 4
+ mutationId: 1
+ state: WRITE_ONLY
+ - direction: ADD
+ index:
+ constraintId: 2
+ createdAtNanos: "1640998800000000000"
+ createdExplicitly: true
+ foreignKey: {}
+ geoConfig: {}
+ id: 2
+ interleave: {}
+ keyColumnDirections:
+ - ASC
+ keyColumnIds:
- 2
- storeColumnNames:
+ keyColumnNames:
- j
+ keySuffixColumnIds:
+ - 1
+ name: tbl_j_key
+ partitioning: {}
+ sharded: {}
+ storeColumnNames: []
unique: true
+ version: 4
+ mutationId: 1
+ state: BACKFILLING
+ - direction: ADD
+ index:
+ constraintId: 3
+ createdExplicitly: true
+ foreignKey: {}
+ geoConfig: {}
+ id: 3
+ interleave: {}
+ keyColumnDirections:
+ - ASC
+ keyColumnIds:
+ - 2
+ keyColumnNames:
+ - j
+ keySuffixColumnIds:
+ - 1
+ name: crdb_internal_index_3_name_placeholder
+ partitioning: {}
+ sharded: {}
+ storeColumnNames: []
+ unique: true
useDeletePreservingEncoding: true
version: 4
...
parentId: 104
primaryIndex:
- constraintId: 1
- createdAtNanos: "1640995200000000000"
+ constraintId: 4
+ createdExplicitly: true
encodingType: 1
foreignKey: {}
geoConfig: {}
- id: 1
+ id: 4
interleave: {}
keyColumnDirections:
...
partitioning: {}
sharded: {}
+ storeColumnIds:
+ - 2
+ storeColumnNames:
+ - j
unique: true
version: 4
...
time: {}
unexposedParentSchemaId: 105
- version: "6"
+ version: "7"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 9 of 15 with 1 MutationType op pending"
commit transaction #10
begin transaction #11
## PostCommitPhase stage 9 of 15 with 3 MutationType ops
upsert descriptor #106
...
version: 4
mutationId: 1
- state: DELETE_ONLY
+ state: WRITE_ONLY
name: tbl
nextColumnId: 3
...
time: {}
unexposedParentSchemaId: 105
- version: "7"
+ version: "8"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 10 of 15 with 1 BackfillType op pending"
commit transaction #11
begin transaction #12
## PostCommitPhase stage 10 of 15 with 1 BackfillType op
backfill indexes [2] from index #4 in table #106
commit transaction #12
begin transaction #13
## PostCommitPhase stage 11 of 15 with 3 MutationType ops
upsert descriptor #106
...
version: 4
mutationId: 1
- state: BACKFILLING
+ state: DELETE_ONLY
- direction: ADD
index:
...
time: {}
unexposedParentSchemaId: 105
- version: "8"
+ version: "9"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 12 of 15 with 1 MutationType op pending"
commit transaction #13
begin transaction #14
## PostCommitPhase stage 12 of 15 with 3 MutationType ops
upsert descriptor #106
...
version: 4
mutationId: 1
- state: DELETE_ONLY
+ state: MERGING
- direction: ADD
index:
...
time: {}
unexposedParentSchemaId: 105
- version: "9"
+ version: "10"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 13 of 15 with 1 BackfillType op pending"
commit transaction #14
begin transaction #15
## PostCommitPhase stage 13 of 15 with 1 BackfillType op
merge temporary indexes [3] into backfilled indexes [2] in table #106
commit transaction #15
begin transaction #16
## PostCommitPhase stage 14 of 15 with 4 MutationType ops
upsert descriptor #106
...
version: 4
mutationId: 1
- state: MERGING
- - direction: ADD
+ state: WRITE_ONLY
+ - direction: DROP
index:
constraintId: 3
...
version: 4
mutationId: 1
- state: WRITE_ONLY
+ state: DELETE_ONLY
name: tbl
nextColumnId: 3
...
time: {}
unexposedParentSchemaId: 105
- version: "10"
+ version: "11"
persist all catalog changes to storage
update progress of schema change job #1: "PostCommitPhase stage 15 of 15 with 1 ValidationType op pending"
commit transaction #16
begin transaction #17
## PostCommitPhase stage 15 of 15 with 1 ValidationType op
validate forward indexes [2] in table #106
commit transaction #17
begin transaction #18
## PostCommitNonRevertiblePhase stage 1 of 2 with 12 MutationType ops
upsert descriptor #106
...
oid: 20
width: 64
+ - defaultExpr: CAST(date_part('year':::STRING, now():::TIMESTAMPTZ) AS INT8)
+ id: 2
+ name: j
+ nullable: true
+ type:
+ family: IntFamily
+ oid: 20
+ width: 64
createAsOfTime:
wallTime: "1640995200000000000"
...
now()) AS INT8)
statementTag: ALTER TABLE
- revertible: true
targetRanks: <redacted>
targets: <redacted>
...
formatVersion: 3
id: 106
+ indexes:
+ - constraintId: 2
+ createdAtNanos: "1640998800000000000"
+ createdExplicitly: true
+ foreignKey: {}
+ geoConfig: {}
+ id: 2
+ interleave: {}
+ keyColumnDirections:
+ - ASC
+ keyColumnIds:
+ - 2
+ keyColumnNames:
+ - j
+ keySuffixColumnIds:
+ - 1
+ name: tbl_j_key
+ partitioning: {}
+ sharded: {}
+ storeColumnNames: []
+ unique: true
+ version: 4
modificationTime: {}
mutations:
- - column:
- defaultExpr: CAST(date_part('year':::STRING, now():::TIMESTAMPTZ) AS INT8)
- id: 2
- name: j
- nullable: true
- type:
- family: IntFamily
- oid: 20
- width: 64
- direction: ADD
- mutationId: 1
- state: WRITE_ONLY
- direction: DROP
index:
- constraintId: 5
- createdExplicitly: true
- encodingType: 1
- foreignKey: {}
- geoConfig: {}
- id: 5
- interleave: {}
- keyColumnDirections:
- - ASC
- keyColumnIds:
- - 1
- keyColumnNames:
- - i
- name: crdb_internal_index_5_name_placeholder
- partitioning: {}
- sharded: {}
- storeColumnIds:
- - 2
- storeColumnNames:
- - j
- unique: true
- useDeletePreservingEncoding: true
- version: 4
- mutationId: 1
- state: DELETE_ONLY
- - direction: DROP
- index:
constraintId: 1
createdAtNanos: "1640995200000000000"
...
version: 4
mutationId: 1
- state: WRITE_ONLY
- - direction: ADD
- index:
- constraintId: 2
- createdAtNanos: "1640998800000000000"
- createdExplicitly: true
- foreignKey: {}
- geoConfig: {}
- id: 2
- interleave: {}
- keyColumnDirections:
- - ASC
- keyColumnIds:
- - 2
- keyColumnNames:
- - j
- keySuffixColumnIds:
- - 1
- name: tbl_j_key
- partitioning: {}
- sharded: {}
- storeColumnNames: []
- unique: true
- version: 4
- mutationId: 1
- state: WRITE_ONLY
- - direction: DROP
- index:
- constraintId: 3
- createdExplicitly: true
- foreignKey: {}
- geoConfig: {}
- id: 3
- interleave: {}
- keyColumnDirections:
- - ASC
- keyColumnIds:
- - 2
- keyColumnNames:
- - j
- keySuffixColumnIds:
- - 1
- name: crdb_internal_index_3_name_placeholder
- partitioning: {}
- sharded: {}
- storeColumnNames: []
- unique: true
- useDeletePreservingEncoding: true
- version: 4
- mutationId: 1
state: DELETE_ONLY
name: tbl
...
time: {}
unexposedParentSchemaId: 105
- version: "11"
+ version: "12"
persist all catalog changes to storage
adding table for stats refresh: 106
update progress of schema change job #1: "PostCommitNonRevertiblePhase stage 2 of 2 with 4 MutationType ops pending"
set schema change job #1 to non-cancellable
commit transaction #18
begin transaction #19
## PostCommitNonRevertiblePhase stage 2 of 2 with 6 MutationType ops
upsert descriptor #106
...
createAsOfTime:
wallTime: "1640995200000000000"
- declarativeSchemaChangerState:
- authorization:
- userName: root
- currentStatuses: <redacted>
- jobId: "1"
- nameMapping:
- columns:
- "1": i
- "2": j
- "4294967294": tableoid
- "4294967295": crdb_internal_mvcc_timestamp
- families:
- "0": primary
- id: 106
- indexes:
- "2": tbl_j_key
- "4": tbl_pkey
- name: tbl
- relevantStatements:
- - statement:
- redactedStatement: ALTER TABLE βΉdbβΊ.βΉpublicβΊ.βΉtblβΊ ADD COLUMN βΉjβΊ INT8 UNIQUE
- DEFAULT CAST(date_part(βΉ'year'βΊ, now()) AS INT8)
- statement: ALTER TABLE db.public.tbl ADD COLUMN j INT8 UNIQUE DEFAULT CAST(date_part('year',
- now()) AS INT8)
- statementTag: ALTER TABLE
- targetRanks: <redacted>
- targets: <redacted>
families:
- columnIds:
...
version: 4
modificationTime: {}
- mutations:
- - direction: DROP
- index:
- constraintId: 1
- createdAtNanos: "1640995200000000000"
- encodingType: 1
- foreignKey: {}
- geoConfig: {}
- id: 1
- interleave: {}
- keyColumnDirections:
- - ASC
- keyColumnIds:
- - 1
- keyColumnNames:
- - i
- name: crdb_internal_index_1_name_placeholder
- partitioning: {}
- sharded: {}
- unique: true
- version: 4
- mutationId: 1
- state: DELETE_ONLY
+ mutations: []
name: tbl
nextColumnId: 3
...
time: {}
unexposedParentSchemaId: 105
- version: "12"
+ version: "13"
persist all catalog changes to storage
create job #2 (non-cancelable: true): "GC for ALTER TABLE db.public.tbl ADD COLUMN j INT8 UNIQUE DEFAULT CAST(date_part('year', now()) AS INT8)"
descriptor IDs: [106]
update progress of schema change job #1: "all stages completed"
set schema change job #1 to non-cancellable
updated schema change job #1 descriptor IDs to []
write *eventpb.FinishSchemaChange to event log:
sc:
descriptorId: 106
commit transaction #19
notified job registry to adopt jobs: [2]
# end PostCommitPhase
| pkg/sql/schemachanger/testdata/end_to_end/add_column_default_unique/add_column_default_unique.side_effects | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00021267349075060338,
0.0001736773265292868,
0.0001618492096895352,
0.00017420906806364655,
0.000005537787728826515
] |
{
"id": 9,
"code_window": [
"\t\tq := pgURL.Query()\n",
"\t\tq.Add(\"application_name\", \"someotherapp\")\n",
"\t\tq.Add(\"crdb:session_revival_token_base64\", token)\n",
"\t\tpgURL.RawQuery = q.Encode()\n",
"\t\tconn, err := gosql.Open(\"postgres\", pgURL.String())\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tconn, err := pgx.Connect(ctx, pgURL.String())\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 138
} | statement ok
CREATE TABLE a (k STRING PRIMARY KEY, v STRING)
statement ok
INSERT INTO a VALUES ('a', '1'), ('b', '2'), ('c', '3')
statement ok
CREATE VIEW b AS SELECT k,v from a
statement ok
CREATE VIEW c AS SELECT k,v from b
query TTTTIT rowsort
SHOW TABLES FROM test
----
public a table root 0 NULL
public b view root 0 NULL
public c view root 0 NULL
statement error cannot drop relation "a" because view "b" depends on it
DROP TABLE a
statement error pgcode 42809 "b" is not a table
DROP TABLE b
statement error cannot drop relation "b" because view "c" depends on it
DROP VIEW b
statement ok
CREATE VIEW d AS SELECT k,v FROM a
statement ok
CREATE VIEW diamond AS SELECT count(*) FROM b AS b JOIN d AS d ON b.k = d.k
statement error cannot drop relation "d" because view "diamond" depends on it
DROP VIEW d
statement ok
GRANT ALL ON d TO testuser
query TTTTIT rowsort
SHOW TABLES FROM test
----
public a table root 0 NULL
public b view root 0 NULL
public c view root 0 NULL
public d view root 0 NULL
public diamond view root 0 NULL
user testuser
statement error user testuser does not have DROP privilege on relation diamond
DROP VIEW diamond
statement error cannot drop relation "d" because view "diamond" depends on it
DROP VIEW d
user root
statement ok
CREATE VIEW testuser1 AS SELECT k,v FROM a
statement ok
CREATE VIEW testuser2 AS SELECT k,v FROM testuser1
statement ok
CREATE VIEW testuser3 AS SELECT k,v FROM testuser2
statement ok
GRANT ALL ON testuser1 to testuser
statement ok
GRANT ALL ON testuser2 to testuser
statement ok
GRANT ALL ON testuser3 to testuser
query TTTTIT rowsort
SHOW TABLES FROM test
----
public a table root 0 NULL
public b view root 0 NULL
public c view root 0 NULL
public d view root 0 NULL
public diamond view root 0 NULL
public testuser1 view root 0 NULL
public testuser2 view root 0 NULL
public testuser3 view root 0 NULL
# Revoke needed for a meaningful test for testuser.
statement ok
REVOKE CONNECT ON DATABASE test FROM public
user testuser
statement ok
DROP VIEW testuser3
query TTTTIT rowsort
SHOW TABLES FROM test
----
public d view root 0 NULL
public testuser1 view root 0 NULL
public testuser2 view root 0 NULL
statement error cannot drop relation "testuser1" because view "testuser2" depends on it
DROP VIEW testuser1
statement error cannot drop relation "testuser1" because view "testuser2" depends on it
DROP VIEW testuser1 RESTRICT
statement ok
DROP VIEW testuser1 CASCADE
query TTTTIT
SHOW TABLES FROM test
----
public d view root 0 NULL
statement error pgcode 42P01 relation "testuser2" does not exist
DROP VIEW testuser2
user root
statement ok
GRANT ALL ON a to testuser
statement ok
GRANT ALL ON b to testuser
statement ok
GRANT ALL ON c to testuser
statement ok
GRANT ALL ON d to testuser
user testuser
statement error user testuser does not have DROP privilege on relation diamond
DROP TABLE a CASCADE
user root
statement ok
DROP TABLE a CASCADE
query TTTTIT
SHOW TABLES FROM test
----
statement ok
CREATE VIEW x AS VALUES (1, 2), (3, 4)
statement ok
CREATE VIEW y AS SELECT column1, column2 FROM x
statement error cannot drop relation "x" because view "y" depends on it
DROP VIEW x
statement ok
DROP VIEW x, y
statement ok
CREATE VIEW x AS VALUES (1, 2), (3, 4)
statement ok
CREATE VIEW y AS SELECT column1, column2 FROM x
statement error cannot drop relation "x" because view "y" depends on it
DROP VIEW x
statement ok
DROP VIEW y, x
# Ensure that dropping a database works even when views get referred to more=
# than once. See #15953 for more details.
statement ok
CREATE DATABASE a
statement ok
SET DATABASE=a
statement ok
CREATE TABLE a (a int);
statement ok
CREATE TABLE b (b int);
statement ok
CREATE VIEW v AS SELECT a.a, b.b FROM a CROSS JOIN b
statement ok
CREATE VIEW u AS SELECT a FROM a UNION SELECT a FROM a
statement ok
DROP DATABASE a CASCADE
| pkg/sql/logictest/testdata/logic_test/drop_view | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0002587742928881198,
0.0001751648960635066,
0.00016172611503861845,
0.00016948750999290496,
0.000020609062630683184
] |
{
"id": 9,
"code_window": [
"\t\tq := pgURL.Query()\n",
"\t\tq.Add(\"application_name\", \"someotherapp\")\n",
"\t\tq.Add(\"crdb:session_revival_token_base64\", token)\n",
"\t\tpgURL.RawQuery = q.Encode()\n",
"\t\tconn, err := gosql.Open(\"postgres\", pgURL.String())\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tconn, err := pgx.Connect(ctx, pgURL.String())\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 138
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlproxyccl
import (
"bytes"
"context"
"fmt"
"io"
"math/rand"
"net"
"testing"
"testing/iotest"
"time"
"github.com/cockroachdb/cockroach/pkg/ccl/sqlproxyccl/interceptor"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirebase"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/jackc/pgproto3/v2"
"github.com/stretchr/testify/require"
)
func TestForward(t *testing.T) {
defer leaktest.AfterTest(t)()
bgCtx := context.Background()
t.Run("closed_when_processors_error", func(t *testing.T) {
p1, p2 := net.Pipe()
f := newForwarder(bgCtx, nil /* connector */, nil /* metrics */, nil /* timeSource */)
defer f.Close()
err := f.run(p1, p2)
require.NoError(t, err)
func() {
f.mu.Lock()
defer f.mu.Unlock()
require.True(t, f.mu.isInitialized)
}()
// Close the connection right away to simulate processor error.
p1.Close()
// We have to wait for the goroutine to run. Once the forwarder stops,
// we're good.
testutils.SucceedsSoon(t, func() error {
if f.ctx.Err() != nil {
return nil
}
return errors.New("forwarder is still running")
})
})
t.Run("client_to_server", func(t *testing.T) {
ctx, cancel := context.WithTimeout(bgCtx, 5*time.Second)
defer cancel()
// We don't close client and server here since we have no control
// over those. The rest are handled by the forwarder.
clientProxy, client := net.Pipe()
serverProxy, server := net.Pipe()
// Use a custom time source for testing.
t0 := time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)
timeSource := timeutil.NewManualTime(t0)
f := newForwarder(ctx, nil /* connector */, nil /* metrics */, timeSource)
defer f.Close()
err := f.run(clientProxy, serverProxy)
require.NoError(t, err)
require.Nil(t, f.ctx.Err())
require.False(t, f.IsIdle())
func() {
f.mu.Lock()
defer f.mu.Unlock()
require.True(t, f.mu.isInitialized)
}()
f.mu.Lock()
requestProc := f.mu.request
f.mu.Unlock()
initialClock := requestProc.logicalClockFn()
barrierStart, barrierEnd := make(chan struct{}), make(chan struct{})
requestProc.testingKnobs.beforeForwardMsg = func() {
// Use two barriers here to ensure that we don't get a race when
// asserting the last message.
<-barrierStart
<-barrierEnd
}
requestProc.mu.Lock()
require.True(t, requestProc.mu.resumed)
requestProc.mu.Unlock()
// Client writes some pgwire messages.
sendEventCh := make(chan struct{}, 1)
errChan := make(chan error, 1)
go func() {
<-sendEventCh
if _, err := client.Write((&pgproto3.Query{
String: "SELECT 1",
}).Encode(nil)); err != nil {
errChan <- err
return
}
<-sendEventCh
if _, err := client.Write((&pgproto3.Execute{
Portal: "foobar",
MaxRows: 42,
}).Encode(nil)); err != nil {
errChan <- err
return
}
<-sendEventCh
if _, err := client.Write((&pgproto3.Close{
ObjectType: 'P',
}).Encode(nil)); err != nil {
errChan <- err
return
}
}()
// Server should receive messages in order.
backend := pgproto3.NewBackend(pgproto3.NewChunkReader(server), server)
// Send SELECT 1. Before we send, advance the timesource, and forwarder
// should be idle.
timeSource.Advance(idleTimeout)
require.True(t, f.IsIdle())
sendEventCh <- struct{}{}
barrierStart <- struct{}{}
requestProc.mu.Lock()
require.Equal(t, byte(pgwirebase.ClientMsgSimpleQuery), requestProc.mu.lastMessageType)
require.Equal(t, initialClock+1, requestProc.mu.lastMessageTransferredAt)
requestProc.mu.Unlock()
require.False(t, f.IsIdle())
barrierEnd <- struct{}{}
// Server should receive SELECT 1.
msg, err := backend.Receive()
require.NoError(t, err)
m1, ok := msg.(*pgproto3.Query)
require.True(t, ok)
require.Equal(t, "SELECT 1", m1.String)
// Send Execute message. Before we send, advance the timesource, and
// forwarder should be idle.
timeSource.Advance(idleTimeout)
require.True(t, f.IsIdle())
sendEventCh <- struct{}{}
barrierStart <- struct{}{}
requestProc.mu.Lock()
require.Equal(t, byte(pgwirebase.ClientMsgExecute), requestProc.mu.lastMessageType)
require.Equal(t, initialClock+2, requestProc.mu.lastMessageTransferredAt)
requestProc.mu.Unlock()
require.False(t, f.IsIdle())
barrierEnd <- struct{}{}
// Server receives Execute.
msg, err = backend.Receive()
require.NoError(t, err)
m2, ok := msg.(*pgproto3.Execute)
require.True(t, ok)
require.Equal(t, "foobar", m2.Portal)
require.Equal(t, uint32(42), m2.MaxRows)
// Send Close message. Before we send, advance the timesource, and
// forwarder should be idle.
timeSource.Advance(idleTimeout)
require.True(t, f.IsIdle())
sendEventCh <- struct{}{}
barrierStart <- struct{}{}
requestProc.mu.Lock()
require.Equal(t, byte(pgwirebase.ClientMsgClose), requestProc.mu.lastMessageType)
require.Equal(t, initialClock+3, requestProc.mu.lastMessageTransferredAt)
requestProc.mu.Unlock()
require.False(t, f.IsIdle())
barrierEnd <- struct{}{}
// Server receives Close.
msg, err = backend.Receive()
require.NoError(t, err)
m3, ok := msg.(*pgproto3.Close)
require.True(t, ok)
require.Equal(t, byte('P'), m3.ObjectType)
select {
case err = <-errChan:
t.Fatalf("require no error, but got %v", err)
default:
}
})
t.Run("server_to_client", func(t *testing.T) {
ctx, cancel := context.WithTimeout(bgCtx, 5*time.Second)
defer cancel()
// We don't close client and server here since we have no control
// over those. The rest are handled by the forwarder.
clientProxy, client := net.Pipe()
serverProxy, server := net.Pipe()
// Use a custom time source for testing.
t0 := time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)
timeSource := timeutil.NewManualTime(t0)
f := newForwarder(ctx, nil /* connector */, nil /* metrics */, timeSource)
defer f.Close()
err := f.run(clientProxy, serverProxy)
require.NoError(t, err)
require.Nil(t, f.ctx.Err())
require.False(t, f.IsIdle())
func() {
f.mu.Lock()
defer f.mu.Unlock()
require.True(t, f.mu.isInitialized)
}()
f.mu.Lock()
responseProc := f.mu.response
f.mu.Unlock()
initialClock := responseProc.logicalClockFn()
barrierStart, barrierEnd := make(chan struct{}), make(chan struct{})
responseProc.testingKnobs.beforeForwardMsg = func() {
// Use two barriers here to ensure that we don't get a race when
// asserting the last message.
<-barrierStart
<-barrierEnd
}
responseProc.mu.Lock()
require.True(t, responseProc.mu.resumed)
responseProc.mu.Unlock()
// Server writes some pgwire messages.
recvEventCh := make(chan struct{}, 1)
errChan := make(chan error, 1)
go func() {
<-recvEventCh
if _, err := server.Write((&pgproto3.ErrorResponse{
Code: "100",
Message: "foobarbaz",
}).Encode(nil)); err != nil {
errChan <- err
return
}
<-recvEventCh
if _, err := server.Write((&pgproto3.ReadyForQuery{
TxStatus: 'I',
}).Encode(nil)); err != nil {
errChan <- err
return
}
}()
// Client should receive messages in order.
frontend := pgproto3.NewFrontend(pgproto3.NewChunkReader(client), client)
// Receive an ErrorResponse. Before we receive, advance the timesource,
// and forwarder should be idle.
timeSource.Advance(idleTimeout)
require.True(t, f.IsIdle())
recvEventCh <- struct{}{}
barrierStart <- struct{}{}
responseProc.mu.Lock()
require.Equal(t, byte(pgwirebase.ServerMsgErrorResponse), responseProc.mu.lastMessageType)
require.Equal(t, initialClock+1, responseProc.mu.lastMessageTransferredAt)
responseProc.mu.Unlock()
require.False(t, f.IsIdle())
barrierEnd <- struct{}{}
// Client receives ErrorResponse.
msg, err := frontend.Receive()
require.NoError(t, err)
m1, ok := msg.(*pgproto3.ErrorResponse)
require.True(t, ok)
require.Equal(t, "100", m1.Code)
require.Equal(t, "foobarbaz", m1.Message)
// Receive a ReadyForQuery. Before we receive, advance the timesource,
// and forwarder should be idle.
timeSource.Advance(idleTimeout)
require.True(t, f.IsIdle())
recvEventCh <- struct{}{}
barrierStart <- struct{}{}
responseProc.mu.Lock()
require.Equal(t, byte(pgwirebase.ServerMsgReady), responseProc.mu.lastMessageType)
require.Equal(t, initialClock+2, responseProc.mu.lastMessageTransferredAt)
responseProc.mu.Unlock()
require.False(t, f.IsIdle())
barrierEnd <- struct{}{}
// Client receives ReadyForQuery.
msg, err = frontend.Receive()
require.NoError(t, err)
m2, ok := msg.(*pgproto3.ReadyForQuery)
require.True(t, ok)
require.Equal(t, byte('I'), m2.TxStatus)
select {
case err = <-errChan:
t.Fatalf("require no error, but got %v", err)
default:
}
})
}
func TestForwarder_Context(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := logtags.AddTag(context.Background(), "foo", "bar")
f := newForwarder(ctx, nil /* connector */, nil /* metrics */, nil /* timeSource */)
defer f.Close()
// Check that the right context was returned.
b := logtags.FromContext(f.Context())
require.NotNil(t, b)
require.Equal(t, "foo=bar", b.String())
}
func TestForwarder_Close(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
for _, withRun := range []bool{true, false} {
t.Run(fmt.Sprintf("withRun=%t", withRun), func(t *testing.T) {
f := newForwarder(ctx, nil /* connector */, nil /* metrics */, nil /* timeSource */)
defer f.Close()
if withRun {
p1, p2 := net.Pipe()
err := f.run(p1, p2)
require.NoError(t, err)
}
require.Nil(t, f.ctx.Err())
f.Close()
require.EqualError(t, f.ctx.Err(), context.Canceled.Error())
})
}
}
func TestForwarder_tryReportError(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
p1, p2 := net.Pipe()
f := newForwarder(ctx, nil /* connector */, nil /* metrics */, nil /* timeSource */)
defer f.Close()
err := f.run(p1, p2)
require.NoError(t, err)
select {
case err := <-f.errCh:
t.Fatalf("expected no error, but got %v", err)
default:
// We are good.
}
// Report an error.
f.tryReportError(errors.New("foo"))
select {
case err := <-f.errCh:
require.EqualError(t, err, "foo")
default:
t.Fatal("expected error, but got none")
}
// Forwarder should be closed.
_, err = p1.Write([]byte("foobarbaz"))
require.Regexp(t, "closed pipe", err)
require.EqualError(t, f.ctx.Err(), context.Canceled.Error())
}
func TestForwarder_replaceServerConn(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
clientProxy, client := net.Pipe()
serverProxy, server := net.Pipe()
f := newForwarder(ctx, nil /* connector */, nil /* metrics */, nil /* timeSource */)
defer f.Close()
err := f.run(clientProxy, serverProxy)
require.NoError(t, err)
c, s := f.getConns()
require.Equal(t, clientProxy, c.Conn)
require.Equal(t, serverProxy, s.Conn)
req, res := f.getProcessors()
require.NoError(t, req.suspend(ctx))
require.NoError(t, res.suspend(ctx))
newServerProxy, newServer := net.Pipe()
f.replaceServerConn(interceptor.NewPGConn(newServerProxy))
require.NoError(t, f.resumeProcessors())
// Check that we can receive messages from newServer.
q := (&pgproto3.ReadyForQuery{TxStatus: 'I'}).Encode(nil)
go func() {
_, _ = newServer.Write(q)
}()
frontend := interceptor.NewFrontendConn(client)
msg, err := frontend.ReadMsg()
require.NoError(t, err)
rmsg, ok := msg.(*pgproto3.ReadyForQuery)
require.True(t, ok)
require.Equal(t, byte('I'), rmsg.TxStatus)
// Check that old connection was closed.
_, err = server.Write([]byte("foobarbaz"))
require.Regexp(t, "closed pipe", err)
}
func TestWrapClientToServerError(t *testing.T) {
defer leaktest.AfterTest(t)()
for _, tc := range []struct {
input error
output error
}{
// Nil errors.
{nil, nil},
{context.Canceled, nil},
{context.DeadlineExceeded, nil},
{errors.Mark(errors.New("foo"), context.Canceled), nil},
{errors.Wrap(context.DeadlineExceeded, "foo"), nil},
// Forwarding errors.
{errors.New("foo"), withCode(errors.New(
"unexpected error copying from client to target server: foo"),
codeClientDisconnected,
)},
{errors.Mark(errors.New("some write error"), errClientWrite),
withCode(errors.New(
"unable to write to client: some write error"),
codeClientWriteFailed,
)},
} {
err := wrapClientToServerError(tc.input)
if tc.output == nil {
require.NoError(t, err)
} else {
require.EqualError(t, err, tc.output.Error())
}
}
}
func TestWrapServerToClientError(t *testing.T) {
defer leaktest.AfterTest(t)()
for _, tc := range []struct {
input error
output error
}{
// Nil errors.
{nil, nil},
{context.Canceled, nil},
{context.DeadlineExceeded, nil},
{errors.Mark(errors.New("foo"), context.Canceled), nil},
{errors.Wrap(context.DeadlineExceeded, "foo"), nil},
// Forwarding errors.
{errors.New("foo"), withCode(errors.New(
"unexpected error copying from target server to client: foo"),
codeBackendDisconnected,
)},
{errors.Mark(errors.New("some read error"), errServerRead),
withCode(errors.New(
"unable to read from sql server: some read error"),
codeBackendReadFailed,
)},
} {
err := wrapServerToClientError(tc.input)
if tc.output == nil {
require.NoError(t, err)
} else {
require.EqualError(t, err, tc.output.Error())
}
}
}
func TestMakeLogicalClockFn(t *testing.T) {
defer leaktest.AfterTest(t)()
clockFn := makeLogicalClockFn()
require.Equal(t, uint64(1), clockFn())
require.Equal(t, uint64(2), clockFn())
require.Equal(t, uint64(3), clockFn())
const concurrency = 200
for i := 0; i < concurrency; i++ {
go clockFn()
}
// Allow some time for the goroutines to complete.
expected := uint64(3 + concurrency)
testutils.SucceedsSoon(t, func() error {
expected++
clock := clockFn()
if expected == clock {
return nil
}
return errors.Newf("require clock=%d, but got %d", expected, clock)
})
}
func TestSuspendResumeProcessor(t *testing.T) {
defer leaktest.AfterTest(t)()
t.Run("context_cancelled", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
clientProxy, serverProxy := net.Pipe()
defer clientProxy.Close()
defer serverProxy.Close()
p := newProcessor(
makeLogicalClockFn(),
interceptor.NewPGConn(clientProxy),
interceptor.NewPGConn(serverProxy),
)
require.EqualError(t, p.resume(ctx), context.Canceled.Error())
p.mu.Lock()
require.True(t, p.mu.closed)
p.mu.Unlock()
// Set resumed to true to simulate suspend loop.
p.mu.Lock()
p.mu.resumed = true
p.mu.Unlock()
require.EqualError(t, p.suspend(ctx), errProcessorClosed.Error())
})
t.Run("wait_for_resumed", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
clientProxy, serverProxy := net.Pipe()
defer clientProxy.Close()
defer serverProxy.Close()
p := newProcessor(
makeLogicalClockFn(),
interceptor.NewPGConn(clientProxy),
interceptor.NewPGConn(serverProxy),
)
errCh := make(chan error)
go func() {
errCh <- p.waitResumed(ctx)
}()
select {
case <-errCh:
t.Fatal("expected not resumed")
default:
// We're good.
}
go func() { _ = p.resume(ctx) }()
var lastErr error
require.Eventually(t, func() bool {
select {
case lastErr = <-errCh:
return true
default:
return false
}
}, 10*time.Second, 100*time.Millisecond)
require.NoError(t, lastErr)
})
// This tests that resume() and suspend() can be called multiple times.
// As an aside, we also check that we can suspend when blocked on PeekMsg
// because there are no messages.
t.Run("already_resumed_or_suspended", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
clientProxy, serverProxy := net.Pipe()
defer clientProxy.Close()
defer serverProxy.Close()
p := newProcessor(
makeLogicalClockFn(),
interceptor.NewPGConn(clientProxy),
interceptor.NewPGConn(serverProxy),
)
// Ensure that two resume calls will return right away.
errCh := make(chan error, 2)
go func() { errCh <- p.resume(ctx) }()
go func() { errCh <- p.resume(ctx) }()
go func() { errCh <- p.resume(ctx) }()
err := <-errCh
require.NoError(t, err)
err = <-errCh
require.NoError(t, err)
// Suspend the last goroutine.
err = p.waitResumed(ctx)
require.NoError(t, err)
err = p.suspend(ctx)
require.NoError(t, err)
// Validate suspension.
err = <-errCh
require.NoError(t, err)
p.mu.Lock()
require.False(t, p.mu.resumed)
require.False(t, p.mu.inPeek)
require.False(t, p.mu.suspendReq)
p.mu.Unlock()
// Suspend a second time.
err = p.suspend(ctx)
require.NoError(t, err)
// If already suspended, do nothing.
p.mu.Lock()
require.False(t, p.mu.resumed)
require.False(t, p.mu.inPeek)
require.False(t, p.mu.suspendReq)
p.mu.Unlock()
})
// Multiple suspend/resumes calls should not cause issues. ForwardMsg should
// not be interrupted.
t.Run("multiple_resume_suspend_race", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
clientProxy, client := net.Pipe()
defer clientProxy.Close()
defer client.Close()
serverProxy, server := net.Pipe()
defer serverProxy.Close()
defer server.Close()
p := newProcessor(
makeLogicalClockFn(),
interceptor.NewPGConn(clientProxy),
interceptor.NewPGConn(serverProxy),
)
const (
queryCount = 100
concurrency = 200
)
// Client writes messages to be forwarded.
buf := new(bytes.Buffer)
q := (&pgproto3.Query{String: "SELECT 1"}).Encode(nil)
for i := 0; i < queryCount; i++ {
// Alternate between SELECT 1 and 2 to ensure correctness.
if i%2 == 0 {
q[12] = '1'
} else {
q[12] = '2'
}
_, _ = buf.Write(q)
}
go func() {
// Simulate slow writes by writing byte by byte.
_, _ = io.Copy(client, iotest.OneByteReader(buf))
}()
// Server reads messages that are forwarded.
msgCh := make(chan pgproto3.FrontendMessage, queryCount)
go func() {
backend := interceptor.NewBackendConn(server)
for {
msg, err := backend.ReadMsg()
if err != nil {
return
}
msgCh <- msg
}
}()
// Start the suspend/resume calls.
errResumeCh := make(chan error, concurrency)
errSuspendCh := make(chan error, concurrency)
for i := 1; i <= concurrency; i++ {
go func(p *processor, i int) {
time.Sleep(jitteredInterval(time.Duration((i*2)+500) * time.Millisecond))
errResumeCh <- p.resume(ctx)
}(p, i)
go func(p *processor, i int) {
time.Sleep(jitteredInterval(time.Duration((i*2)+500) * time.Millisecond))
errSuspendCh <- p.suspend(ctx)
}(p, i)
}
// Wait until all resume calls except 1 have returned.
for i := 0; i < concurrency-1; i++ {
err := <-errResumeCh
require.NoError(t, err)
}
// Wait until the last one returns. We can guarantee that this is for
// the last resume because all the other resume calls have returned.
var lastErr error
require.Eventually(t, func() bool {
select {
case lastErr = <-errResumeCh:
return true
default:
_ = p.suspend(ctx)
return false
}
}, 10*time.Second, 100*time.Millisecond)
// If error is not nil, it has to be an already resumed error. This
// would happen if suspend was the last to be called within all those
// suspend/resume calls.
if lastErr != nil {
require.EqualError(t, lastErr, errProcessorResumed.Error())
}
// Wait until all initial suspend calls have returned.
for i := 0; i < concurrency; i++ {
err := <-errSuspendCh
require.NoError(t, err)
}
// At this point, we know that all pending resume and suspend calls
// have returned. Run the final resumption to make sure all packets
// have been forwarded.
go func(p *processor) { _ = p.resume(ctx) }(p)
err := p.waitResumed(ctx)
require.NoError(t, err)
// Now read all the messages on the server for correctness.
for i := 0; i < queryCount; i++ {
msg := <-msgCh
q := msg.(*pgproto3.Query)
expectedStr := "SELECT 1"
if i%2 == 1 {
expectedStr = "SELECT 2"
}
require.Equal(t, expectedStr, q.String)
}
// Suspend the final goroutine.
err = p.suspend(ctx)
require.NoError(t, err)
})
}
// jitteredInterval returns a randomly jittered (+/-50%) duration from interval.
func jitteredInterval(interval time.Duration) time.Duration {
return time.Duration(float64(interval) * (0.5 + 0.5*rand.Float64()))
}
| pkg/ccl/sqlproxyccl/forwarder_test.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.7287381291389465,
0.009692437015473843,
0.0001612200285308063,
0.0001743081520544365,
0.08142144978046417
] |
{
"id": 10,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer conn.Close()\n",
"\n",
"\t\tvar appName string\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tdefer func() { _ = conn.Close(ctx) }()\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 140
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.9970701932907104,
0.100779227912426,
0.00016600902017671615,
0.001952949445694685,
0.2851638197898865
] |
{
"id": 10,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer conn.Close()\n",
"\n",
"\t\tvar appName string\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tdefer func() { _ = conn.Close(ctx) }()\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 140
} | // Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sql
import (
"context"
"sync"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/rowcontainer"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/errors"
)
var updateNodePool = sync.Pool{
New: func() interface{} {
return &updateNode{}
},
}
type updateNode struct {
source planNode
// columns is set if this UPDATE is returning any rows, to be
// consumed by a renderNode upstream. This occurs when there is a
// RETURNING clause with some scalar expressions.
columns colinfo.ResultColumns
run updateRun
}
var _ mutationPlanNode = &updateNode{}
// updateRun contains the run-time state of updateNode during local execution.
type updateRun struct {
tu tableUpdater
rowsNeeded bool
checkOrds checkSet
// done informs a new call to BatchedNext() that the previous call to
// BatchedNext() has completed the work already.
done bool
// traceKV caches the current KV tracing flag.
traceKV bool
// computedCols are the columns that need to be (re-)computed as
// the result of updating some of the columns in updateCols.
computedCols []catalog.Column
// computeExprs are the expressions to evaluate to re-compute the
// columns in computedCols.
computeExprs []tree.TypedExpr
// iVarContainerForComputedCols is used as a temporary buffer that
// holds the updated values for every column in the source, to
// serve as input for indexed vars contained in the computeExprs.
iVarContainerForComputedCols schemaexpr.RowIndexedVarContainer
// sourceSlots is the helper that maps RHS expressions to LHS targets.
// This is necessary because there may be fewer RHS expressions than
// LHS targets. For example, SET (a, b) = (SELECT 1,2) has:
// - 2 targets (a, b)
// - 1 source slot, the subquery (SELECT 1, 2).
// Each call to extractValues() on a sourceSlot will return 1 or more
// datums suitable for assignments. In the example above, the
// method would return 2 values.
sourceSlots []sourceSlot
// updateValues will hold the new values for every column
// mentioned in the LHS of the SET expressions, in the
// order specified by those SET expressions (thus potentially
// a different order than the source).
updateValues tree.Datums
// During the update, the expressions provided by the source plan
// contain the columns that are being assigned in the order
// specified by the table descriptor.
//
// For example, with UPDATE kv SET v=3, k=2, the source plan will
// provide the values in the order k, v (assuming this is the order
// the columns are defined in kv's descriptor).
//
// Then during the update, the columns are updated in the order of
// the setExprs (or, equivalently, the order of the sourceSlots),
// for the example above that would be v, k. The results
// are stored in updateValues above.
//
// Then at the end of the update, the values need to be presented
// back to the TableRowUpdater in the order of the table descriptor
// again.
//
// updateVals is the buffer for this 2nd stage.
// updateColsIdx maps the order of the 2nd stage into the order of the 3rd stage.
// This provides the inverse mapping of sourceSlots.
//
updateColsIdx catalog.TableColMap
// rowIdxToRetIdx is the mapping from the columns in ru.FetchCols to the
// columns in the resultRowBuffer. A value of -1 is used to indicate
// that the column at that index is not part of the resultRowBuffer
// of the mutation. Otherwise, the value at the i-th index refers to the
// index of the resultRowBuffer where the i-th column is to be returned.
rowIdxToRetIdx []int
// numPassthrough is the number of columns in addition to the set of
// columns of the target table being returned, that we must pass through
// from the input node.
numPassthrough int
// regionLocalInfo handles erroring out the UPDATE when the
// enforce_home_region setting is on.
regionLocalInfo regionLocalInfoType
}
func (u *updateNode) startExec(params runParams) error {
// cache traceKV during execution, to avoid re-evaluating it for every row.
u.run.traceKV = params.p.ExtendedEvalContext().Tracing.KVTracingEnabled()
if u.run.rowsNeeded {
u.run.tu.rows = rowcontainer.NewRowContainer(
params.p.Mon().MakeBoundAccount(),
colinfo.ColTypeInfoFromResCols(u.columns),
)
}
return u.run.tu.init(params.ctx, params.p.txn, params.EvalContext(), ¶ms.EvalContext().Settings.SV)
}
// Next is required because batchedPlanNode inherits from planNode, but
// batchedPlanNode doesn't really provide it. See the explanatory comments
// in plan_batch.go.
func (u *updateNode) Next(params runParams) (bool, error) { panic("not valid") }
// Values is required because batchedPlanNode inherits from planNode, but
// batchedPlanNode doesn't really provide it. See the explanatory comments
// in plan_batch.go.
func (u *updateNode) Values() tree.Datums { panic("not valid") }
// BatchedNext implements the batchedPlanNode interface.
func (u *updateNode) BatchedNext(params runParams) (bool, error) {
if u.run.done {
return false, nil
}
// Advance one batch. First, clear the last batch.
u.run.tu.clearLastBatch(params.ctx)
// Now consume/accumulate the rows for this batch.
lastBatch := false
for {
if err := params.p.cancelChecker.Check(); err != nil {
return false, err
}
// Advance one individual row.
if next, err := u.source.Next(params); !next {
lastBatch = true
if err != nil {
return false, err
}
break
}
// Process the update for the current source row, potentially
// accumulating the result row for later.
if err := u.processSourceRow(params, u.source.Values()); err != nil {
return false, err
}
// Are we done yet with the current batch?
if u.run.tu.currentBatchSize >= u.run.tu.maxBatchSize ||
u.run.tu.b.ApproximateMutationBytes() >= u.run.tu.maxBatchByteSize {
break
}
}
if u.run.tu.currentBatchSize > 0 {
if !lastBatch {
// We only run/commit the batch if there were some rows processed
// in this batch.
if err := u.run.tu.flushAndStartNewBatch(params.ctx); err != nil {
return false, err
}
}
}
if lastBatch {
u.run.tu.setRowsWrittenLimit(params.extendedEvalCtx.SessionData())
if err := u.run.tu.finalize(params.ctx); err != nil {
return false, err
}
// Remember we're done for the next call to BatchedNext().
u.run.done = true
}
// Possibly initiate a run of CREATE STATISTICS.
params.ExecCfg().StatsRefresher.NotifyMutation(u.run.tu.tableDesc(), u.run.tu.lastBatchSize)
return u.run.tu.lastBatchSize > 0, nil
}
// processSourceRow processes one row from the source for update and, if
// result rows are needed, saves it in the result row container.
func (u *updateNode) processSourceRow(params runParams, sourceVals tree.Datums) error {
// sourceVals contains values for the columns from the table, in the order of the
// table descriptor. (One per column in u.tw.ru.FetchCols)
//
// And then after that, all the extra expressions potentially added via
// a renderNode for the RHS of the assignments.
// oldValues is the prefix of sourceVals that corresponds to real
// stored columns in the table, that is, excluding the RHS assignment
// expressions.
oldValues := sourceVals[:len(u.run.tu.ru.FetchCols)]
// valueIdx is used in the loop below to map sourceSlots to
// entries in updateValues.
valueIdx := 0
// Propagate the values computed for the RHS expressions into
// updateValues at the right positions. The positions in
// updateValues correspond to the columns named in the LHS
// operands for SET.
for _, slot := range u.run.sourceSlots {
for _, value := range slot.extractValues(sourceVals) {
u.run.updateValues[valueIdx] = value
valueIdx++
}
}
// At this point, we have populated updateValues with the result of
// computing the RHS for every assignment.
//
if len(u.run.computeExprs) > 0 {
// We now need to (re-)compute the computed column values, using
// the updated values above as input.
//
// This needs to happen in the context of a row containing all the
// table's columns as if they had been updated already. This is not
// yet reflected neither by oldValues (which contain non-updated values)
// nor updateValues (which contain only those columns mentioned in the SET LHS).
//
// So we need to construct a buffer that groups them together.
// iVarContainerForComputedCols does this.
copy(u.run.iVarContainerForComputedCols.CurSourceRow, oldValues)
for i := range u.run.tu.ru.UpdateCols {
id := u.run.tu.ru.UpdateCols[i].GetID()
idx := u.run.tu.ru.FetchColIDtoRowIndex.GetDefault(id)
u.run.iVarContainerForComputedCols.CurSourceRow[idx] = u.run.
updateValues[i]
}
// Now (re-)compute the computed columns.
// Note that it's safe to do this in any order, because we currently
// prevent computed columns from depending on other computed columns.
params.EvalContext().PushIVarContainer(&u.run.iVarContainerForComputedCols)
for i := range u.run.computedCols {
d, err := eval.Expr(params.ctx, params.EvalContext(), u.run.computeExprs[i])
if err != nil {
params.EvalContext().IVarContainer = nil
name := u.run.computedCols[i].GetName()
return errors.Wrapf(err, "computed column %s", tree.ErrString((*tree.Name)(&name)))
}
idx := u.run.updateColsIdx.GetDefault(u.run.computedCols[i].GetID())
u.run.updateValues[idx] = d
}
params.EvalContext().PopIVarContainer()
}
// Verify the schema constraints. For consistency with INSERT/UPSERT
// and compatibility with PostgreSQL, we must do this before
// processing the CHECK constraints.
if err := enforceLocalColumnConstraints(u.run.updateValues, u.run.tu.ru.UpdateCols); err != nil {
return err
}
// Run the CHECK constraints, if any. CheckHelper will either evaluate the
// constraints itself, or else inspect boolean columns from the input that
// contain the results of evaluation.
if !u.run.checkOrds.Empty() {
checkVals := sourceVals[len(u.run.tu.ru.FetchCols)+len(u.run.tu.ru.UpdateCols)+u.run.numPassthrough:]
if err := checkMutationInput(
params.ctx, ¶ms.p.semaCtx, params.p.SessionData(), u.run.tu.tableDesc(), u.run.checkOrds, checkVals,
); err != nil {
return err
}
}
// Create a set of partial index IDs to not add entries or remove entries
// from.
var pm row.PartialIndexUpdateHelper
if n := len(u.run.tu.tableDesc().PartialIndexes()); n > 0 {
offset := len(u.run.tu.ru.FetchCols) + len(u.run.tu.ru.UpdateCols) + u.run.checkOrds.Len() + u.run.numPassthrough
partialIndexVals := sourceVals[offset:]
partialIndexPutVals := partialIndexVals[:n]
partialIndexDelVals := partialIndexVals[n : n*2]
err := pm.Init(partialIndexPutVals, partialIndexDelVals, u.run.tu.tableDesc())
if err != nil {
return err
}
}
// Error out the update if the enforce_home_region session setting is on and
// the row's locality doesn't match the gateway region.
if err := u.run.regionLocalInfo.checkHomeRegion(u.run.updateValues); err != nil {
return err
}
// Queue the insert in the KV batch.
newValues, err := u.run.tu.rowForUpdate(params.ctx, oldValues, u.run.updateValues, pm, u.run.traceKV)
if err != nil {
return err
}
// If result rows need to be accumulated, do it.
if u.run.tu.rows != nil {
// The new values can include all columns, so the values may contain
// additional columns for every newly added column not yet visible. We do
// not want them to be available for RETURNING.
//
// MakeUpdater guarantees that the first columns of the new values
// are those specified u.columns.
resultValues := make([]tree.Datum, len(u.columns))
largestRetIdx := -1
for i := range u.run.rowIdxToRetIdx {
retIdx := u.run.rowIdxToRetIdx[i]
if retIdx >= 0 {
if retIdx >= largestRetIdx {
largestRetIdx = retIdx
}
resultValues[retIdx] = newValues[i]
}
}
// At this point we've extracted all the RETURNING values that are part
// of the target table. We must now extract the columns in the RETURNING
// clause that refer to other tables (from the FROM clause of the update).
if u.run.numPassthrough > 0 {
passthroughBegin := len(u.run.tu.ru.FetchCols) + len(u.run.tu.ru.UpdateCols)
passthroughEnd := passthroughBegin + u.run.numPassthrough
passthroughValues := sourceVals[passthroughBegin:passthroughEnd]
for i := 0; i < u.run.numPassthrough; i++ {
largestRetIdx++
resultValues[largestRetIdx] = passthroughValues[i]
}
}
if _, err := u.run.tu.rows.AddRow(params.ctx, resultValues); err != nil {
return err
}
}
return nil
}
// BatchedCount implements the batchedPlanNode interface.
func (u *updateNode) BatchedCount() int { return u.run.tu.lastBatchSize }
// BatchedCount implements the batchedPlanNode interface.
func (u *updateNode) BatchedValues(rowIdx int) tree.Datums { return u.run.tu.rows.At(rowIdx) }
func (u *updateNode) Close(ctx context.Context) {
u.source.Close(ctx)
u.run.tu.close(ctx)
*u = updateNode{}
updateNodePool.Put(u)
}
func (u *updateNode) rowsWritten() int64 {
return u.run.tu.rowsWritten
}
func (u *updateNode) enableAutoCommit() {
u.run.tu.enableAutoCommit()
}
// sourceSlot abstracts the idea that our update sources can either be tuples
// or scalars. Tuples are for cases such as SET (a, b) = (1, 2) or SET (a, b) =
// (SELECT 1, 2), and scalars are for situations like SET a = b. A sourceSlot
// represents how to extract and type-check the results of the right-hand side
// of a single SET statement. We could treat everything as tuples, including
// scalars as tuples of size 1, and eliminate this indirection, but that makes
// the query plan more complex.
type sourceSlot interface {
// extractValues returns a slice of the values this slot is responsible for,
// as extracted from the row of results.
extractValues(resultRow tree.Datums) tree.Datums
// checkColumnTypes compares the types of the results that this slot refers to to the types of
// the columns those values will be assigned to. It returns an error if those types don't match up.
checkColumnTypes(row []tree.TypedExpr) error
}
type scalarSlot struct {
column catalog.Column
sourceIndex int
}
func (ss scalarSlot) extractValues(row tree.Datums) tree.Datums {
return row[ss.sourceIndex : ss.sourceIndex+1]
}
func (ss scalarSlot) checkColumnTypes(row []tree.TypedExpr) error {
renderedResult := row[ss.sourceIndex]
typ := renderedResult.ResolvedType()
return colinfo.CheckDatumTypeFitsColumnType(ss.column, typ)
}
// enforceLocalColumnConstraints asserts the column constraints that do not
// require data validation from other sources than the row data itself. This
// currently only includes checking for null values in non-nullable columns.
func enforceLocalColumnConstraints(row tree.Datums, cols []catalog.Column) error {
for i, col := range cols {
if !col.IsNullable() && row[i] == tree.DNull {
return sqlerrors.NewNonNullViolationError(col.GetName())
}
}
return nil
}
| pkg/sql/update.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0021382926497608423,
0.0002446001162752509,
0.0001613773638382554,
0.0001682772854110226,
0.0003363231080584228
] |
{
"id": 10,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer conn.Close()\n",
"\n",
"\t\tvar appName string\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tdefer func() { _ = conn.Close(ctx) }()\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 140
} | load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "tpcc",
srcs = ["tpcc_bench.go"],
importpath = "github.com/cockroachdb/cockroach/pkg/bench/tpcc",
visibility = ["//visibility:public"],
)
go_test(
name = "tpcc_test",
srcs = [
"main_test.go",
"subprocess_commands_test.go",
"subprocess_utils_test.go",
"tpcc_bench_generate_data_test.go",
"tpcc_bench_options_test.go",
"tpcc_bench_test.go",
],
args = ["-test.timeout=295s"],
embed = [":tpcc"],
deps = [
"//pkg/base",
"//pkg/security/securityassets",
"//pkg/security/securitytest",
"//pkg/server",
"//pkg/testutils",
"//pkg/testutils/serverutils",
"//pkg/testutils/skip",
"//pkg/testutils/sqlutils",
"//pkg/testutils/testcluster",
"//pkg/util/envutil",
"//pkg/util/leaktest",
"//pkg/util/log",
"//pkg/util/randutil",
"//pkg/workload",
"//pkg/workload/histogram",
"//pkg/workload/tpcc",
"//pkg/workload/workloadsql",
"@com_github_cockroachdb_pebble//vfs",
"@com_github_stretchr_testify//require",
],
)
| pkg/bench/tpcc/BUILD.bazel | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017168070189654827,
0.00016843140474520624,
0.00016694334044586867,
0.00016744025924708694,
0.0000017426403928766376
] |
{
"id": 10,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\tdefer conn.Close()\n",
"\n",
"\t\tvar appName string\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tdefer func() { _ = conn.Close(ctx) }()\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 140
} | // Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package kvbase
// FollowerReadServingMsg is a log message that needs to be used for tests in
// other packages.
const FollowerReadServingMsg = "serving via follower read"
// RoutingRequestLocallyMsg is a log message that needs to be used for tests in
// other packages.
const RoutingRequestLocallyMsg = "sending request to local client"
// SpawningHeartbeatLoopMsg is a log message that needs to be used for tests in
// other packages.
const SpawningHeartbeatLoopMsg = "coordinator spawns heartbeat loop"
| pkg/kv/kvbase/constants.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0002348725392948836,
0.000211181424674578,
0.00017500712419860065,
0.00022366465418599546,
0.000025985124011640437
] |
{
"id": 11,
"code_window": [
"\n",
"\t\tvar appName string\n",
"\t\terr = conn.QueryRow(\"SHOW application_name\").Scan(&appName)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"someotherapp\", appName)\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\terr = conn.QueryRow(ctx, \"SHOW application_name\").Scan(&appName)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 143
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.9980602860450745,
0.09217298030853271,
0.00016583182150498033,
0.0014223766047507524,
0.2861350476741791
] |
{
"id": 11,
"code_window": [
"\n",
"\t\tvar appName string\n",
"\t\terr = conn.QueryRow(\"SHOW application_name\").Scan(&appName)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"someotherapp\", appName)\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\terr = conn.QueryRow(ctx, \"SHOW application_name\").Scan(&appName)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 143
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package gossip
import (
"context"
"fmt"
"time"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/storepool"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/asim/config"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/asim/state"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
)
// Gossip collects and updates the storepools of the cluster upon capacity
// changes and the gossip interval defined in the simulation settings.
type Gossip interface {
// Tick checks for completed gossip updates and triggers new gossip
// updates if needed.
Tick(context.Context, time.Time, state.State)
}
// gossip is an implementation of the Gossip interface. It manages the
// dissemenation of gossip information to stores in the cluster.
type gossip struct {
storeGossip map[state.StoreID]*storeGossiper
settings *config.SimulationSettings
exchange *fixedDelayExchange
}
var _ Gossip = &gossip{}
// storeGossiper is the store-local gossip state that tracks information
// required to decide when to gossip and pending outbound gossip infos that
// have been triggered by the underlying kvserver.StoreGossip component.
type storeGossiper struct {
local *kvserver.StoreGossip
lastIntervalGossip time.Time
descriptorGetter func(cached bool) roachpb.StoreDescriptor
pendingOutbound *roachpb.StoreDescriptor
addingStore bool
}
func newStoreGossiper(descriptorGetter func(cached bool) roachpb.StoreDescriptor) *storeGossiper {
sg := &storeGossiper{
lastIntervalGossip: time.Time{},
descriptorGetter: descriptorGetter,
}
desc := sg.descriptorGetter(false /* cached */)
knobs := kvserver.StoreGossipTestingKnobs{AsyncDisabled: true}
sg.local = kvserver.NewStoreGossip(sg, sg, knobs)
sg.local.Ident = roachpb.StoreIdent{StoreID: desc.StoreID, NodeID: desc.Node.NodeID}
return sg
}
var _ kvserver.InfoGossiper = &storeGossiper{}
var _ kvserver.StoreDescriptorProvider = &storeGossiper{}
// AddInfoProto adds or updates an info object in gossip. Returns an error
// if info couldn't be added.
func (sg *storeGossiper) AddInfoProto(key string, msg protoutil.Message, ttl time.Duration) error {
desc := msg.(*roachpb.StoreDescriptor)
// NB: We overwrite any pending outbound gossip infos. This behavior is
// valid as at each tick we will check this field before sending it off to
// the asim internal gossip exchange; any overwritten gossip infos would
// also have been overwritten in the same tick at the receiver i.e. last
// writer in the tick wins.
sg.pendingOutbound = desc
return nil
}
// Descriptor returns a StoreDescriptor including current store
// capacity information.
func (sg *storeGossiper) Descriptor(
ctx context.Context, cached bool,
) (*roachpb.StoreDescriptor, error) {
desc := sg.descriptorGetter(cached)
if cached {
capacity := sg.local.CachedCapacity()
if capacity != (roachpb.StoreCapacity{}) {
desc.Capacity = capacity
}
}
return &desc, nil
}
// NewGossip returns an implementation of the Gossip interface.
func NewGossip(s state.State, settings *config.SimulationSettings) *gossip {
g := &gossip{
settings: settings,
storeGossip: map[state.StoreID]*storeGossiper{},
exchange: &fixedDelayExchange{
pending: []exchangeInfo{},
settings: settings,
},
}
for _, store := range s.Stores() {
g.addStoreToGossip(s, store.StoreID())
}
s.RegisterCapacityChangeListener(g)
s.RegisterCapacityListener(g)
s.RegisterConfigChangeListener(g)
return g
}
func (g *gossip) addStoreToGossip(s state.State, storeID state.StoreID) {
// Add the store gossip in an "adding" state initially, this is to avoid
// recursive calls to get the store descriptor.
g.storeGossip[storeID] = &storeGossiper{addingStore: true}
g.storeGossip[storeID] = newStoreGossiper(func(cached bool) roachpb.StoreDescriptor {
return s.StoreDescriptors(cached, storeID)[0]
})
}
// Tick checks for completed gossip updates and triggers new gossip
// updates if needed.
func (g *gossip) Tick(ctx context.Context, tick time.Time, s state.State) {
stores := s.Stores()
for _, store := range stores {
var sg *storeGossiper
var ok bool
// If the store gossip for this store doesn't yet exist, create it and
// add it to the map of store gossips.
if sg, ok = g.storeGossip[store.StoreID()]; !ok {
g.addStoreToGossip(s, store.StoreID())
}
// If the interval between the last time this store was gossiped for
// interval and this tick is not less than the gossip interval, then we
// shoud gossip.
// NB: In the real code this is controlled by a gossip
// ticker on the node that activates every 10 seconds.
if !tick.Before(sg.lastIntervalGossip.Add(g.settings.StateExchangeInterval)) {
sg.lastIntervalGossip = tick
_ = sg.local.GossipStore(ctx, false /* useCached */)
}
// Put the pending gossip infos into the exchange.
if sg.pendingOutbound != nil {
desc := *sg.pendingOutbound
g.exchange.put(tick, desc)
// Clear the pending gossip infos for this store.
sg.pendingOutbound = nil
}
}
// Update with any recently complete gossip infos.
g.maybeUpdateState(tick, s)
}
// CapacityChangeNotify notifies that a capacity change event has occurred
// for the store with ID StoreID.
func (g *gossip) CapacityChangeNotify(cce kvserver.CapacityChangeEvent, storeID state.StoreID) {
if sg, ok := g.storeGossip[storeID]; ok {
if !sg.addingStore {
sg.local.MaybeGossipOnCapacityChange(context.Background(), cce)
}
} else {
panic(
fmt.Sprintf("capacity change event but no found store in store gossip with ID %d",
storeID,
))
}
}
// NewCapacityNotify notifies that a new capacity event has occurred for
// the store with ID StoreID.
func (g *gossip) NewCapacityNotify(capacity roachpb.StoreCapacity, storeID state.StoreID) {
if sg, ok := g.storeGossip[storeID]; ok {
if !sg.addingStore {
sg.local.UpdateCachedCapacity(capacity)
}
} else {
panic(
fmt.Sprintf("new capacity event but no found store in store gossip with ID %d",
storeID,
))
}
}
// StoreAddNotify notifies that a new store has been added with ID storeID.
func (g *gossip) StoreAddNotify(storeID state.StoreID, s state.State) {
g.addStoreToGossip(s, storeID)
}
func (g *gossip) maybeUpdateState(tick time.Time, s state.State) {
// NB: The updates function gives back all store descriptors which have
// completed exchange. We apply the update to every stores state uniformly,
// i.e. fixed delay.
updates := g.exchange.updates(tick)
if len(updates) == 0 {
return
}
updateMap := map[roachpb.StoreID]*storepool.StoreDetail{}
for _, update := range updates {
updateMap[update.Desc.StoreID] = update
}
for _, store := range s.Stores() {
s.UpdateStorePool(store.StoreID(), updateMap)
}
}
| pkg/kv/kvserver/asim/gossip/gossip.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0002126834588125348,
0.0001717768027447164,
0.00016227804007939994,
0.00016963084635790437,
0.00000959323915594723
] |
{
"id": 11,
"code_window": [
"\n",
"\t\tvar appName string\n",
"\t\terr = conn.QueryRow(\"SHOW application_name\").Scan(&appName)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"someotherapp\", appName)\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\terr = conn.QueryRow(ctx, \"SHOW application_name\").Scan(&appName)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 143
} | # Test the basics of admitting elastic work; look at metrics, what the
# underlying work queue observes, and the handle returned.
init
----
# Verify that admitting 50ms of work translates to just that much in the
# underlying work queue, metrics, and the work handle itself.
admit duration=50ms
----
granter:
work-queue: admitted=50ms
metrics: acquired=50ms returned=0s max-available=8s
handle: 50ms
# Verify that requested durations are clamped between [10ms, 100ms].
admit duration=101ms
----
granter:
work-queue: admitted=100ms
metrics: acquired=150ms returned=0s max-available=8s
handle: 100ms
admit duration=1ms
----
granter:
work-queue: admitted=10ms
metrics: acquired=160ms returned=0s max-available=8s
handle: 10ms
# Verify that if the underlying queue is disabled, nothing happens (handle is
# empty, metrics stay as is).
admit duration=10ms disabled=true
----
granter:
work-queue:
metrics: acquired=160ms returned=0s max-available=8s
handle: n/a
# Verify that re-enabling the underlying queue works as expected.
admit duration=10ms disabled=false
----
granter:
work-queue: admitted=10ms
metrics: acquired=170ms returned=0s max-available=8s
handle: 10ms
# Test the basics of invoking work-completion functions; ensure the accounting
# (metrics) and grant-forwarding is done correctly.
init
----
admit duration=50ms
----
granter:
work-queue: admitted=50ms
metrics: acquired=50ms returned=0s max-available=8s
handle: 50ms
# If we've acquired more than needed, we should be returning the difference
# back to the granter and updating the right metric (returned nanos).
admitted-work-done running=10ms allotted=50ms
----
granter: return-grant=40ms
work-queue:
metrics: acquired=50ms returned=40ms max-available=8s
# Repeat the same but this time simulate what happens if we've taken less than
# what we ended up needing.
init
----
admit duration=50ms
----
granter:
work-queue: admitted=50ms
metrics: acquired=50ms returned=0s max-available=8s
handle: 50ms
# We should subtract the overage from the granter without blocking and count
# the difference towards the right metric (acquired)
admitted-work-done running=70ms allotted=50ms
----
granter: took-without-permission=20ms
work-queue:
metrics: acquired=70ms returned=0s max-available=8s
# vim:ft=sh
| pkg/util/admission/testdata/elastic_cpu_work_queue | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017217561253346503,
0.00016994663747027516,
0.00016782099555712193,
0.00017010467126965523,
0.0000015697688695581746
] |
{
"id": 11,
"code_window": [
"\n",
"\t\tvar appName string\n",
"\t\terr = conn.QueryRow(\"SHOW application_name\").Scan(&appName)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"someotherapp\", appName)\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\terr = conn.QueryRow(ctx, \"SHOW application_name\").Scan(&appName)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 143
} | init
rate: 100
initial: 1000
----
Current RUs: 1000
request
ru: 10
----
Granted: 10 RU
Trickle duration: 0s
Fallback rate: 100.2777778 RU/s
Current RUs: 990
request
ru: 890
----
Granted: 890 RU
Trickle duration: 0s
Fallback rate: 100.275 RU/s
Current RUs: 100
# We have 100 available, and it will take 1s for another 100 to become
# available.
request
ru: 200
----
Granted: 200 RU
Trickle duration: 1s
Fallback rate: 100.0277778 RU/s
Current RUs: -100
# Request a very large value. We only grant what we get over the next request
# period (10s by default).
request
ru: 10000
----
Granted: 1000 RU
Trickle duration: 10s
Fallback rate: 100 RU/s
Current RUs: -1100
# If we keep requesting, we will enter into debt and less will be granted.
request
ru: 1000
----
Granted: 900 RU
Trickle duration: 10s
Fallback rate: 100 RU/s
Current RUs: -2000
request
ru: 1000
----
Granted: 50 RU
Trickle duration: 10s
Fallback rate: 100 RU/s
Current RUs: -2050
update
10s
----
Current RUs: -1050
request
ru: 100
----
Granted: 100 RU
Trickle duration: 1.052631578s
Fallback rate: 100 RU/s
Current RUs: -1150
update
10s
----
Current RUs: -150
request
ru: 100
----
Granted: 100 RU
Trickle duration: 1s
Fallback rate: 100 RU/s
Current RUs: -250
| pkg/ccl/multitenantccl/tenantcostserver/tenanttokenbucket/testdata/request | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017490569734945893,
0.00017238943837583065,
0.0001683279115241021,
0.00017282762564718723,
0.000002117344820362632
] |
{
"id": 12,
"code_window": [
"\t\trequire.Equal(t, \"someotherapp\", appName)\n",
"\n",
"\t\tvar b bool\n",
"\t\terr = conn.QueryRow(\n",
"\t\t\t\"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))\",\n",
"\t\t\tstate,\n",
"\t\t).Scan(&b)\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tctx,\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 149
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.997666597366333,
0.09678839892148972,
0.00016299777780659497,
0.0015547445509582758,
0.2853167653083801
] |
{
"id": 12,
"code_window": [
"\t\trequire.Equal(t, \"someotherapp\", appName)\n",
"\n",
"\t\tvar b bool\n",
"\t\terr = conn.QueryRow(\n",
"\t\t\t\"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))\",\n",
"\t\t\tstate,\n",
"\t\t).Scan(&b)\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tctx,\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 149
} | // Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
//go:build !386 && !amd64
// +build !386,!amd64
package encoding
func onesComplement(b []byte) {
for i := range b {
b[i] = ^b[i]
}
}
| pkg/util/encoding/complement_safe.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00978542398661375,
0.003380559151992202,
0.00017632616800256073,
0.00017992692301049829,
0.00452892342582345
] |
{
"id": 12,
"code_window": [
"\t\trequire.Equal(t, \"someotherapp\", appName)\n",
"\n",
"\t\tvar b bool\n",
"\t\terr = conn.QueryRow(\n",
"\t\t\t\"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))\",\n",
"\t\t\tstate,\n",
"\t\t).Scan(&b)\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tctx,\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 149
} | // Copyright 2023 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package opgen
import (
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scop"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scpb"
)
func init() {
opRegistry.register((*scpb.CheckConstraintUnvalidated)(nil),
toPublic(
scpb.Status_ABSENT,
to(scpb.Status_PUBLIC,
emit(func(this *scpb.CheckConstraintUnvalidated) *scop.AddCheckConstraint {
return &scop.AddCheckConstraint{
TableID: this.TableID,
ConstraintID: this.ConstraintID,
ColumnIDs: this.ColumnIDs,
CheckExpr: this.Expr,
Validity: descpb.ConstraintValidity_Unvalidated,
}
}),
emit(func(this *scpb.CheckConstraintUnvalidated) *scop.UpdateTableBackReferencesInTypes {
if len(this.UsesTypeIDs) == 0 {
return nil
}
return &scop.UpdateTableBackReferencesInTypes{
TypeIDs: this.UsesTypeIDs,
BackReferencedTableID: this.TableID,
}
}),
emit(func(this *scpb.CheckConstraintUnvalidated) *scop.UpdateTableBackReferencesInSequences {
if len(this.UsesSequenceIDs) == 0 {
return nil
}
return &scop.UpdateTableBackReferencesInSequences{
SequenceIDs: this.UsesSequenceIDs,
BackReferencedTableID: this.TableID,
}
}),
),
),
toAbsent(
scpb.Status_PUBLIC,
to(scpb.Status_ABSENT,
emit(func(this *scpb.CheckConstraintUnvalidated) *scop.RemoveCheckConstraint {
return &scop.RemoveCheckConstraint{
TableID: this.TableID,
ConstraintID: this.ConstraintID,
}
}),
emit(func(this *scpb.CheckConstraintUnvalidated) *scop.UpdateTableBackReferencesInTypes {
if len(this.UsesTypeIDs) == 0 {
return nil
}
return &scop.UpdateTableBackReferencesInTypes{
TypeIDs: this.UsesTypeIDs,
BackReferencedTableID: this.TableID,
}
}),
emit(func(this *scpb.CheckConstraintUnvalidated) *scop.UpdateTableBackReferencesInSequences {
if len(this.UsesSequenceIDs) == 0 {
return nil
}
return &scop.UpdateTableBackReferencesInSequences{
SequenceIDs: this.UsesSequenceIDs,
BackReferencedTableID: this.TableID,
}
}),
),
),
)
}
| pkg/sql/schemachanger/scplan/internal/opgen/opgen_check_constraint_unvalidated.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017920132086146623,
0.00017212606326211244,
0.00016789718938525766,
0.00017100723925977945,
0.000003464333758529392
] |
{
"id": 12,
"code_window": [
"\t\trequire.Equal(t, \"someotherapp\", appName)\n",
"\n",
"\t\tvar b bool\n",
"\t\terr = conn.QueryRow(\n",
"\t\t\t\"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))\",\n",
"\t\t\tstate,\n",
"\t\t).Scan(&b)\n",
"\t\trequire.NoError(t, err)\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tctx,\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 149
} | // Code generated by TestPretty. DO NOT EDIT.
// GENERATED FILE DO NOT EDIT
1:
-
CREATE VIEW startrek.quotes_per_season (
season,
quotes
) AS
SELECT
startrek.episodes.season,
count(
*
)
FROM
startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY
startrek.episodes.season
16:
----------------
CREATE VIEW startrek.quotes_per_season (
season,
quotes
) AS
SELECT
startrek.episodes.season,
count(*)
FROM
startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY
startrek.episodes.season
38:
--------------------------------------
CREATE VIEW startrek.quotes_per_season (
season,
quotes
) AS
SELECT startrek.episodes.season,
count(*)
FROM startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY startrek.episodes.season
40:
----------------------------------------
CREATE VIEW startrek.quotes_per_season (
season,
quotes
) AS SELECT startrek.episodes.season,
count(*)
FROM startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY startrek.episodes.season
48:
------------------------------------------------
CREATE VIEW startrek.quotes_per_season (
season,
quotes
) AS SELECT startrek.episodes.season, count(*)
FROM startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY startrek.episodes.season
58:
----------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (
season,
quotes
) AS SELECT startrek.episodes.season, count(*)
FROM startrek.quotes
JOIN startrek.episodes ON startrek.quotes.episode
= startrek.episodes.id
GROUP BY startrek.episodes.season
65:
-----------------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (season, quotes) AS SELECT
startrek.episodes.season,
count(
*
)
FROM
startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY
startrek.episodes.season
68:
--------------------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (season, quotes) AS SELECT
startrek.episodes.season,
count(*)
FROM
startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY
startrek.episodes.season
93:
---------------------------------------------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (season, quotes) AS SELECT startrek.episodes.season,
count(*)
FROM startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY startrek.episodes.season
102:
------------------------------------------------------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (season, quotes) AS SELECT startrek.episodes.season, count(*)
FROM startrek.quotes
JOIN startrek.episodes ON
startrek.quotes.episode
= startrek.episodes.id
GROUP BY startrek.episodes.season
112:
----------------------------------------------------------------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (season, quotes) AS SELECT startrek.episodes.season, count(*)
FROM startrek.quotes
JOIN startrek.episodes ON startrek.quotes.episode
= startrek.episodes.id
GROUP BY startrek.episodes.season
135:
---------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (season, quotes) AS SELECT startrek.episodes.season, count(*)
FROM startrek.quotes
JOIN startrek.episodes ON startrek.quotes.episode = startrek.episodes.id
GROUP BY startrek.episodes.season
156:
------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (season, quotes) AS SELECT startrek.episodes.season, count(*)
FROM startrek.quotes JOIN startrek.episodes ON startrek.quotes.episode = startrek.episodes.id
GROUP BY startrek.episodes.season
228:
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW startrek.quotes_per_season (season, quotes) AS SELECT startrek.episodes.season, count(*) FROM startrek.quotes JOIN startrek.episodes ON startrek.quotes.episode = startrek.episodes.id GROUP BY startrek.episodes.season
| pkg/sql/sem/tree/testdata/pretty/create_view.align-deindent.golden | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0001771586830727756,
0.00017260028107557446,
0.00016431465337518603,
0.00017393575399182737,
0.000003277829591752379
] |
{
"id": 13,
"code_window": [
"\t\t).Scan(&b)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.True(t, b)\n",
"\n",
"\t\terr = conn.QueryRow(\"SHOW application_name\").Scan(&appName)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"carl\", appName)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\terr = conn.QueryRow(ctx, \"SHOW application_name\").Scan(&appName)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 155
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.997961163520813,
0.050039950758218765,
0.00016544171376153827,
0.000755592598579824,
0.20725932717323303
] |
{
"id": 13,
"code_window": [
"\t\t).Scan(&b)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.True(t, b)\n",
"\n",
"\t\terr = conn.QueryRow(\"SHOW application_name\").Scan(&appName)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"carl\", appName)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\terr = conn.QueryRow(ctx, \"SHOW application_name\").Scan(&appName)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 155
} | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tests
var sqlAlchemyBlocklist = blocklist{}
var sqlAlchemyIgnoreList = blocklist{}
| pkg/cmd/roachtest/tests/sqlalchemy_blocklist.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00019645314023364335,
0.00018674327293410897,
0.00017703339108265936,
0.00018674327293410897,
0.000009709874575491995
] |
{
"id": 13,
"code_window": [
"\t\t).Scan(&b)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.True(t, b)\n",
"\n",
"\t\terr = conn.QueryRow(\"SHOW application_name\").Scan(&appName)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"carl\", appName)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\terr = conn.QueryRow(ctx, \"SHOW application_name\").Scan(&appName)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 155
} | blank_issues_enabled: false
contact_links:
- name: Security Vulnerabilities
url: https://www.cockroachlabs.com/security/responsible-disclosure-policy/
about: "Report a security vulnerability or security-related bug in CockroachDB or Cockroach Cloud"
- name: CockroachDB Community Forum
url: https://forum.cockroachlabs.com/
about: "For general questions about CockroachDB"
- name: Enterprise Support
url: https://support.cockroachlabs.com
about: "Enterprise Support"
| .github/ISSUE_TEMPLATE/config.yml | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00017547547759022564,
0.00017004774417728186,
0.00016461999621242285,
0.00017004774417728186,
0.000005427740688901395
] |
{
"id": 13,
"code_window": [
"\t\t).Scan(&b)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.True(t, b)\n",
"\n",
"\t\terr = conn.QueryRow(\"SHOW application_name\").Scan(&appName)\n",
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"carl\", appName)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\terr = conn.QueryRow(ctx, \"SHOW application_name\").Scan(&appName)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "replace",
"edit_start_line_idx": 155
} | load("@io_bazel_rules_go//go:def.bzl", "go_test")
go_test(
name = "spanconfiglimiterccl_test",
srcs = [
"datadriven_test.go",
"drop_table_test.go",
"main_test.go",
],
args = ["-test.timeout=295s"],
data = glob(["testdata/**"]),
tags = ["ccl_test"],
deps = [
"//pkg/base",
"//pkg/ccl",
"//pkg/ccl/kvccl/kvtenantccl",
"//pkg/ccl/partitionccl",
"//pkg/config",
"//pkg/config/zonepb",
"//pkg/roachpb",
"//pkg/security/securityassets",
"//pkg/security/securitytest",
"//pkg/server",
"//pkg/spanconfig",
"//pkg/spanconfig/spanconfigtestutils/spanconfigtestcluster",
"//pkg/sql",
"//pkg/sql/gcjob",
"//pkg/testutils",
"//pkg/testutils/datapathutils",
"//pkg/testutils/serverutils",
"//pkg/testutils/skip",
"//pkg/testutils/sqlutils",
"//pkg/testutils/testcluster",
"//pkg/util/leaktest",
"//pkg/util/log",
"//pkg/util/randutil",
"@com_github_cockroachdb_datadriven//:datadriven",
"@com_github_cockroachdb_errors//:errors",
"@com_github_stretchr_testify//require",
],
)
| pkg/ccl/spanconfigccl/spanconfiglimiterccl/BUILD.bazel | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0001772553223418072,
0.00017332452989649028,
0.00016978495114017278,
0.0001728213537717238,
0.0000025209876639564754
] |
{
"id": 14,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"carl\", appName)\n",
"\t})\n",
"\n",
"\t// Errors should be displayed as a SQL value.\n",
"\tt.Run(\"errors\", func(t *testing.T) {\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t// Confirm that the prepared statement can be used after deserializing the\n",
"\t\t// session.\n",
"\t\tresult := conn.PgConn().ExecPrepared(\n",
"\t\t\tctx,\n",
"\t\t\t\"prepared_stmt\",\n",
"\t\t\t[][]byte{{0, 0, 0, 2}}, // binary representation of 2\n",
"\t\t\t[]int16{1}, // paramFormats - 1 means binary\n",
"\t\t\t[]int16{1}, // resultFormats - 1 means binary\n",
"\t\t).Read()\n",
"\t\trequire.Equal(t, [][][]byte{{\n",
"\t\t\t{0, 0, 0, 2}, {0x66, 0x6f, 0x6f}, // binary representation of 2, 'foo'\n",
"\t\t}}, result.Rows)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 158
} | // Copyright 2022 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package sqlccl
import (
"context"
gosql "database/sql"
"net/url"
"testing"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestShowTransferState(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
})
defer s.Stopper().Stop(ctx)
tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{
TenantID: serverutils.TestTenantID(),
})
defer tenant.Stopper().Stop(ctx)
_, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'")
require.NoError(t, err)
_, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true")
require.NoError(t, err)
testUserConn := tenant.SQLConnForUser(t, username.TestUser, "")
t.Run("without_transfer_key", func(t *testing.T) {
conn := testUserConn
rows, err := conn.Query("SHOW TRANSFER STATE")
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
}, resultColumns)
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
})
var state, token string
t.Run("with_transfer_key", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-with_transfer_key",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "carl")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
// Add a prepared statement to make sure SHOW TRANSFER STATE handles it.
// Since lib/pq doesn't tell us the name of the prepared statement, we won't
// be able to test that we can use it after deserializing the session, but
// there are other tests for that.
stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1")
require.NoError(t, err)
defer stmt.Close()
rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`)
require.NoError(t, err, "show transfer state failed")
defer rows.Close()
resultColumns, err := rows.Columns()
require.NoError(t, err)
require.Equal(t, []string{
"error",
"session_state_base64",
"session_revival_token_base64",
"transfer_key",
}, resultColumns)
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
rows.Next()
err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err, "unexpected error while reading transfer state")
require.Equal(t, "foobar", key)
require.False(t, errVal.Valid)
require.True(t, sessionState.Valid)
require.True(t, sessionRevivalToken.Valid)
state = sessionState.String
token = sessionRevivalToken.String
})
t.Run("successful_transfer", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-successful_transfer",
url.User(username.TestUser), // Do not use a password here.
)
defer cleanup()
q := pgURL.Query()
q.Add("application_name", "someotherapp")
q.Add("crdb:session_revival_token_base64", token)
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
var appName string
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "someotherapp", appName)
var b bool
err = conn.QueryRow(
"SELECT crdb_internal.deserialize_session(decode($1, 'base64'))",
state,
).Scan(&b)
require.NoError(t, err)
require.True(t, b)
err = conn.QueryRow("SHOW application_name").Scan(&appName)
require.NoError(t, err)
require.Equal(t, "carl", appName)
})
// Errors should be displayed as a SQL value.
t.Run("errors", func(t *testing.T) {
t.Run("root_user", func(t *testing.T) {
var key string
var errVal, sessionState, sessionRevivalToken gosql.NullString
err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot create token for root user", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("transaction", func(t *testing.T) {
conn := testUserConn
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error {
return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
})
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
t.Run("temp_tables", func(t *testing.T) {
pgURL, cleanup := sqlutils.PGUrl(
t,
tenant.SQLAddr(),
"TestShowTransferState-errors-temp_tables",
url.UserPassword(username.TestUser, "hunter2"),
)
defer cleanup()
q := pgURL.Query()
q.Add("experimental_enable_temp_tables", "true")
pgURL.RawQuery = q.Encode()
conn, err := gosql.Open("postgres", pgURL.String())
require.NoError(t, err)
defer conn.Close()
_, err = conn.Exec("CREATE TEMP TABLE temp_tbl()")
require.NoError(t, err)
var errVal, sessionState, sessionRevivalToken gosql.NullString
err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken)
require.NoError(t, err)
require.True(t, errVal.Valid)
require.Equal(t, "cannot serialize session with temporary schemas", errVal.String)
require.False(t, sessionState.Valid)
require.False(t, sessionRevivalToken.Valid)
})
})
}
| pkg/ccl/testccl/sqlccl/show_transfer_state_test.go | 1 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.8383351564407349,
0.05345261096954346,
0.00016728276386857033,
0.001451797434128821,
0.17972692847251892
] |
{
"id": 14,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"carl\", appName)\n",
"\t})\n",
"\n",
"\t// Errors should be displayed as a SQL value.\n",
"\tt.Run(\"errors\", func(t *testing.T) {\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t// Confirm that the prepared statement can be used after deserializing the\n",
"\t\t// session.\n",
"\t\tresult := conn.PgConn().ExecPrepared(\n",
"\t\t\tctx,\n",
"\t\t\t\"prepared_stmt\",\n",
"\t\t\t[][]byte{{0, 0, 0, 2}}, // binary representation of 2\n",
"\t\t\t[]int16{1}, // paramFormats - 1 means binary\n",
"\t\t\t[]int16{1}, // resultFormats - 1 means binary\n",
"\t\t).Read()\n",
"\t\trequire.Equal(t, [][][]byte{{\n",
"\t\t\t{0, 0, 0, 2}, {0x66, 0x6f, 0x6f}, // binary representation of 2, 'foo'\n",
"\t\t}}, result.Rows)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 158
} | show_create_stmt ::=
'SHOW' 'CREATE' object_name opt_show_create_format_options
| 'SHOW' 'CREATE' 'ALL' 'SCHEMAS'
| 'SHOW' 'CREATE' 'ALL' 'TABLES'
| 'SHOW' 'CREATE' 'ALL' 'TYPES'
| docs/generated/sql/bnf/show_create_stmt.bnf | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.00016654047067277133,
0.00016654047067277133,
0.00016654047067277133,
0.00016654047067277133,
0
] |
{
"id": 14,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"carl\", appName)\n",
"\t})\n",
"\n",
"\t// Errors should be displayed as a SQL value.\n",
"\tt.Run(\"errors\", func(t *testing.T) {\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t// Confirm that the prepared statement can be used after deserializing the\n",
"\t\t// session.\n",
"\t\tresult := conn.PgConn().ExecPrepared(\n",
"\t\t\tctx,\n",
"\t\t\t\"prepared_stmt\",\n",
"\t\t\t[][]byte{{0, 0, 0, 2}}, // binary representation of 2\n",
"\t\t\t[]int16{1}, // paramFormats - 1 means binary\n",
"\t\t\t[]int16{1}, // resultFormats - 1 means binary\n",
"\t\t).Read()\n",
"\t\trequire.Equal(t, [][][]byte{{\n",
"\t\t\t{0, 0, 0, 2}, {0x66, 0x6f, 0x6f}, // binary representation of 2, 'foo'\n",
"\t\t}}, result.Rows)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 158
} | // Code generated by TestPretty. DO NOT EDIT.
// GENERATED FILE DO NOT EDIT
1:
-
SELECT
1,
2,
3
9:
---------
SELECT 1,
2,
3
14:
--------------
SELECT 1, 2, 3
| pkg/sql/sem/tree/testdata/pretty/10.align-deindent.golden | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.0001799150777515024,
0.00017822526569943875,
0.00017588371702004224,
0.00017887695867102593,
0.0000017090951587306336
] |
{
"id": 14,
"code_window": [
"\t\trequire.NoError(t, err)\n",
"\t\trequire.Equal(t, \"carl\", appName)\n",
"\t})\n",
"\n",
"\t// Errors should be displayed as a SQL value.\n",
"\tt.Run(\"errors\", func(t *testing.T) {\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\t// Confirm that the prepared statement can be used after deserializing the\n",
"\t\t// session.\n",
"\t\tresult := conn.PgConn().ExecPrepared(\n",
"\t\t\tctx,\n",
"\t\t\t\"prepared_stmt\",\n",
"\t\t\t[][]byte{{0, 0, 0, 2}}, // binary representation of 2\n",
"\t\t\t[]int16{1}, // paramFormats - 1 means binary\n",
"\t\t\t[]int16{1}, // resultFormats - 1 means binary\n",
"\t\t).Read()\n",
"\t\trequire.Equal(t, [][][]byte{{\n",
"\t\t\t{0, 0, 0, 2}, {0x66, 0x6f, 0x6f}, // binary representation of 2, 'foo'\n",
"\t\t}}, result.Rows)\n"
],
"file_path": "pkg/ccl/testccl/sqlccl/show_transfer_state_test.go",
"type": "add",
"edit_start_line_idx": 158
} | // Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package clisqlexec
import (
"database/sql/driver"
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
func isNotPrintableASCII(r rune) bool { return r < 0x20 || r > 0x7e || r == '"' || r == '\\' }
func isNotGraphicUnicode(r rune) bool { return !unicode.IsGraphic(r) }
func isNotGraphicUnicodeOrTabOrNewline(r rune) bool {
return r != '\t' && r != '\n' && !unicode.IsGraphic(r)
}
// FormatVal formats a value retrieved by a SQL driver into a string
// suitable for displaying to the user.
func FormatVal(val driver.Value, showPrintableUnicode bool, showNewLinesAndTabs bool) string {
switch t := val.(type) {
case nil:
return "NULL"
case string:
if showPrintableUnicode {
pred := isNotGraphicUnicode
if showNewLinesAndTabs {
pred = isNotGraphicUnicodeOrTabOrNewline
}
if utf8.ValidString(t) && strings.IndexFunc(t, pred) == -1 {
return t
}
} else {
if strings.IndexFunc(t, isNotPrintableASCII) == -1 {
return t
}
}
s := fmt.Sprintf("%+q", t)
// Strip the start and final quotes. The surrounding display
// format (e.g. CSV/TSV) will add its own quotes.
return s[1 : len(s)-1]
}
// Fallback to printing the value as-is.
return fmt.Sprint(val)
}
| pkg/cli/clisqlexec/format_value.go | 0 | https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e | [
0.008448363281786442,
0.0028429937083274126,
0.00016671732009854168,
0.00019992968009319156,
0.0037639369256794453
] |
{
"id": 0,
"code_window": [
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n",
"\tif !user.IsActive {\n",
"\t\treturn nil, ErrUserInactive{user.ID, user.Name}\n",
"\t} else if user.ProhibitLogin {\n",
"\t\treturn nil, ErrUserProhibitLogin{user.ID, user.Name}\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// WARN: DON'T check user.IsActive, that will be checked on reqSign so that\n",
"\t// user could be hint to resend confirm email.\n",
"\tif user.ProhibitLogin {\n"
],
"file_path": "models/login_source.go",
"type": "replace",
"edit_start_line_idx": 618
} | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/smtp"
"net/textproto"
"strings"
"github.com/Unknwon/com"
"github.com/go-macaron/binding"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
"code.gitea.io/gitea/modules/auth/ldap"
"code.gitea.io/gitea/modules/auth/oauth2"
"code.gitea.io/gitea/modules/auth/pam"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util"
)
// LoginType represents an login type.
type LoginType int
// Note: new type must append to the end of list to maintain compatibility.
const (
LoginNoType LoginType = iota
LoginPlain // 1
LoginLDAP // 2
LoginSMTP // 3
LoginPAM // 4
LoginDLDAP // 5
LoginOAuth2 // 6
)
// LoginNames contains the name of LoginType values.
var LoginNames = map[LoginType]string{
LoginLDAP: "LDAP (via BindDN)",
LoginDLDAP: "LDAP (simple auth)", // Via direct bind
LoginSMTP: "SMTP",
LoginPAM: "PAM",
LoginOAuth2: "OAuth2",
}
// SecurityProtocolNames contains the name of SecurityProtocol values.
var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
ldap.SecurityProtocolUnencrypted: "Unencrypted",
ldap.SecurityProtocolLDAPS: "LDAPS",
ldap.SecurityProtocolStartTLS: "StartTLS",
}
// Ensure structs implemented interface.
var (
_ core.Conversion = &LDAPConfig{}
_ core.Conversion = &SMTPConfig{}
_ core.Conversion = &PAMConfig{}
_ core.Conversion = &OAuth2Config{}
)
// LDAPConfig holds configuration for LDAP login source.
type LDAPConfig struct {
*ldap.Source
}
// FromDB fills up a LDAPConfig from serialized format.
func (cfg *LDAPConfig) FromDB(bs []byte) error {
return json.Unmarshal(bs, &cfg)
}
// ToDB exports a LDAPConfig to a serialized format.
func (cfg *LDAPConfig) ToDB() ([]byte, error) {
return json.Marshal(cfg)
}
// SecurityProtocolName returns the name of configured security
// protocol.
func (cfg *LDAPConfig) SecurityProtocolName() string {
return SecurityProtocolNames[cfg.SecurityProtocol]
}
// SMTPConfig holds configuration for the SMTP login source.
type SMTPConfig struct {
Auth string
Host string
Port int
AllowedDomains string `xorm:"TEXT"`
TLS bool
SkipVerify bool
}
// FromDB fills up an SMTPConfig from serialized format.
func (cfg *SMTPConfig) FromDB(bs []byte) error {
return json.Unmarshal(bs, cfg)
}
// ToDB exports an SMTPConfig to a serialized format.
func (cfg *SMTPConfig) ToDB() ([]byte, error) {
return json.Marshal(cfg)
}
// PAMConfig holds configuration for the PAM login source.
type PAMConfig struct {
ServiceName string // pam service (e.g. system-auth)
}
// FromDB fills up a PAMConfig from serialized format.
func (cfg *PAMConfig) FromDB(bs []byte) error {
return json.Unmarshal(bs, &cfg)
}
// ToDB exports a PAMConfig to a serialized format.
func (cfg *PAMConfig) ToDB() ([]byte, error) {
return json.Marshal(cfg)
}
// OAuth2Config holds configuration for the OAuth2 login source.
type OAuth2Config struct {
Provider string
ClientID string
ClientSecret string
OpenIDConnectAutoDiscoveryURL string
CustomURLMapping *oauth2.CustomURLMapping
}
// FromDB fills up an OAuth2Config from serialized format.
func (cfg *OAuth2Config) FromDB(bs []byte) error {
return json.Unmarshal(bs, cfg)
}
// ToDB exports an SMTPConfig to a serialized format.
func (cfg *OAuth2Config) ToDB() ([]byte, error) {
return json.Marshal(cfg)
}
// LoginSource represents an external way for authorizing users.
type LoginSource struct {
ID int64 `xorm:"pk autoincr"`
Type LoginType
Name string `xorm:"UNIQUE"`
IsActived bool `xorm:"INDEX NOT NULL DEFAULT false"`
IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
Cfg core.Conversion `xorm:"TEXT"`
CreatedUnix util.TimeStamp `xorm:"INDEX created"`
UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
}
// Cell2Int64 converts a xorm.Cell type to int64,
// and handles possible irregular cases.
func Cell2Int64(val xorm.Cell) int64 {
switch (*val).(type) {
case []uint8:
log.Trace("Cell2Int64 ([]uint8): %v", *val)
return com.StrTo(string((*val).([]uint8))).MustInt64()
}
return (*val).(int64)
}
// BeforeSet is invoked from XORM before setting the value of a field of this object.
func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
switch colName {
case "type":
switch LoginType(Cell2Int64(val)) {
case LoginLDAP, LoginDLDAP:
source.Cfg = new(LDAPConfig)
case LoginSMTP:
source.Cfg = new(SMTPConfig)
case LoginPAM:
source.Cfg = new(PAMConfig)
case LoginOAuth2:
source.Cfg = new(OAuth2Config)
default:
panic("unrecognized login source type: " + com.ToStr(*val))
}
}
}
// TypeName return name of this login source type.
func (source *LoginSource) TypeName() string {
return LoginNames[source.Type]
}
// IsLDAP returns true of this source is of the LDAP type.
func (source *LoginSource) IsLDAP() bool {
return source.Type == LoginLDAP
}
// IsDLDAP returns true of this source is of the DLDAP type.
func (source *LoginSource) IsDLDAP() bool {
return source.Type == LoginDLDAP
}
// IsSMTP returns true of this source is of the SMTP type.
func (source *LoginSource) IsSMTP() bool {
return source.Type == LoginSMTP
}
// IsPAM returns true of this source is of the PAM type.
func (source *LoginSource) IsPAM() bool {
return source.Type == LoginPAM
}
// IsOAuth2 returns true of this source is of the OAuth2 type.
func (source *LoginSource) IsOAuth2() bool {
return source.Type == LoginOAuth2
}
// HasTLS returns true of this source supports TLS.
func (source *LoginSource) HasTLS() bool {
return ((source.IsLDAP() || source.IsDLDAP()) &&
source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
source.IsSMTP()
}
// UseTLS returns true of this source is configured to use TLS.
func (source *LoginSource) UseTLS() bool {
switch source.Type {
case LoginLDAP, LoginDLDAP:
return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
case LoginSMTP:
return source.SMTP().TLS
}
return false
}
// SkipVerify returns true if this source is configured to skip SSL
// verification.
func (source *LoginSource) SkipVerify() bool {
switch source.Type {
case LoginLDAP, LoginDLDAP:
return source.LDAP().SkipVerify
case LoginSMTP:
return source.SMTP().SkipVerify
}
return false
}
// LDAP returns LDAPConfig for this source, if of LDAP type.
func (source *LoginSource) LDAP() *LDAPConfig {
return source.Cfg.(*LDAPConfig)
}
// SMTP returns SMTPConfig for this source, if of SMTP type.
func (source *LoginSource) SMTP() *SMTPConfig {
return source.Cfg.(*SMTPConfig)
}
// PAM returns PAMConfig for this source, if of PAM type.
func (source *LoginSource) PAM() *PAMConfig {
return source.Cfg.(*PAMConfig)
}
// OAuth2 returns OAuth2Config for this source, if of OAuth2 type.
func (source *LoginSource) OAuth2() *OAuth2Config {
return source.Cfg.(*OAuth2Config)
}
// CreateLoginSource inserts a LoginSource in the DB if not already
// existing with the given name.
func CreateLoginSource(source *LoginSource) error {
has, err := x.Get(&LoginSource{Name: source.Name})
if err != nil {
return err
} else if has {
return ErrLoginSourceAlreadyExist{source.Name}
}
// Synchronization is only aviable with LDAP for now
if !source.IsLDAP() {
source.IsSyncEnabled = false
}
_, err = x.Insert(source)
if err == nil && source.IsOAuth2() && source.IsActived {
oAuth2Config := source.OAuth2()
err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
if err != nil {
// remove the LoginSource in case of errors while registering OAuth2 providers
x.Delete(source)
}
}
return err
}
// LoginSources returns a slice of all login sources found in DB.
func LoginSources() ([]*LoginSource, error) {
auths := make([]*LoginSource, 0, 6)
return auths, x.Find(&auths)
}
// GetLoginSourceByID returns login source by given ID.
func GetLoginSourceByID(id int64) (*LoginSource, error) {
source := new(LoginSource)
has, err := x.ID(id).Get(source)
if err != nil {
return nil, err
} else if !has {
return nil, ErrLoginSourceNotExist{id}
}
return source, nil
}
// UpdateSource updates a LoginSource record in DB.
func UpdateSource(source *LoginSource) error {
var originalLoginSource *LoginSource
if source.IsOAuth2() {
// keep track of the original values so we can restore in case of errors while registering OAuth2 providers
var err error
if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
return err
}
}
_, err := x.ID(source.ID).AllCols().Update(source)
if err == nil && source.IsOAuth2() && source.IsActived {
oAuth2Config := source.OAuth2()
err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
if err != nil {
// restore original values since we cannot update the provider it self
x.ID(source.ID).AllCols().Update(originalLoginSource)
}
}
return err
}
// DeleteSource deletes a LoginSource record in DB.
func DeleteSource(source *LoginSource) error {
count, err := x.Count(&User{LoginSource: source.ID})
if err != nil {
return err
} else if count > 0 {
return ErrLoginSourceInUse{source.ID}
}
count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
if err != nil {
return err
} else if count > 0 {
return ErrLoginSourceInUse{source.ID}
}
if source.IsOAuth2() {
oauth2.RemoveProvider(source.Name)
}
_, err = x.ID(source.ID).Delete(new(LoginSource))
return err
}
// CountLoginSources returns number of login sources.
func CountLoginSources() int64 {
count, _ := x.Count(new(LoginSource))
return count
}
// .____ ________ _____ __________
// | | \______ \ / _ \\______ \
// | | | | \ / /_\ \| ___/
// | |___ | ` \/ | \ |
// |_______ \/_______ /\____|__ /____|
// \/ \/ \/
func composeFullName(firstname, surname, username string) string {
switch {
case len(firstname) == 0 && len(surname) == 0:
return username
case len(firstname) == 0:
return surname
case len(surname) == 0:
return firstname
default:
return firstname + " " + surname
}
}
// LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
// and create a local user if success when enabled.
func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
if sr == nil {
// User not in LDAP, do nothing
return nil, ErrUserNotExist{0, login, 0}
}
var isAttributeSSHPublicKeySet = len(strings.TrimSpace(source.LDAP().AttributeSSHPublicKey)) > 0
if !autoRegister {
if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
RewriteAllPublicKeys()
}
return user, nil
}
// Fallback.
if len(sr.Username) == 0 {
sr.Username = login
}
// Validate username make sure it satisfies requirement.
if binding.AlphaDashDotPattern.MatchString(sr.Username) {
return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", sr.Username)
}
if len(sr.Mail) == 0 {
sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
}
user = &User{
LowerName: strings.ToLower(sr.Username),
Name: sr.Username,
FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
Email: sr.Mail,
LoginType: source.Type,
LoginSource: source.ID,
LoginName: login,
IsActive: true,
IsAdmin: sr.IsAdmin,
}
err := CreateUser(user)
if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
RewriteAllPublicKeys()
}
return user, err
}
// _________ __________________________
// / _____/ / \__ ___/\______ \
// \_____ \ / \ / \| | | ___/
// / \/ Y \ | | |
// /_______ /\____|__ /____| |____|
// \/ \/
type smtpLoginAuth struct {
username, password string
}
func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte(auth.username), nil
}
func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(auth.username), nil
case "Password:":
return []byte(auth.password), nil
}
}
return nil, nil
}
// SMTP authentication type names.
const (
SMTPPlain = "PLAIN"
SMTPLogin = "LOGIN"
)
// SMTPAuths contains available SMTP authentication type names.
var SMTPAuths = []string{SMTPPlain, SMTPLogin}
// SMTPAuth performs an SMTP authentication.
func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
if err != nil {
return err
}
defer c.Close()
if err = c.Hello("gogs"); err != nil {
return err
}
if cfg.TLS {
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(&tls.Config{
InsecureSkipVerify: cfg.SkipVerify,
ServerName: cfg.Host,
}); err != nil {
return err
}
} else {
return errors.New("SMTP server unsupports TLS")
}
}
if ok, _ := c.Extension("AUTH"); ok {
return c.Auth(a)
}
return ErrUnsupportedLoginType
}
// LoginViaSMTP queries if login/password is valid against the SMTP,
// and create a local user if success when enabled.
func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
// Verify allowed domains.
if len(cfg.AllowedDomains) > 0 {
idx := strings.Index(login, "@")
if idx == -1 {
return nil, ErrUserNotExist{0, login, 0}
} else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
return nil, ErrUserNotExist{0, login, 0}
}
}
var auth smtp.Auth
if cfg.Auth == SMTPPlain {
auth = smtp.PlainAuth("", login, password, cfg.Host)
} else if cfg.Auth == SMTPLogin {
auth = &smtpLoginAuth{login, password}
} else {
return nil, errors.New("Unsupported SMTP auth type")
}
if err := SMTPAuth(auth, cfg); err != nil {
// Check standard error format first,
// then fallback to worse case.
tperr, ok := err.(*textproto.Error)
if (ok && tperr.Code == 535) ||
strings.Contains(err.Error(), "Username and Password not accepted") {
return nil, ErrUserNotExist{0, login, 0}
}
return nil, err
}
if !autoRegister {
return user, nil
}
username := login
idx := strings.Index(login, "@")
if idx > -1 {
username = login[:idx]
}
user = &User{
LowerName: strings.ToLower(username),
Name: strings.ToLower(username),
Email: login,
Passwd: password,
LoginType: LoginSMTP,
LoginSource: sourceID,
LoginName: login,
IsActive: true,
}
return user, CreateUser(user)
}
// __________ _____ _____
// \______ \/ _ \ / \
// | ___/ /_\ \ / \ / \
// | | / | \/ Y \
// |____| \____|__ /\____|__ /
// \/ \/
// LoginViaPAM queries if login/password is valid against the PAM,
// and create a local user if success when enabled.
func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
if strings.Contains(err.Error(), "Authentication failure") {
return nil, ErrUserNotExist{0, login, 0}
}
return nil, err
}
if !autoRegister {
return user, nil
}
user = &User{
LowerName: strings.ToLower(login),
Name: login,
Email: login,
Passwd: password,
LoginType: LoginPAM,
LoginSource: sourceID,
LoginName: login,
IsActive: true,
}
return user, CreateUser(user)
}
// ExternalUserLogin attempts a login using external source types.
func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
if !source.IsActived {
return nil, ErrLoginSourceNotActived
}
var err error
switch source.Type {
case LoginLDAP, LoginDLDAP:
user, err = LoginViaLDAP(user, login, password, source, autoRegister)
case LoginSMTP:
user, err = LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
case LoginPAM:
user, err = LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
default:
return nil, ErrUnsupportedLoginType
}
if err != nil {
return nil, err
}
if !user.IsActive {
return nil, ErrUserInactive{user.ID, user.Name}
} else if user.ProhibitLogin {
return nil, ErrUserProhibitLogin{user.ID, user.Name}
}
return user, nil
}
// UserSignIn validates user name and password.
func UserSignIn(username, password string) (*User, error) {
var user *User
if strings.Contains(username, "@") {
user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
// check same email
cnt, err := x.Count(user)
if err != nil {
return nil, err
}
if cnt > 1 {
return nil, ErrEmailAlreadyUsed{
Email: user.Email,
}
}
} else {
trimmedUsername := strings.TrimSpace(username)
if len(trimmedUsername) == 0 {
return nil, ErrUserNotExist{0, username, 0}
}
user = &User{LowerName: strings.ToLower(trimmedUsername)}
}
hasUser, err := x.Get(user)
if err != nil {
return nil, err
}
if hasUser {
switch user.LoginType {
case LoginNoType, LoginPlain, LoginOAuth2:
if user.IsPasswordSet() && user.ValidatePassword(password) {
if !user.IsActive {
return nil, ErrUserInactive{user.ID, user.Name}
} else if user.ProhibitLogin {
return nil, ErrUserProhibitLogin{user.ID, user.Name}
}
return user, nil
}
return nil, ErrUserNotExist{user.ID, user.Name, 0}
default:
var source LoginSource
hasSource, err := x.ID(user.LoginSource).Get(&source)
if err != nil {
return nil, err
} else if !hasSource {
return nil, ErrLoginSourceNotExist{user.LoginSource}
}
return ExternalUserLogin(user, user.LoginName, password, &source, false)
}
}
sources := make([]*LoginSource, 0, 5)
if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
return nil, err
}
for _, source := range sources {
if source.IsOAuth2() {
// don't try to authenticate against OAuth2 sources
continue
}
authUser, err := ExternalUserLogin(nil, username, password, source, true)
if err == nil {
return authUser, nil
}
log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
}
return nil, ErrUserNotExist{user.ID, user.Name, 0}
}
| models/login_source.go | 1 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.9950242638587952,
0.019001759588718414,
0.00016256983508355916,
0.000248792115598917,
0.11911115795373917
] |
{
"id": 0,
"code_window": [
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n",
"\tif !user.IsActive {\n",
"\t\treturn nil, ErrUserInactive{user.ID, user.Name}\n",
"\t} else if user.ProhibitLogin {\n",
"\t\treturn nil, ErrUserProhibitLogin{user.ID, user.Name}\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// WARN: DON'T check user.IsActive, that will be checked on reqSign so that\n",
"\t// user could be hint to resend confirm email.\n",
"\tif user.ProhibitLogin {\n"
],
"file_path": "models/login_source.go",
"type": "replace",
"edit_start_line_idx": 618
} | // OAuth 1.0 consumer implementation.
// See http://www.oauth.net and RFC 5849
//
// There are typically three parties involved in an OAuth exchange:
// (1) The "Service Provider" (e.g. Google, Twitter, NetFlix) who operates the
// service where the data resides.
// (2) The "End User" who owns that data, and wants to grant access to a third-party.
// (3) That third-party who wants access to the data (after first being authorized by
// the user). This third-party is referred to as the "Consumer" in OAuth
// terminology.
//
// This library is designed to help implement the third-party consumer by handling the
// low-level authentication tasks, and allowing for authenticated requests to the
// service provider on behalf of the user.
//
// Caveats:
// - Currently only supports HMAC and RSA signatures.
// - Currently only supports SHA1 and SHA256 hashes.
// - Currently only supports OAuth 1.0
//
// Overview of how to use this library:
// (1) First create a new Consumer instance with the NewConsumer function
// (2) Get a RequestToken, and "authorization url" from GetRequestTokenAndUrl()
// (3) Save the RequestToken, you will need it again in step 6.
// (4) Redirect the user to the "authorization url" from step 2, where they will
// authorize your access to the service provider.
// (5) Wait. You will be called back on the CallbackUrl that you provide, and you
// will recieve a "verification code".
// (6) Call AuthorizeToken() with the RequestToken from step 2 and the
// "verification code" from step 5.
// (7) You will get back an AccessToken. Save this for as long as you need access
// to the user's data, and treat it like a password; it is a secret.
// (8) You can now throw away the RequestToken from step 2, it is no longer
// necessary.
// (9) Call "MakeHttpClient" using the AccessToken from step 7 to get an
// HTTP client which can access protected resources.
package oauth
import (
"bytes"
"crypto"
"crypto/hmac"
cryptoRand "crypto/rand"
"crypto/rsa"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"mime/multipart"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const (
OAUTH_VERSION = "1.0"
SIGNATURE_METHOD_HMAC = "HMAC-"
SIGNATURE_METHOD_RSA = "RSA-"
HTTP_AUTH_HEADER = "Authorization"
OAUTH_HEADER = "OAuth "
BODY_HASH_PARAM = "oauth_body_hash"
CALLBACK_PARAM = "oauth_callback"
CONSUMER_KEY_PARAM = "oauth_consumer_key"
NONCE_PARAM = "oauth_nonce"
SESSION_HANDLE_PARAM = "oauth_session_handle"
SIGNATURE_METHOD_PARAM = "oauth_signature_method"
SIGNATURE_PARAM = "oauth_signature"
TIMESTAMP_PARAM = "oauth_timestamp"
TOKEN_PARAM = "oauth_token"
TOKEN_SECRET_PARAM = "oauth_token_secret"
VERIFIER_PARAM = "oauth_verifier"
VERSION_PARAM = "oauth_version"
)
var HASH_METHOD_MAP = map[crypto.Hash]string{
crypto.SHA1: "SHA1",
crypto.SHA256: "SHA256",
}
// TODO(mrjones) Do we definitely want separate "Request" and "Access" token classes?
// They're identical structurally, but used for different purposes.
type RequestToken struct {
Token string
Secret string
}
type AccessToken struct {
Token string
Secret string
AdditionalData map[string]string
}
type DataLocation int
const (
LOC_BODY DataLocation = iota + 1
LOC_URL
LOC_MULTIPART
LOC_JSON
LOC_XML
)
// Information about how to contact the service provider (see #1 above).
// You usually find all of these URLs by reading the documentation for the service
// that you're trying to connect to.
// Some common examples are:
// (1) Google, standard APIs:
// http://code.google.com/apis/accounts/docs/OAuth_ref.html
// - RequestTokenUrl: https://www.google.com/accounts/OAuthGetRequestToken
// - AuthorizeTokenUrl: https://www.google.com/accounts/OAuthAuthorizeToken
// - AccessTokenUrl: https://www.google.com/accounts/OAuthGetAccessToken
// Note: Some Google APIs (for example, Google Latitude) use different values for
// one or more of those URLs.
// (2) Twitter API:
// http://dev.twitter.com/pages/auth
// - RequestTokenUrl: http://api.twitter.com/oauth/request_token
// - AuthorizeTokenUrl: https://api.twitter.com/oauth/authorize
// - AccessTokenUrl: https://api.twitter.com/oauth/access_token
// (3) NetFlix API:
// http://developer.netflix.com/docs/Security
// - RequestTokenUrl: http://api.netflix.com/oauth/request_token
// - AuthroizeTokenUrl: https://api-user.netflix.com/oauth/login
// - AccessTokenUrl: http://api.netflix.com/oauth/access_token
// Set HttpMethod if the service provider requires a different HTTP method
// to be used for OAuth token requests
type ServiceProvider struct {
RequestTokenUrl string
AuthorizeTokenUrl string
AccessTokenUrl string
HttpMethod string
BodyHash bool
IgnoreTimestamp bool
// Enables non spec-compliant behavior:
// Allow parameters to be passed in the query string rather
// than the body.
// See https://github.com/mrjones/oauth/pull/63
SignQueryParams bool
}
func (sp *ServiceProvider) httpMethod() string {
if sp.HttpMethod != "" {
return sp.HttpMethod
}
return "GET"
}
// lockedNonceGenerator wraps a non-reentrant random number generator with a
// lock
type lockedNonceGenerator struct {
nonceGenerator nonceGenerator
lock sync.Mutex
}
func newLockedNonceGenerator(c clock) *lockedNonceGenerator {
return &lockedNonceGenerator{
nonceGenerator: rand.New(rand.NewSource(c.Nanos())),
}
}
func (n *lockedNonceGenerator) Int63() int64 {
n.lock.Lock()
r := n.nonceGenerator.Int63()
n.lock.Unlock()
return r
}
// Consumers are stateless, you can call the various methods (GetRequestTokenAndUrl,
// AuthorizeToken, and Get) on various different instances of Consumers *as long as
// they were set up in the same way.* It is up to you, as the caller to persist the
// necessary state (RequestTokens and AccessTokens).
type Consumer struct {
// Some ServiceProviders require extra parameters to be passed for various reasons.
// For example Google APIs require you to set a scope= parameter to specify how much
// access is being granted. The proper values for scope= depend on the service:
// For more, see: http://code.google.com/apis/accounts/docs/OAuth.html#prepScope
AdditionalParams map[string]string
// The rest of this class is configured via the NewConsumer function.
consumerKey string
serviceProvider ServiceProvider
// Some APIs (e.g. Netflix) aren't quite standard OAuth, and require passing
// additional parameters when authorizing the request token. For most APIs
// this field can be ignored. For Netflix, do something like:
// consumer.AdditionalAuthorizationUrlParams = map[string]string{
// "application_name": "YourAppName",
// "oauth_consumer_key": "YourConsumerKey",
// }
AdditionalAuthorizationUrlParams map[string]string
debug bool
// Defaults to http.Client{}, can be overridden (e.g. for testing) as necessary
HttpClient HttpClient
// Some APIs (e.g. Intuit/Quickbooks) require sending additional headers along with
// requests. (like "Accept" to specify the response type as XML or JSON) Note that this
// will only *add* headers, not set existing ones.
AdditionalHeaders map[string][]string
// Private seams for mocking dependencies when testing
clock clock
// Seeded generators are not reentrant
nonceGenerator nonceGenerator
signer signer
}
func newConsumer(consumerKey string, serviceProvider ServiceProvider, httpClient *http.Client) *Consumer {
clock := &defaultClock{}
if httpClient == nil {
httpClient = &http.Client{}
}
return &Consumer{
consumerKey: consumerKey,
serviceProvider: serviceProvider,
clock: clock,
HttpClient: httpClient,
nonceGenerator: newLockedNonceGenerator(clock),
AdditionalParams: make(map[string]string),
AdditionalAuthorizationUrlParams: make(map[string]string),
}
}
// Creates a new Consumer instance, with a HMAC-SHA1 signer
// - consumerKey and consumerSecret:
// values you should obtain from the ServiceProvider when you register your
// application.
//
// - serviceProvider:
// see the documentation for ServiceProvider for how to create this.
//
func NewConsumer(consumerKey string, consumerSecret string,
serviceProvider ServiceProvider) *Consumer {
consumer := newConsumer(consumerKey, serviceProvider, nil)
consumer.signer = &HMACSigner{
consumerSecret: consumerSecret,
hashFunc: crypto.SHA1,
}
return consumer
}
// Creates a new Consumer instance, with a HMAC-SHA1 signer
// - consumerKey and consumerSecret:
// values you should obtain from the ServiceProvider when you register your
// application.
//
// - serviceProvider:
// see the documentation for ServiceProvider for how to create this.
//
// - httpClient:
// Provides a custom implementation of the httpClient used under the hood
// to make the request. This is especially useful if you want to use
// Google App Engine.
//
func NewCustomHttpClientConsumer(consumerKey string, consumerSecret string,
serviceProvider ServiceProvider, httpClient *http.Client) *Consumer {
consumer := newConsumer(consumerKey, serviceProvider, httpClient)
consumer.signer = &HMACSigner{
consumerSecret: consumerSecret,
hashFunc: crypto.SHA1,
}
return consumer
}
// Creates a new Consumer instance, with a HMAC signer
// - consumerKey and consumerSecret:
// values you should obtain from the ServiceProvider when you register your
// application.
//
// - hashFunc:
// the crypto.Hash to use for signatures
//
// - serviceProvider:
// see the documentation for ServiceProvider for how to create this.
//
// - httpClient:
// Provides a custom implementation of the httpClient used under the hood
// to make the request. This is especially useful if you want to use
// Google App Engine. Can be nil for default.
//
func NewCustomConsumer(consumerKey string, consumerSecret string,
hashFunc crypto.Hash, serviceProvider ServiceProvider,
httpClient *http.Client) *Consumer {
consumer := newConsumer(consumerKey, serviceProvider, httpClient)
consumer.signer = &HMACSigner{
consumerSecret: consumerSecret,
hashFunc: hashFunc,
}
return consumer
}
// Creates a new Consumer instance, with a RSA-SHA1 signer
// - consumerKey:
// value you should obtain from the ServiceProvider when you register your
// application.
//
// - privateKey:
// the private key to use for signatures
//
// - serviceProvider:
// see the documentation for ServiceProvider for how to create this.
//
func NewRSAConsumer(consumerKey string, privateKey *rsa.PrivateKey,
serviceProvider ServiceProvider) *Consumer {
consumer := newConsumer(consumerKey, serviceProvider, nil)
consumer.signer = &RSASigner{
privateKey: privateKey,
hashFunc: crypto.SHA1,
rand: cryptoRand.Reader,
}
return consumer
}
// Creates a new Consumer instance, with a RSA signer
// - consumerKey:
// value you should obtain from the ServiceProvider when you register your
// application.
//
// - privateKey:
// the private key to use for signatures
//
// - hashFunc:
// the crypto.Hash to use for signatures
//
// - serviceProvider:
// see the documentation for ServiceProvider for how to create this.
//
// - httpClient:
// Provides a custom implementation of the httpClient used under the hood
// to make the request. This is especially useful if you want to use
// Google App Engine. Can be nil for default.
//
func NewCustomRSAConsumer(consumerKey string, privateKey *rsa.PrivateKey,
hashFunc crypto.Hash, serviceProvider ServiceProvider,
httpClient *http.Client) *Consumer {
consumer := newConsumer(consumerKey, serviceProvider, httpClient)
consumer.signer = &RSASigner{
privateKey: privateKey,
hashFunc: hashFunc,
rand: cryptoRand.Reader,
}
return consumer
}
// Kicks off the OAuth authorization process.
// - callbackUrl:
// Authorizing a token *requires* redirecting to the service provider. This is the
// URL which the service provider will redirect the user back to after that
// authorization is completed. The service provider will pass back a verification
// code which is necessary to complete the rest of the process (in AuthorizeToken).
// Notes on callbackUrl:
// - Some (all?) service providers allow for setting "oob" (for out-of-band) as a
// callback url. If this is set the service provider will present the
// verification code directly to the user, and you must provide a place for
// them to copy-and-paste it into.
// - Otherwise, the user will be redirected to callbackUrl in the browser, and
// will append a "oauth_verifier=<verifier>" parameter.
//
// This function returns:
// - rtoken:
// A temporary RequestToken, used during the authorization process. You must save
// this since it will be necessary later in the process when calling
// AuthorizeToken().
//
// - url:
// A URL that you should redirect the user to in order that they may authorize you
// to the service provider.
//
// - err:
// Set only if there was an error, nil otherwise.
func (c *Consumer) GetRequestTokenAndUrl(callbackUrl string) (rtoken *RequestToken, loginUrl string, err error) {
return c.GetRequestTokenAndUrlWithParams(callbackUrl, c.AdditionalParams)
}
func (c *Consumer) GetRequestTokenAndUrlWithParams(callbackUrl string, additionalParams map[string]string) (rtoken *RequestToken, loginUrl string, err error) {
params := c.baseParams(c.consumerKey, additionalParams)
if callbackUrl != "" {
params.Add(CALLBACK_PARAM, callbackUrl)
}
req := &request{
method: c.serviceProvider.httpMethod(),
url: c.serviceProvider.RequestTokenUrl,
oauthParams: params,
}
if _, err := c.signRequest(req, ""); err != nil { // We don't have a token secret for the key yet
return nil, "", err
}
resp, err := c.getBody(c.serviceProvider.httpMethod(), c.serviceProvider.RequestTokenUrl, params)
if err != nil {
return nil, "", errors.New("getBody: " + err.Error())
}
requestToken, err := parseRequestToken(*resp)
if err != nil {
return nil, "", errors.New("parseRequestToken: " + err.Error())
}
loginParams := make(url.Values)
for k, v := range c.AdditionalAuthorizationUrlParams {
loginParams.Set(k, v)
}
loginParams.Set(TOKEN_PARAM, requestToken.Token)
loginUrl = c.serviceProvider.AuthorizeTokenUrl + "?" + loginParams.Encode()
return requestToken, loginUrl, nil
}
// After the user has authorized you to the service provider, use this method to turn
// your temporary RequestToken into a permanent AccessToken. You must pass in two values:
// - rtoken:
// The RequestToken returned from GetRequestTokenAndUrl()
//
// - verificationCode:
// The string which passed back from the server, either as the oauth_verifier
// query param appended to callbackUrl *OR* a string manually entered by the user
// if callbackUrl is "oob"
//
// It will return:
// - atoken:
// A permanent AccessToken which can be used to access the user's data (until it is
// revoked by the user or the service provider).
//
// - err:
// Set only if there was an error, nil otherwise.
func (c *Consumer) AuthorizeToken(rtoken *RequestToken, verificationCode string) (atoken *AccessToken, err error) {
return c.AuthorizeTokenWithParams(rtoken, verificationCode, c.AdditionalParams)
}
func (c *Consumer) AuthorizeTokenWithParams(rtoken *RequestToken, verificationCode string, additionalParams map[string]string) (atoken *AccessToken, err error) {
params := map[string]string{
TOKEN_PARAM: rtoken.Token,
}
if verificationCode != "" {
params[VERIFIER_PARAM] = verificationCode
}
return c.makeAccessTokenRequestWithParams(params, rtoken.Secret, additionalParams)
}
// Use the service provider to refresh the AccessToken for a given session.
// Note that this is only supported for service providers that manage an
// authorization session (e.g. Yahoo).
//
// Most providers do not return the SESSION_HANDLE_PARAM needed to refresh
// the token.
//
// See http://oauth.googlecode.com/svn/spec/ext/session/1.0/drafts/1/spec.html
// for more information.
// - accessToken:
// The AccessToken returned from AuthorizeToken()
//
// It will return:
// - atoken:
// An AccessToken which can be used to access the user's data (until it is
// revoked by the user or the service provider).
//
// - err:
// Set if accessToken does not contain the SESSION_HANDLE_PARAM needed to
// refresh the token, or if an error occurred when making the request.
func (c *Consumer) RefreshToken(accessToken *AccessToken) (atoken *AccessToken, err error) {
params := make(map[string]string)
sessionHandle, ok := accessToken.AdditionalData[SESSION_HANDLE_PARAM]
if !ok {
return nil, errors.New("Missing " + SESSION_HANDLE_PARAM + " in access token.")
}
params[SESSION_HANDLE_PARAM] = sessionHandle
params[TOKEN_PARAM] = accessToken.Token
return c.makeAccessTokenRequest(params, accessToken.Secret)
}
// Use the service provider to obtain an AccessToken for a given session
// - params:
// The access token request paramters.
//
// - secret:
// Secret key to use when signing the access token request.
//
// It will return:
// - atoken
// An AccessToken which can be used to access the user's data (until it is
// revoked by the user or the service provider).
//
// - err:
// Set only if there was an error, nil otherwise.
func (c *Consumer) makeAccessTokenRequest(params map[string]string, secret string) (atoken *AccessToken, err error) {
return c.makeAccessTokenRequestWithParams(params, secret, c.AdditionalParams)
}
func (c *Consumer) makeAccessTokenRequestWithParams(params map[string]string, secret string, additionalParams map[string]string) (atoken *AccessToken, err error) {
orderedParams := c.baseParams(c.consumerKey, additionalParams)
for key, value := range params {
orderedParams.Add(key, value)
}
req := &request{
method: c.serviceProvider.httpMethod(),
url: c.serviceProvider.AccessTokenUrl,
oauthParams: orderedParams,
}
if _, err := c.signRequest(req, secret); err != nil {
return nil, err
}
resp, err := c.getBody(c.serviceProvider.httpMethod(), c.serviceProvider.AccessTokenUrl, orderedParams)
if err != nil {
return nil, err
}
return parseAccessToken(*resp)
}
type RoundTripper struct {
consumer *Consumer
token *AccessToken
}
func (c *Consumer) MakeRoundTripper(token *AccessToken) (*RoundTripper, error) {
return &RoundTripper{consumer: c, token: token}, nil
}
func (c *Consumer) MakeHttpClient(token *AccessToken) (*http.Client, error) {
return &http.Client{
Transport: &RoundTripper{consumer: c, token: token},
}, nil
}
// ** DEPRECATED **
// Please call Get on the http client returned by MakeHttpClient instead!
//
// Executes an HTTP Get, authorized via the AccessToken.
// - url:
// The base url, without any query params, which is being accessed
//
// - userParams:
// Any key=value params to be included in the query string
//
// - token:
// The AccessToken returned by AuthorizeToken()
//
// This method returns:
// - resp:
// The HTTP Response resulting from making this request.
//
// - err:
// Set only if there was an error, nil otherwise.
func (c *Consumer) Get(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
return c.makeAuthorizedRequest("GET", url, LOC_URL, "", userParams, token)
}
func encodeUserParams(userParams map[string]string) string {
data := url.Values{}
for k, v := range userParams {
data.Add(k, v)
}
return data.Encode()
}
// ** DEPRECATED **
// Please call "Post" on the http client returned by MakeHttpClient instead
func (c *Consumer) PostForm(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
return c.PostWithBody(url, "", userParams, token)
}
// ** DEPRECATED **
// Please call "Post" on the http client returned by MakeHttpClient instead
func (c *Consumer) Post(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
return c.PostWithBody(url, "", userParams, token)
}
// ** DEPRECATED **
// Please call "Post" on the http client returned by MakeHttpClient instead
func (c *Consumer) PostWithBody(url string, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
return c.makeAuthorizedRequest("POST", url, LOC_BODY, body, userParams, token)
}
// ** DEPRECATED **
// Please call "Do" on the http client returned by MakeHttpClient instead
// (and set the "Content-Type" header explicitly in the http.Request)
func (c *Consumer) PostJson(url string, body string, token *AccessToken) (resp *http.Response, err error) {
return c.makeAuthorizedRequest("POST", url, LOC_JSON, body, nil, token)
}
// ** DEPRECATED **
// Please call "Do" on the http client returned by MakeHttpClient instead
// (and set the "Content-Type" header explicitly in the http.Request)
func (c *Consumer) PostXML(url string, body string, token *AccessToken) (resp *http.Response, err error) {
return c.makeAuthorizedRequest("POST", url, LOC_XML, body, nil, token)
}
// ** DEPRECATED **
// Please call "Do" on the http client returned by MakeHttpClient instead
// (and setup the multipart data explicitly in the http.Request)
func (c *Consumer) PostMultipart(url, multipartName string, multipartData io.ReadCloser, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
return c.makeAuthorizedRequestReader("POST", url, LOC_MULTIPART, 0, multipartName, multipartData, userParams, token)
}
// ** DEPRECATED **
// Please call "Delete" on the http client returned by MakeHttpClient instead
func (c *Consumer) Delete(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
return c.makeAuthorizedRequest("DELETE", url, LOC_URL, "", userParams, token)
}
// ** DEPRECATED **
// Please call "Put" on the http client returned by MakeHttpClient instead
func (c *Consumer) Put(url string, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
return c.makeAuthorizedRequest("PUT", url, LOC_URL, body, userParams, token)
}
func (c *Consumer) Debug(enabled bool) {
c.debug = enabled
c.signer.Debug(enabled)
}
type pair struct {
key string
value string
}
type pairs []pair
func (p pairs) Len() int { return len(p) }
func (p pairs) Less(i, j int) bool { return p[i].key < p[j].key }
func (p pairs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// This function has basically turned into a backwards compatibility layer
// between the old API (where clients explicitly called consumer.Get()
// consumer.Post() etc), and the new API (which takes actual http.Requests)
//
// So, here we construct the appropriate HTTP request for the inputs.
func (c *Consumer) makeAuthorizedRequestReader(method string, urlString string, dataLocation DataLocation, contentLength int, multipartName string, body io.ReadCloser, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
urlObject, err := url.Parse(urlString)
if err != nil {
return nil, err
}
request := &http.Request{
Method: method,
URL: urlObject,
Header: http.Header{},
Body: body,
ContentLength: int64(contentLength),
}
vals := url.Values{}
for k, v := range userParams {
vals.Add(k, v)
}
if dataLocation != LOC_BODY {
request.URL.RawQuery = vals.Encode()
request.URL.RawQuery = strings.Replace(
request.URL.RawQuery, ";", "%3B", -1)
} else {
// TODO(mrjones): validate that we're not overrideing an exising body?
request.ContentLength = int64(len(vals.Encode()))
if request.ContentLength == 0 {
request.Body = nil
} else {
request.Body = ioutil.NopCloser(strings.NewReader(vals.Encode()))
}
}
for k, vs := range c.AdditionalHeaders {
for _, v := range vs {
request.Header.Set(k, v)
}
}
if dataLocation == LOC_BODY {
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
if dataLocation == LOC_JSON {
request.Header.Set("Content-Type", "application/json")
}
if dataLocation == LOC_XML {
request.Header.Set("Content-Type", "application/xml")
}
if dataLocation == LOC_MULTIPART {
pipeReader, pipeWriter := io.Pipe()
writer := multipart.NewWriter(pipeWriter)
if request.URL.Host == "www.mrjon.es" &&
request.URL.Path == "/unittest" {
writer.SetBoundary("UNITTESTBOUNDARY")
}
go func(body io.Reader) {
part, err := writer.CreateFormFile(multipartName, "/no/matter")
if err != nil {
writer.Close()
pipeWriter.CloseWithError(err)
return
}
_, err = io.Copy(part, body)
if err != nil {
writer.Close()
pipeWriter.CloseWithError(err)
return
}
writer.Close()
pipeWriter.Close()
}(body)
request.Body = pipeReader
request.Header.Set("Content-Type", writer.FormDataContentType())
}
rt := RoundTripper{consumer: c, token: token}
resp, err = rt.RoundTrip(request)
if err != nil {
return resp, err
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body)
return resp, HTTPExecuteError{
RequestHeaders: "",
ResponseBodyBytes: bytes,
Status: resp.Status,
StatusCode: resp.StatusCode,
}
}
return resp, nil
}
// cloneReq clones the src http.Request, making deep copies of the Header and
// the URL but shallow copies of everything else
func cloneReq(src *http.Request) *http.Request {
dst := &http.Request{}
*dst = *src
dst.Header = make(http.Header, len(src.Header))
for k, s := range src.Header {
dst.Header[k] = append([]string(nil), s...)
}
if src.URL != nil {
dst.URL = cloneURL(src.URL)
}
return dst
}
// cloneURL shallow clones the src *url.URL
func cloneURL(src *url.URL) *url.URL {
dst := &url.URL{}
*dst = *src
return dst
}
func canonicalizeUrl(u *url.URL) string {
var buf bytes.Buffer
buf.WriteString(u.Scheme)
buf.WriteString("://")
buf.WriteString(u.Host)
buf.WriteString(u.Path)
return buf.String()
}
func getBody(request *http.Request) ([]byte, error) {
if request.Body == nil {
return nil, nil
}
defer request.Body.Close()
originalBody, err := ioutil.ReadAll(request.Body)
if err != nil {
return nil, err
}
// We have to re-install the body (because we've ruined it by reading it).
if len(originalBody) > 0 {
request.Body = ioutil.NopCloser(bytes.NewReader(originalBody))
} else {
request.Body = nil
}
return originalBody, nil
}
func parseBody(request *http.Request) (map[string]string, error) {
userParams := map[string]string{}
// TODO(mrjones): factor parameter extraction into a separate method
if request.Header.Get("Content-Type") !=
"application/x-www-form-urlencoded" {
// Most of the time we get parameters from the query string:
for k, vs := range request.URL.Query() {
if len(vs) != 1 {
return nil, fmt.Errorf("Must have exactly one value per param")
}
userParams[k] = vs[0]
}
} else {
// x-www-form-urlencoded parameters come from the body instead:
body, err := getBody(request)
if err != nil {
return nil, err
}
params, err := url.ParseQuery(string(body))
if err != nil {
return nil, err
}
for k, vs := range params {
if len(vs) != 1 {
return nil, fmt.Errorf("Must have exactly one value per param")
}
userParams[k] = vs[0]
}
}
return userParams, nil
}
func paramsToSortedPairs(params map[string]string) pairs {
// Sort parameters alphabetically
paramPairs := make(pairs, len(params))
i := 0
for key, value := range params {
paramPairs[i] = pair{key: key, value: value}
i++
}
sort.Sort(paramPairs)
return paramPairs
}
func calculateBodyHash(request *http.Request, s signer) (string, error) {
if request.Header.Get("Content-Type") ==
"application/x-www-form-urlencoded" {
return "", nil
}
var body []byte
if request.Body != nil {
var err error
body, err = getBody(request)
if err != nil {
return "", err
}
}
h := s.HashFunc().New()
h.Write(body)
rawSignature := h.Sum(nil)
return base64.StdEncoding.EncodeToString(rawSignature), nil
}
func (rt *RoundTripper) RoundTrip(userRequest *http.Request) (*http.Response, error) {
serverRequest := cloneReq(userRequest)
allParams := rt.consumer.baseParams(
rt.consumer.consumerKey, rt.consumer.AdditionalParams)
// Do not add the "oauth_token" parameter, if the access token has not been
// specified. By omitting this parameter when it is not specified, allows
// two-legged OAuth calls.
if len(rt.token.Token) > 0 {
allParams.Add(TOKEN_PARAM, rt.token.Token)
}
if rt.consumer.serviceProvider.BodyHash {
bodyHash, err := calculateBodyHash(serverRequest, rt.consumer.signer)
if err != nil {
return nil, err
}
if bodyHash != "" {
allParams.Add(BODY_HASH_PARAM, bodyHash)
}
}
authParams := allParams.Clone()
// TODO(mrjones): put these directly into the paramPairs below?
userParams, err := parseBody(serverRequest)
if err != nil {
return nil, err
}
paramPairs := paramsToSortedPairs(userParams)
for i := range paramPairs {
allParams.Add(paramPairs[i].key, paramPairs[i].value)
}
signingURL := cloneURL(serverRequest.URL)
if host := serverRequest.Host; host != "" {
signingURL.Host = host
}
baseString := rt.consumer.requestString(serverRequest.Method, canonicalizeUrl(signingURL), allParams)
signature, err := rt.consumer.signer.Sign(baseString, rt.token.Secret)
if err != nil {
return nil, err
}
authParams.Add(SIGNATURE_PARAM, signature)
// Set auth header.
oauthHdr := OAUTH_HEADER
for pos, key := range authParams.Keys() {
for innerPos, value := range authParams.Get(key) {
if pos+innerPos > 0 {
oauthHdr += ","
}
oauthHdr += key + "=\"" + value + "\""
}
}
serverRequest.Header.Add(HTTP_AUTH_HEADER, oauthHdr)
if rt.consumer.debug {
fmt.Printf("Request: %v\n", serverRequest)
}
resp, err := rt.consumer.HttpClient.Do(serverRequest)
if err != nil {
return resp, err
}
return resp, nil
}
func (c *Consumer) makeAuthorizedRequest(method string, url string, dataLocation DataLocation, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
return c.makeAuthorizedRequestReader(method, url, dataLocation, len(body), "", ioutil.NopCloser(strings.NewReader(body)), userParams, token)
}
type request struct {
method string
url string
oauthParams *OrderedParams
userParams map[string]string
}
type HttpClient interface {
Do(req *http.Request) (resp *http.Response, err error)
}
type clock interface {
Seconds() int64
Nanos() int64
}
type nonceGenerator interface {
Int63() int64
}
type key interface {
String() string
}
type signer interface {
Sign(message string, tokenSecret string) (string, error)
Verify(message string, signature string) error
SignatureMethod() string
HashFunc() crypto.Hash
Debug(enabled bool)
}
type defaultClock struct{}
func (*defaultClock) Seconds() int64 {
return time.Now().Unix()
}
func (*defaultClock) Nanos() int64 {
return time.Now().UnixNano()
}
func (c *Consumer) signRequest(req *request, tokenSecret string) (*request, error) {
baseString := c.requestString(req.method, req.url, req.oauthParams)
signature, err := c.signer.Sign(baseString, tokenSecret)
if err != nil {
return nil, err
}
req.oauthParams.Add(SIGNATURE_PARAM, signature)
return req, nil
}
// Obtains an AccessToken from the response of a service provider.
// - data:
// The response body.
//
// This method returns:
// - atoken:
// The AccessToken generated from the response body.
//
// - err:
// Set if an AccessToken could not be parsed from the given input.
func parseAccessToken(data string) (atoken *AccessToken, err error) {
parts, err := url.ParseQuery(data)
if err != nil {
return nil, err
}
tokenParam := parts[TOKEN_PARAM]
parts.Del(TOKEN_PARAM)
if len(tokenParam) < 1 {
return nil, errors.New("Missing " + TOKEN_PARAM + " in response. " +
"Full response body: '" + data + "'")
}
tokenSecretParam := parts[TOKEN_SECRET_PARAM]
parts.Del(TOKEN_SECRET_PARAM)
if len(tokenSecretParam) < 1 {
return nil, errors.New("Missing " + TOKEN_SECRET_PARAM + " in response." +
"Full response body: '" + data + "'")
}
additionalData := parseAdditionalData(parts)
return &AccessToken{tokenParam[0], tokenSecretParam[0], additionalData}, nil
}
func parseRequestToken(data string) (*RequestToken, error) {
parts, err := url.ParseQuery(data)
if err != nil {
return nil, err
}
tokenParam := parts[TOKEN_PARAM]
if len(tokenParam) < 1 {
return nil, errors.New("Missing " + TOKEN_PARAM + " in response. " +
"Full response body: '" + data + "'")
}
tokenSecretParam := parts[TOKEN_SECRET_PARAM]
if len(tokenSecretParam) < 1 {
return nil, errors.New("Missing " + TOKEN_SECRET_PARAM + " in response." +
"Full response body: '" + data + "'")
}
return &RequestToken{tokenParam[0], tokenSecretParam[0]}, nil
}
func (c *Consumer) baseParams(consumerKey string, additionalParams map[string]string) *OrderedParams {
params := NewOrderedParams()
params.Add(VERSION_PARAM, OAUTH_VERSION)
params.Add(SIGNATURE_METHOD_PARAM, c.signer.SignatureMethod())
params.Add(TIMESTAMP_PARAM, strconv.FormatInt(c.clock.Seconds(), 10))
params.Add(NONCE_PARAM, strconv.FormatInt(c.nonceGenerator.Int63(), 10))
params.Add(CONSUMER_KEY_PARAM, consumerKey)
for key, value := range additionalParams {
params.Add(key, value)
}
return params
}
func parseAdditionalData(parts url.Values) map[string]string {
params := make(map[string]string)
for key, value := range parts {
if len(value) > 0 {
params[key] = value[0]
}
}
return params
}
type HMACSigner struct {
consumerSecret string
hashFunc crypto.Hash
debug bool
}
func (s *HMACSigner) Debug(enabled bool) {
s.debug = enabled
}
func (s *HMACSigner) Sign(message string, tokenSecret string) (string, error) {
key := escape(s.consumerSecret) + "&" + escape(tokenSecret)
if s.debug {
fmt.Println("Signing:", message)
fmt.Println("Key:", key)
}
h := hmac.New(s.HashFunc().New, []byte(key))
h.Write([]byte(message))
rawSignature := h.Sum(nil)
base64signature := base64.StdEncoding.EncodeToString(rawSignature)
if s.debug {
fmt.Println("Base64 signature:", base64signature)
}
return base64signature, nil
}
func (s *HMACSigner) Verify(message string, signature string) error {
if s.debug {
fmt.Println("Verifying Base64 signature:", signature)
}
validSignature, err := s.Sign(message, "")
if err != nil {
return err
}
if validSignature != signature {
decodedSigniture, _ := url.QueryUnescape(signature)
if validSignature != decodedSigniture {
return fmt.Errorf("signature did not match")
}
}
return nil
}
func (s *HMACSigner) SignatureMethod() string {
return SIGNATURE_METHOD_HMAC + HASH_METHOD_MAP[s.HashFunc()]
}
func (s *HMACSigner) HashFunc() crypto.Hash {
return s.hashFunc
}
type RSASigner struct {
debug bool
rand io.Reader
privateKey *rsa.PrivateKey
hashFunc crypto.Hash
}
func (s *RSASigner) Debug(enabled bool) {
s.debug = enabled
}
func (s *RSASigner) Sign(message string, tokenSecret string) (string, error) {
if s.debug {
fmt.Println("Signing:", message)
}
h := s.HashFunc().New()
h.Write([]byte(message))
digest := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(s.rand, s.privateKey, s.HashFunc(), digest)
if err != nil {
return "", nil
}
base64signature := base64.StdEncoding.EncodeToString(signature)
if s.debug {
fmt.Println("Base64 signature:", base64signature)
}
return base64signature, nil
}
func (s *RSASigner) Verify(message string, base64signature string) error {
if s.debug {
fmt.Println("Verifying:", message)
fmt.Println("Verifying Base64 signature:", base64signature)
}
h := s.HashFunc().New()
h.Write([]byte(message))
digest := h.Sum(nil)
signature, err := base64.StdEncoding.DecodeString(base64signature)
if err != nil {
return err
}
return rsa.VerifyPKCS1v15(&s.privateKey.PublicKey, s.HashFunc(), digest, signature)
}
func (s *RSASigner) SignatureMethod() string {
return SIGNATURE_METHOD_RSA + HASH_METHOD_MAP[s.HashFunc()]
}
func (s *RSASigner) HashFunc() crypto.Hash {
return s.hashFunc
}
func escape(s string) string {
t := make([]byte, 0, 3*len(s))
for i := 0; i < len(s); i++ {
c := s[i]
if isEscapable(c) {
t = append(t, '%')
t = append(t, "0123456789ABCDEF"[c>>4])
t = append(t, "0123456789ABCDEF"[c&15])
} else {
t = append(t, s[i])
}
}
return string(t)
}
func isEscapable(b byte) bool {
return !('A' <= b && b <= 'Z' || 'a' <= b && b <= 'z' || '0' <= b && b <= '9' || b == '-' || b == '.' || b == '_' || b == '~')
}
func (c *Consumer) requestString(method string, url string, params *OrderedParams) string {
result := method + "&" + escape(url)
for pos, key := range params.Keys() {
for innerPos, value := range params.Get(key) {
if pos+innerPos == 0 {
result += "&"
} else {
result += escape("&")
}
result += escape(fmt.Sprintf("%s=%s", key, value))
}
}
return result
}
func (c *Consumer) getBody(method, url string, oauthParams *OrderedParams) (*string, error) {
resp, err := c.httpExecute(method, url, "", 0, nil, oauthParams)
if err != nil {
return nil, errors.New("httpExecute: " + err.Error())
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, errors.New("ReadAll: " + err.Error())
}
bodyStr := string(bodyBytes)
if c.debug {
fmt.Printf("STATUS: %d %s\n", resp.StatusCode, resp.Status)
fmt.Println("BODY RESPONSE: " + bodyStr)
}
return &bodyStr, nil
}
// HTTPExecuteError signals that a call to httpExecute failed.
type HTTPExecuteError struct {
// RequestHeaders provides a stringified listing of request headers.
RequestHeaders string
// ResponseBodyBytes is the response read into a byte slice.
ResponseBodyBytes []byte
// Status is the status code string response.
Status string
// StatusCode is the parsed status code.
StatusCode int
}
// Error provides a printable string description of an HTTPExecuteError.
func (e HTTPExecuteError) Error() string {
return "HTTP response is not 200/OK as expected. Actual response: \n" +
"\tResponse Status: '" + e.Status + "'\n" +
"\tResponse Code: " + strconv.Itoa(e.StatusCode) + "\n" +
"\tResponse Body: " + string(e.ResponseBodyBytes) + "\n" +
"\tRequest Headers: " + e.RequestHeaders
}
func (c *Consumer) httpExecute(
method string, urlStr string, contentType string, contentLength int, body io.Reader, oauthParams *OrderedParams) (*http.Response, error) {
// Create base request.
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
return nil, errors.New("NewRequest failed: " + err.Error())
}
// Set auth header.
req.Header = http.Header{}
oauthHdr := "OAuth "
for pos, key := range oauthParams.Keys() {
for innerPos, value := range oauthParams.Get(key) {
if pos+innerPos > 0 {
oauthHdr += ","
}
oauthHdr += key + "=\"" + value + "\""
}
}
req.Header.Add("Authorization", oauthHdr)
// Add additional custom headers
for key, vals := range c.AdditionalHeaders {
for _, val := range vals {
req.Header.Add(key, val)
}
}
// Set contentType if passed.
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
// Set contentLength if passed.
if contentLength > 0 {
req.Header.Set("Content-Length", strconv.Itoa(contentLength))
}
if c.debug {
fmt.Printf("Request: %v\n", req)
}
resp, err := c.HttpClient.Do(req)
if err != nil {
return nil, errors.New("Do: " + err.Error())
}
debugHeader := ""
for k, vals := range req.Header {
for _, val := range vals {
debugHeader += "[key: " + k + ", val: " + val + "]"
}
}
// StatusMultipleChoices is 300, any 2xx response should be treated as success
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body)
return resp, HTTPExecuteError{
RequestHeaders: debugHeader,
ResponseBodyBytes: bytes,
Status: resp.Status,
StatusCode: resp.StatusCode,
}
}
return resp, err
}
//
// String Sorting helpers
//
type ByValue []string
func (a ByValue) Len() int {
return len(a)
}
func (a ByValue) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByValue) Less(i, j int) bool {
return a[i] < a[j]
}
//
// ORDERED PARAMS
//
type OrderedParams struct {
allParams map[string][]string
keyOrdering []string
}
func NewOrderedParams() *OrderedParams {
return &OrderedParams{
allParams: make(map[string][]string),
keyOrdering: make([]string, 0),
}
}
func (o *OrderedParams) Get(key string) []string {
sort.Sort(ByValue(o.allParams[key]))
return o.allParams[key]
}
func (o *OrderedParams) Keys() []string {
sort.Sort(o)
return o.keyOrdering
}
func (o *OrderedParams) Add(key, value string) {
o.AddUnescaped(key, escape(value))
}
func (o *OrderedParams) AddUnescaped(key, value string) {
if _, exists := o.allParams[key]; !exists {
o.keyOrdering = append(o.keyOrdering, key)
o.allParams[key] = make([]string, 1)
o.allParams[key][0] = value
} else {
o.allParams[key] = append(o.allParams[key], value)
}
}
func (o *OrderedParams) Len() int {
return len(o.keyOrdering)
}
func (o *OrderedParams) Less(i int, j int) bool {
return o.keyOrdering[i] < o.keyOrdering[j]
}
func (o *OrderedParams) Swap(i int, j int) {
o.keyOrdering[i], o.keyOrdering[j] = o.keyOrdering[j], o.keyOrdering[i]
}
func (o *OrderedParams) Clone() *OrderedParams {
clone := NewOrderedParams()
for _, key := range o.Keys() {
for _, value := range o.Get(key) {
clone.AddUnescaped(key, value)
}
}
return clone
}
| vendor/github.com/mrjones/oauth/oauth.go | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.0020316201262176037,
0.00019161180534865707,
0.0001597523660166189,
0.00017128727631643414,
0.0001595718931639567
] |
{
"id": 0,
"code_window": [
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n",
"\tif !user.IsActive {\n",
"\t\treturn nil, ErrUserInactive{user.ID, user.Name}\n",
"\t} else if user.ProhibitLogin {\n",
"\t\treturn nil, ErrUserProhibitLogin{user.ID, user.Name}\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// WARN: DON'T check user.IsActive, that will be checked on reqSign so that\n",
"\t// user could be hint to resend confirm email.\n",
"\tif user.ProhibitLogin {\n"
],
"file_path": "models/login_source.go",
"type": "replace",
"edit_start_line_idx": 618
} | Copyright (C) 2006 by Rob Landley <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
| options/license/0BSD | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.00017320457845926285,
0.0001715235848678276,
0.00016984259127639234,
0.0001715235848678276,
0.0000016809935914352536
] |
{
"id": 0,
"code_window": [
"\tif err != nil {\n",
"\t\treturn nil, err\n",
"\t}\n",
"\n",
"\tif !user.IsActive {\n",
"\t\treturn nil, ErrUserInactive{user.ID, user.Name}\n",
"\t} else if user.ProhibitLogin {\n",
"\t\treturn nil, ErrUserProhibitLogin{user.ID, user.Name}\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// WARN: DON'T check user.IsActive, that will be checked on reqSign so that\n",
"\t// user could be hint to resend confirm email.\n",
"\tif user.ProhibitLogin {\n"
],
"file_path": "models/login_source.go",
"type": "replace",
"edit_start_line_idx": 618
} | #!/usr/bin/env bash
"$GITEA_ROOT/gitea" hook --config="$GITEA_ROOT/$GITEA_CONF" update $1 $2 $3
| integrations/gitea-repositories-meta/user2/utf8.git/hooks/update.d/gitea | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.00017411363660357893,
0.00017411363660357893,
0.00017411363660357893,
0.00017411363660357893,
0
] |
{
"id": 1,
"code_window": [
"\n",
"\tif hasUser {\n",
"\t\tswitch user.LoginType {\n",
"\t\tcase LoginNoType, LoginPlain, LoginOAuth2:\n",
"\t\t\tif user.IsPasswordSet() && user.ValidatePassword(password) {\n",
"\t\t\t\tif !user.IsActive {\n",
"\t\t\t\t\treturn nil, ErrUserInactive{user.ID, user.Name}\n",
"\t\t\t\t} else if user.ProhibitLogin {\n",
"\t\t\t\t\treturn nil, ErrUserProhibitLogin{user.ID, user.Name}\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// WARN: DON'T check user.IsActive, that will be checked on reqSign so that\n",
"\t\t\t\t// user could be hint to resend confirm email.\n",
"\t\t\t\tif user.ProhibitLogin {\n"
],
"file_path": "models/login_source.go",
"type": "replace",
"edit_start_line_idx": 660
} | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/smtp"
"net/textproto"
"strings"
"github.com/Unknwon/com"
"github.com/go-macaron/binding"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
"code.gitea.io/gitea/modules/auth/ldap"
"code.gitea.io/gitea/modules/auth/oauth2"
"code.gitea.io/gitea/modules/auth/pam"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util"
)
// LoginType represents an login type.
type LoginType int
// Note: new type must append to the end of list to maintain compatibility.
const (
LoginNoType LoginType = iota
LoginPlain // 1
LoginLDAP // 2
LoginSMTP // 3
LoginPAM // 4
LoginDLDAP // 5
LoginOAuth2 // 6
)
// LoginNames contains the name of LoginType values.
var LoginNames = map[LoginType]string{
LoginLDAP: "LDAP (via BindDN)",
LoginDLDAP: "LDAP (simple auth)", // Via direct bind
LoginSMTP: "SMTP",
LoginPAM: "PAM",
LoginOAuth2: "OAuth2",
}
// SecurityProtocolNames contains the name of SecurityProtocol values.
var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
ldap.SecurityProtocolUnencrypted: "Unencrypted",
ldap.SecurityProtocolLDAPS: "LDAPS",
ldap.SecurityProtocolStartTLS: "StartTLS",
}
// Ensure structs implemented interface.
var (
_ core.Conversion = &LDAPConfig{}
_ core.Conversion = &SMTPConfig{}
_ core.Conversion = &PAMConfig{}
_ core.Conversion = &OAuth2Config{}
)
// LDAPConfig holds configuration for LDAP login source.
type LDAPConfig struct {
*ldap.Source
}
// FromDB fills up a LDAPConfig from serialized format.
func (cfg *LDAPConfig) FromDB(bs []byte) error {
return json.Unmarshal(bs, &cfg)
}
// ToDB exports a LDAPConfig to a serialized format.
func (cfg *LDAPConfig) ToDB() ([]byte, error) {
return json.Marshal(cfg)
}
// SecurityProtocolName returns the name of configured security
// protocol.
func (cfg *LDAPConfig) SecurityProtocolName() string {
return SecurityProtocolNames[cfg.SecurityProtocol]
}
// SMTPConfig holds configuration for the SMTP login source.
type SMTPConfig struct {
Auth string
Host string
Port int
AllowedDomains string `xorm:"TEXT"`
TLS bool
SkipVerify bool
}
// FromDB fills up an SMTPConfig from serialized format.
func (cfg *SMTPConfig) FromDB(bs []byte) error {
return json.Unmarshal(bs, cfg)
}
// ToDB exports an SMTPConfig to a serialized format.
func (cfg *SMTPConfig) ToDB() ([]byte, error) {
return json.Marshal(cfg)
}
// PAMConfig holds configuration for the PAM login source.
type PAMConfig struct {
ServiceName string // pam service (e.g. system-auth)
}
// FromDB fills up a PAMConfig from serialized format.
func (cfg *PAMConfig) FromDB(bs []byte) error {
return json.Unmarshal(bs, &cfg)
}
// ToDB exports a PAMConfig to a serialized format.
func (cfg *PAMConfig) ToDB() ([]byte, error) {
return json.Marshal(cfg)
}
// OAuth2Config holds configuration for the OAuth2 login source.
type OAuth2Config struct {
Provider string
ClientID string
ClientSecret string
OpenIDConnectAutoDiscoveryURL string
CustomURLMapping *oauth2.CustomURLMapping
}
// FromDB fills up an OAuth2Config from serialized format.
func (cfg *OAuth2Config) FromDB(bs []byte) error {
return json.Unmarshal(bs, cfg)
}
// ToDB exports an SMTPConfig to a serialized format.
func (cfg *OAuth2Config) ToDB() ([]byte, error) {
return json.Marshal(cfg)
}
// LoginSource represents an external way for authorizing users.
type LoginSource struct {
ID int64 `xorm:"pk autoincr"`
Type LoginType
Name string `xorm:"UNIQUE"`
IsActived bool `xorm:"INDEX NOT NULL DEFAULT false"`
IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
Cfg core.Conversion `xorm:"TEXT"`
CreatedUnix util.TimeStamp `xorm:"INDEX created"`
UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
}
// Cell2Int64 converts a xorm.Cell type to int64,
// and handles possible irregular cases.
func Cell2Int64(val xorm.Cell) int64 {
switch (*val).(type) {
case []uint8:
log.Trace("Cell2Int64 ([]uint8): %v", *val)
return com.StrTo(string((*val).([]uint8))).MustInt64()
}
return (*val).(int64)
}
// BeforeSet is invoked from XORM before setting the value of a field of this object.
func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
switch colName {
case "type":
switch LoginType(Cell2Int64(val)) {
case LoginLDAP, LoginDLDAP:
source.Cfg = new(LDAPConfig)
case LoginSMTP:
source.Cfg = new(SMTPConfig)
case LoginPAM:
source.Cfg = new(PAMConfig)
case LoginOAuth2:
source.Cfg = new(OAuth2Config)
default:
panic("unrecognized login source type: " + com.ToStr(*val))
}
}
}
// TypeName return name of this login source type.
func (source *LoginSource) TypeName() string {
return LoginNames[source.Type]
}
// IsLDAP returns true of this source is of the LDAP type.
func (source *LoginSource) IsLDAP() bool {
return source.Type == LoginLDAP
}
// IsDLDAP returns true of this source is of the DLDAP type.
func (source *LoginSource) IsDLDAP() bool {
return source.Type == LoginDLDAP
}
// IsSMTP returns true of this source is of the SMTP type.
func (source *LoginSource) IsSMTP() bool {
return source.Type == LoginSMTP
}
// IsPAM returns true of this source is of the PAM type.
func (source *LoginSource) IsPAM() bool {
return source.Type == LoginPAM
}
// IsOAuth2 returns true of this source is of the OAuth2 type.
func (source *LoginSource) IsOAuth2() bool {
return source.Type == LoginOAuth2
}
// HasTLS returns true of this source supports TLS.
func (source *LoginSource) HasTLS() bool {
return ((source.IsLDAP() || source.IsDLDAP()) &&
source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
source.IsSMTP()
}
// UseTLS returns true of this source is configured to use TLS.
func (source *LoginSource) UseTLS() bool {
switch source.Type {
case LoginLDAP, LoginDLDAP:
return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
case LoginSMTP:
return source.SMTP().TLS
}
return false
}
// SkipVerify returns true if this source is configured to skip SSL
// verification.
func (source *LoginSource) SkipVerify() bool {
switch source.Type {
case LoginLDAP, LoginDLDAP:
return source.LDAP().SkipVerify
case LoginSMTP:
return source.SMTP().SkipVerify
}
return false
}
// LDAP returns LDAPConfig for this source, if of LDAP type.
func (source *LoginSource) LDAP() *LDAPConfig {
return source.Cfg.(*LDAPConfig)
}
// SMTP returns SMTPConfig for this source, if of SMTP type.
func (source *LoginSource) SMTP() *SMTPConfig {
return source.Cfg.(*SMTPConfig)
}
// PAM returns PAMConfig for this source, if of PAM type.
func (source *LoginSource) PAM() *PAMConfig {
return source.Cfg.(*PAMConfig)
}
// OAuth2 returns OAuth2Config for this source, if of OAuth2 type.
func (source *LoginSource) OAuth2() *OAuth2Config {
return source.Cfg.(*OAuth2Config)
}
// CreateLoginSource inserts a LoginSource in the DB if not already
// existing with the given name.
func CreateLoginSource(source *LoginSource) error {
has, err := x.Get(&LoginSource{Name: source.Name})
if err != nil {
return err
} else if has {
return ErrLoginSourceAlreadyExist{source.Name}
}
// Synchronization is only aviable with LDAP for now
if !source.IsLDAP() {
source.IsSyncEnabled = false
}
_, err = x.Insert(source)
if err == nil && source.IsOAuth2() && source.IsActived {
oAuth2Config := source.OAuth2()
err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
if err != nil {
// remove the LoginSource in case of errors while registering OAuth2 providers
x.Delete(source)
}
}
return err
}
// LoginSources returns a slice of all login sources found in DB.
func LoginSources() ([]*LoginSource, error) {
auths := make([]*LoginSource, 0, 6)
return auths, x.Find(&auths)
}
// GetLoginSourceByID returns login source by given ID.
func GetLoginSourceByID(id int64) (*LoginSource, error) {
source := new(LoginSource)
has, err := x.ID(id).Get(source)
if err != nil {
return nil, err
} else if !has {
return nil, ErrLoginSourceNotExist{id}
}
return source, nil
}
// UpdateSource updates a LoginSource record in DB.
func UpdateSource(source *LoginSource) error {
var originalLoginSource *LoginSource
if source.IsOAuth2() {
// keep track of the original values so we can restore in case of errors while registering OAuth2 providers
var err error
if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
return err
}
}
_, err := x.ID(source.ID).AllCols().Update(source)
if err == nil && source.IsOAuth2() && source.IsActived {
oAuth2Config := source.OAuth2()
err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
if err != nil {
// restore original values since we cannot update the provider it self
x.ID(source.ID).AllCols().Update(originalLoginSource)
}
}
return err
}
// DeleteSource deletes a LoginSource record in DB.
func DeleteSource(source *LoginSource) error {
count, err := x.Count(&User{LoginSource: source.ID})
if err != nil {
return err
} else if count > 0 {
return ErrLoginSourceInUse{source.ID}
}
count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
if err != nil {
return err
} else if count > 0 {
return ErrLoginSourceInUse{source.ID}
}
if source.IsOAuth2() {
oauth2.RemoveProvider(source.Name)
}
_, err = x.ID(source.ID).Delete(new(LoginSource))
return err
}
// CountLoginSources returns number of login sources.
func CountLoginSources() int64 {
count, _ := x.Count(new(LoginSource))
return count
}
// .____ ________ _____ __________
// | | \______ \ / _ \\______ \
// | | | | \ / /_\ \| ___/
// | |___ | ` \/ | \ |
// |_______ \/_______ /\____|__ /____|
// \/ \/ \/
func composeFullName(firstname, surname, username string) string {
switch {
case len(firstname) == 0 && len(surname) == 0:
return username
case len(firstname) == 0:
return surname
case len(surname) == 0:
return firstname
default:
return firstname + " " + surname
}
}
// LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
// and create a local user if success when enabled.
func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
if sr == nil {
// User not in LDAP, do nothing
return nil, ErrUserNotExist{0, login, 0}
}
var isAttributeSSHPublicKeySet = len(strings.TrimSpace(source.LDAP().AttributeSSHPublicKey)) > 0
if !autoRegister {
if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
RewriteAllPublicKeys()
}
return user, nil
}
// Fallback.
if len(sr.Username) == 0 {
sr.Username = login
}
// Validate username make sure it satisfies requirement.
if binding.AlphaDashDotPattern.MatchString(sr.Username) {
return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", sr.Username)
}
if len(sr.Mail) == 0 {
sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
}
user = &User{
LowerName: strings.ToLower(sr.Username),
Name: sr.Username,
FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
Email: sr.Mail,
LoginType: source.Type,
LoginSource: source.ID,
LoginName: login,
IsActive: true,
IsAdmin: sr.IsAdmin,
}
err := CreateUser(user)
if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) {
RewriteAllPublicKeys()
}
return user, err
}
// _________ __________________________
// / _____/ / \__ ___/\______ \
// \_____ \ / \ / \| | | ___/
// / \/ Y \ | | |
// /_______ /\____|__ /____| |____|
// \/ \/
type smtpLoginAuth struct {
username, password string
}
func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte(auth.username), nil
}
func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(auth.username), nil
case "Password:":
return []byte(auth.password), nil
}
}
return nil, nil
}
// SMTP authentication type names.
const (
SMTPPlain = "PLAIN"
SMTPLogin = "LOGIN"
)
// SMTPAuths contains available SMTP authentication type names.
var SMTPAuths = []string{SMTPPlain, SMTPLogin}
// SMTPAuth performs an SMTP authentication.
func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
if err != nil {
return err
}
defer c.Close()
if err = c.Hello("gogs"); err != nil {
return err
}
if cfg.TLS {
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(&tls.Config{
InsecureSkipVerify: cfg.SkipVerify,
ServerName: cfg.Host,
}); err != nil {
return err
}
} else {
return errors.New("SMTP server unsupports TLS")
}
}
if ok, _ := c.Extension("AUTH"); ok {
return c.Auth(a)
}
return ErrUnsupportedLoginType
}
// LoginViaSMTP queries if login/password is valid against the SMTP,
// and create a local user if success when enabled.
func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
// Verify allowed domains.
if len(cfg.AllowedDomains) > 0 {
idx := strings.Index(login, "@")
if idx == -1 {
return nil, ErrUserNotExist{0, login, 0}
} else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
return nil, ErrUserNotExist{0, login, 0}
}
}
var auth smtp.Auth
if cfg.Auth == SMTPPlain {
auth = smtp.PlainAuth("", login, password, cfg.Host)
} else if cfg.Auth == SMTPLogin {
auth = &smtpLoginAuth{login, password}
} else {
return nil, errors.New("Unsupported SMTP auth type")
}
if err := SMTPAuth(auth, cfg); err != nil {
// Check standard error format first,
// then fallback to worse case.
tperr, ok := err.(*textproto.Error)
if (ok && tperr.Code == 535) ||
strings.Contains(err.Error(), "Username and Password not accepted") {
return nil, ErrUserNotExist{0, login, 0}
}
return nil, err
}
if !autoRegister {
return user, nil
}
username := login
idx := strings.Index(login, "@")
if idx > -1 {
username = login[:idx]
}
user = &User{
LowerName: strings.ToLower(username),
Name: strings.ToLower(username),
Email: login,
Passwd: password,
LoginType: LoginSMTP,
LoginSource: sourceID,
LoginName: login,
IsActive: true,
}
return user, CreateUser(user)
}
// __________ _____ _____
// \______ \/ _ \ / \
// | ___/ /_\ \ / \ / \
// | | / | \/ Y \
// |____| \____|__ /\____|__ /
// \/ \/
// LoginViaPAM queries if login/password is valid against the PAM,
// and create a local user if success when enabled.
func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
if strings.Contains(err.Error(), "Authentication failure") {
return nil, ErrUserNotExist{0, login, 0}
}
return nil, err
}
if !autoRegister {
return user, nil
}
user = &User{
LowerName: strings.ToLower(login),
Name: login,
Email: login,
Passwd: password,
LoginType: LoginPAM,
LoginSource: sourceID,
LoginName: login,
IsActive: true,
}
return user, CreateUser(user)
}
// ExternalUserLogin attempts a login using external source types.
func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
if !source.IsActived {
return nil, ErrLoginSourceNotActived
}
var err error
switch source.Type {
case LoginLDAP, LoginDLDAP:
user, err = LoginViaLDAP(user, login, password, source, autoRegister)
case LoginSMTP:
user, err = LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
case LoginPAM:
user, err = LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
default:
return nil, ErrUnsupportedLoginType
}
if err != nil {
return nil, err
}
if !user.IsActive {
return nil, ErrUserInactive{user.ID, user.Name}
} else if user.ProhibitLogin {
return nil, ErrUserProhibitLogin{user.ID, user.Name}
}
return user, nil
}
// UserSignIn validates user name and password.
func UserSignIn(username, password string) (*User, error) {
var user *User
if strings.Contains(username, "@") {
user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
// check same email
cnt, err := x.Count(user)
if err != nil {
return nil, err
}
if cnt > 1 {
return nil, ErrEmailAlreadyUsed{
Email: user.Email,
}
}
} else {
trimmedUsername := strings.TrimSpace(username)
if len(trimmedUsername) == 0 {
return nil, ErrUserNotExist{0, username, 0}
}
user = &User{LowerName: strings.ToLower(trimmedUsername)}
}
hasUser, err := x.Get(user)
if err != nil {
return nil, err
}
if hasUser {
switch user.LoginType {
case LoginNoType, LoginPlain, LoginOAuth2:
if user.IsPasswordSet() && user.ValidatePassword(password) {
if !user.IsActive {
return nil, ErrUserInactive{user.ID, user.Name}
} else if user.ProhibitLogin {
return nil, ErrUserProhibitLogin{user.ID, user.Name}
}
return user, nil
}
return nil, ErrUserNotExist{user.ID, user.Name, 0}
default:
var source LoginSource
hasSource, err := x.ID(user.LoginSource).Get(&source)
if err != nil {
return nil, err
} else if !hasSource {
return nil, ErrLoginSourceNotExist{user.LoginSource}
}
return ExternalUserLogin(user, user.LoginName, password, &source, false)
}
}
sources := make([]*LoginSource, 0, 5)
if err = x.Where("is_actived = ?", true).Find(&sources); err != nil {
return nil, err
}
for _, source := range sources {
if source.IsOAuth2() {
// don't try to authenticate against OAuth2 sources
continue
}
authUser, err := ExternalUserLogin(nil, username, password, source, true)
if err == nil {
return authUser, nil
}
log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
}
return nil, ErrUserNotExist{user.ID, user.Name, 0}
}
| models/login_source.go | 1 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.9944944977760315,
0.029618488624691963,
0.00016237510135397315,
0.00057155208196491,
0.16341492533683777
] |
{
"id": 1,
"code_window": [
"\n",
"\tif hasUser {\n",
"\t\tswitch user.LoginType {\n",
"\t\tcase LoginNoType, LoginPlain, LoginOAuth2:\n",
"\t\t\tif user.IsPasswordSet() && user.ValidatePassword(password) {\n",
"\t\t\t\tif !user.IsActive {\n",
"\t\t\t\t\treturn nil, ErrUserInactive{user.ID, user.Name}\n",
"\t\t\t\t} else if user.ProhibitLogin {\n",
"\t\t\t\t\treturn nil, ErrUserProhibitLogin{user.ID, user.Name}\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// WARN: DON'T check user.IsActive, that will be checked on reqSign so that\n",
"\t\t\t\t// user could be hint to resend confirm email.\n",
"\t\t\t\tif user.ProhibitLogin {\n"
],
"file_path": "models/login_source.go",
"type": "replace",
"edit_start_line_idx": 660
} | // Copyright 2016 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package builder
import "errors"
var (
// ErrNotSupportType not supported SQL type error
ErrNotSupportType = errors.New("Not supported SQL type")
// ErrNoNotInConditions no NOT IN params error
ErrNoNotInConditions = errors.New("No NOT IN conditions")
// ErrNoInConditions no IN params error
ErrNoInConditions = errors.New("No IN conditions")
// ErrNeedMoreArguments need more arguments
ErrNeedMoreArguments = errors.New("Need more sql arguments")
// ErrNoTableName no table name
ErrNoTableName = errors.New("No table indicated")
// ErrNoColumnToInsert no column to update
ErrNoColumnToUpdate = errors.New("No column(s) to update")
// ErrNoColumnToInsert no column to update
ErrNoColumnToInsert = errors.New("No column(s) to insert")
// ErrNotSupportDialectType not supported dialect type error
ErrNotSupportDialectType = errors.New("Not supported dialect type")
// ErrNotUnexpectedUnionConditions using union in a wrong way
ErrNotUnexpectedUnionConditions = errors.New("Unexpected conditional fields in UNION query")
// ErrUnsupportedUnionMembers unexpected members in UNION query
ErrUnsupportedUnionMembers = errors.New("Unexpected members in UNION query")
// ErrUnexpectedSubQuery Unexpected sub-query in SELECT query
ErrUnexpectedSubQuery = errors.New("Unexpected sub-query in SELECT query")
// ErrDialectNotSetUp dialect is not setup yet
ErrDialectNotSetUp = errors.New("Dialect is not setup yet, try to use `Dialect(dbType)` at first")
// ErrInvalidLimitation offset or limit is not correct
ErrInvalidLimitation = errors.New("Offset or limit is not correct")
// ErrUnnamedDerivedTable Every derived table must have its own alias
ErrUnnamedDerivedTable = errors.New("Every derived table must have its own alias")
// ErrInconsistentDialect Inconsistent dialect in same builder
ErrInconsistentDialect = errors.New("Inconsistent dialect in same builder")
)
| vendor/github.com/go-xorm/builder/error.go | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.000272751523880288,
0.00019528016855474561,
0.00017504267452750355,
0.00017514434875920415,
0.00003875613765558228
] |
{
"id": 1,
"code_window": [
"\n",
"\tif hasUser {\n",
"\t\tswitch user.LoginType {\n",
"\t\tcase LoginNoType, LoginPlain, LoginOAuth2:\n",
"\t\t\tif user.IsPasswordSet() && user.ValidatePassword(password) {\n",
"\t\t\t\tif !user.IsActive {\n",
"\t\t\t\t\treturn nil, ErrUserInactive{user.ID, user.Name}\n",
"\t\t\t\t} else if user.ProhibitLogin {\n",
"\t\t\t\t\treturn nil, ErrUserProhibitLogin{user.ID, user.Name}\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// WARN: DON'T check user.IsActive, that will be checked on reqSign so that\n",
"\t\t\t\t// user could be hint to resend confirm email.\n",
"\t\t\t\tif user.ProhibitLogin {\n"
],
"file_path": "models/login_source.go",
"type": "replace",
"edit_start_line_idx": 660
} | # Visual Studio 2015 user specific files
.vs/
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
*.ipa
# These project files can be generated by the engine
*.xcodeproj
*.xcworkspace
*.sln
*.suo
*.opensdf
*.sdf
*.VC.db
*.VC.opendb
# Precompiled Assets
SourceArt/**/*.png
SourceArt/**/*.tga
# Binary Files
Binaries/*
Plugins/*/Binaries/*
# Builds
Build/*
# Whitelist PakBlacklist-<BuildConfiguration>.txt files
!Build/*/
Build/*/**
!Build/*/PakBlacklist*.txt
# Don't ignore icon files in Build
!Build/**/*.ico
# Built data for maps
*_BuiltData.uasset
# Configuration files generated by the Editor
Saved/*
# Compiled source files for the engine to use
Intermediate/*
Plugins/*/Intermediate/*
# Cache files for the editor to use
DerivedDataCache/*
| options/gitignore/UnrealEngine | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.00017576300888322294,
0.0001744628680171445,
0.00017130671767517924,
0.00017538118117954582,
0.0000015495552361244336
] |
{
"id": 1,
"code_window": [
"\n",
"\tif hasUser {\n",
"\t\tswitch user.LoginType {\n",
"\t\tcase LoginNoType, LoginPlain, LoginOAuth2:\n",
"\t\t\tif user.IsPasswordSet() && user.ValidatePassword(password) {\n",
"\t\t\t\tif !user.IsActive {\n",
"\t\t\t\t\treturn nil, ErrUserInactive{user.ID, user.Name}\n",
"\t\t\t\t} else if user.ProhibitLogin {\n",
"\t\t\t\t\treturn nil, ErrUserProhibitLogin{user.ID, user.Name}\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// WARN: DON'T check user.IsActive, that will be checked on reqSign so that\n",
"\t\t\t\t// user could be hint to resend confirm email.\n",
"\t\t\t\tif user.ProhibitLogin {\n"
],
"file_path": "models/login_source.go",
"type": "replace",
"edit_start_line_idx": 660
} | // Copyright 2015 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
import (
"fmt"
"io"
"log"
"github.com/go-xorm/core"
)
// default log options
const (
DEFAULT_LOG_PREFIX = "[xorm]"
DEFAULT_LOG_FLAG = log.Ldate | log.Lmicroseconds
DEFAULT_LOG_LEVEL = core.LOG_DEBUG
)
var _ core.ILogger = DiscardLogger{}
// DiscardLogger don't log implementation for core.ILogger
type DiscardLogger struct{}
// Debug empty implementation
func (DiscardLogger) Debug(v ...interface{}) {}
// Debugf empty implementation
func (DiscardLogger) Debugf(format string, v ...interface{}) {}
// Error empty implementation
func (DiscardLogger) Error(v ...interface{}) {}
// Errorf empty implementation
func (DiscardLogger) Errorf(format string, v ...interface{}) {}
// Info empty implementation
func (DiscardLogger) Info(v ...interface{}) {}
// Infof empty implementation
func (DiscardLogger) Infof(format string, v ...interface{}) {}
// Warn empty implementation
func (DiscardLogger) Warn(v ...interface{}) {}
// Warnf empty implementation
func (DiscardLogger) Warnf(format string, v ...interface{}) {}
// Level empty implementation
func (DiscardLogger) Level() core.LogLevel {
return core.LOG_UNKNOWN
}
// SetLevel empty implementation
func (DiscardLogger) SetLevel(l core.LogLevel) {}
// ShowSQL empty implementation
func (DiscardLogger) ShowSQL(show ...bool) {}
// IsShowSQL empty implementation
func (DiscardLogger) IsShowSQL() bool {
return false
}
// SimpleLogger is the default implment of core.ILogger
type SimpleLogger struct {
DEBUG *log.Logger
ERR *log.Logger
INFO *log.Logger
WARN *log.Logger
level core.LogLevel
showSQL bool
}
var _ core.ILogger = &SimpleLogger{}
// NewSimpleLogger use a special io.Writer as logger output
func NewSimpleLogger(out io.Writer) *SimpleLogger {
return NewSimpleLogger2(out, DEFAULT_LOG_PREFIX, DEFAULT_LOG_FLAG)
}
// NewSimpleLogger2 let you customrize your logger prefix and flag
func NewSimpleLogger2(out io.Writer, prefix string, flag int) *SimpleLogger {
return NewSimpleLogger3(out, prefix, flag, DEFAULT_LOG_LEVEL)
}
// NewSimpleLogger3 let you customrize your logger prefix and flag and logLevel
func NewSimpleLogger3(out io.Writer, prefix string, flag int, l core.LogLevel) *SimpleLogger {
return &SimpleLogger{
DEBUG: log.New(out, fmt.Sprintf("%s [debug] ", prefix), flag),
ERR: log.New(out, fmt.Sprintf("%s [error] ", prefix), flag),
INFO: log.New(out, fmt.Sprintf("%s [info] ", prefix), flag),
WARN: log.New(out, fmt.Sprintf("%s [warn] ", prefix), flag),
level: l,
}
}
// Error implement core.ILogger
func (s *SimpleLogger) Error(v ...interface{}) {
if s.level <= core.LOG_ERR {
s.ERR.Output(2, fmt.Sprint(v...))
}
return
}
// Errorf implement core.ILogger
func (s *SimpleLogger) Errorf(format string, v ...interface{}) {
if s.level <= core.LOG_ERR {
s.ERR.Output(2, fmt.Sprintf(format, v...))
}
return
}
// Debug implement core.ILogger
func (s *SimpleLogger) Debug(v ...interface{}) {
if s.level <= core.LOG_DEBUG {
s.DEBUG.Output(2, fmt.Sprint(v...))
}
return
}
// Debugf implement core.ILogger
func (s *SimpleLogger) Debugf(format string, v ...interface{}) {
if s.level <= core.LOG_DEBUG {
s.DEBUG.Output(2, fmt.Sprintf(format, v...))
}
return
}
// Info implement core.ILogger
func (s *SimpleLogger) Info(v ...interface{}) {
if s.level <= core.LOG_INFO {
s.INFO.Output(2, fmt.Sprint(v...))
}
return
}
// Infof implement core.ILogger
func (s *SimpleLogger) Infof(format string, v ...interface{}) {
if s.level <= core.LOG_INFO {
s.INFO.Output(2, fmt.Sprintf(format, v...))
}
return
}
// Warn implement core.ILogger
func (s *SimpleLogger) Warn(v ...interface{}) {
if s.level <= core.LOG_WARNING {
s.WARN.Output(2, fmt.Sprint(v...))
}
return
}
// Warnf implement core.ILogger
func (s *SimpleLogger) Warnf(format string, v ...interface{}) {
if s.level <= core.LOG_WARNING {
s.WARN.Output(2, fmt.Sprintf(format, v...))
}
return
}
// Level implement core.ILogger
func (s *SimpleLogger) Level() core.LogLevel {
return s.level
}
// SetLevel implement core.ILogger
func (s *SimpleLogger) SetLevel(l core.LogLevel) {
s.level = l
return
}
// ShowSQL implement core.ILogger
func (s *SimpleLogger) ShowSQL(show ...bool) {
if len(show) == 0 {
s.showSQL = true
return
}
s.showSQL = show[0]
}
// IsShowSQL implement core.ILogger
func (s *SimpleLogger) IsShowSQL() bool {
return s.showSQL
}
| vendor/github.com/go-xorm/xorm/logger.go | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.0003741633554454893,
0.00019314362725708634,
0.0001600966788828373,
0.00016867462545633316,
0.00006319168460322544
] |
{
"id": 2,
"code_window": [
"\n",
"\tm.Group(\"/user\", func() {\n",
"\t\t// r.Get(\"/feeds\", binding.Bind(auth.FeedsForm{}), user.Feeds)\n",
"\t\tm.Any(\"/activate\", user.Activate)\n",
"\t\tm.Any(\"/activate_email\", user.ActivateEmail)\n",
"\t\tm.Get(\"/email2user\", user.Email2User)\n",
"\t\tm.Get(\"/forgot_password\", user.ForgotPasswd)\n",
"\t\tm.Post(\"/forgot_password\", user.ForgotPasswdPost)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tm.Any(\"/activate\", user.Activate, reqSignIn)\n"
],
"file_path": "routers/routes/routes.go",
"type": "replace",
"edit_start_line_idx": 341
} | // Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package routes
import (
"encoding/gob"
"fmt"
"net/http"
"os"
"path"
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/auth"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/gzip"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/metrics"
"code.gitea.io/gitea/modules/options"
"code.gitea.io/gitea/modules/public"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/validation"
"code.gitea.io/gitea/routers"
"code.gitea.io/gitea/routers/admin"
apiv1 "code.gitea.io/gitea/routers/api/v1"
"code.gitea.io/gitea/routers/dev"
"code.gitea.io/gitea/routers/org"
"code.gitea.io/gitea/routers/private"
"code.gitea.io/gitea/routers/repo"
"code.gitea.io/gitea/routers/user"
userSetting "code.gitea.io/gitea/routers/user/setting"
"github.com/go-macaron/binding"
"github.com/go-macaron/cache"
"github.com/go-macaron/captcha"
"github.com/go-macaron/csrf"
"github.com/go-macaron/i18n"
"github.com/go-macaron/session"
"github.com/go-macaron/toolbox"
"github.com/prometheus/client_golang/prometheus"
"github.com/tstranex/u2f"
macaron "gopkg.in/macaron.v1"
)
func giteaLogger(l *log.LoggerAsWriter) macaron.Handler {
return func(ctx *macaron.Context) {
start := time.Now()
l.Log(fmt.Sprintf("[Macaron] Started %s %s for %s", ctx.Req.Method, ctx.Req.RequestURI, ctx.RemoteAddr()))
ctx.Next()
rw := ctx.Resp.(macaron.ResponseWriter)
l.Log(fmt.Sprintf("[Macaron] Completed %s %s %v %s in %v", ctx.Req.Method, ctx.Req.RequestURI, rw.Status(), http.StatusText(rw.Status()), time.Since(start)))
}
}
// NewMacaron initializes Macaron instance.
func NewMacaron() *macaron.Macaron {
gob.Register(&u2f.Challenge{})
var m *macaron.Macaron
if setting.RedirectMacaronLog {
loggerAsWriter := log.NewLoggerAsWriter("INFO")
m = macaron.NewWithLogger(loggerAsWriter)
if !setting.DisableRouterLog {
m.Use(giteaLogger(loggerAsWriter))
}
} else {
m = macaron.New()
if !setting.DisableRouterLog {
m.Use(macaron.Logger())
}
}
m.Use(macaron.Recovery())
if setting.EnableGzip {
m.Use(gzip.Middleware())
}
if setting.Protocol == setting.FCGI {
m.SetURLPrefix(setting.AppSubURL)
}
m.Use(public.Custom(
&public.Options{
SkipLogging: setting.DisableRouterLog,
ExpiresAfter: time.Hour * 6,
},
))
m.Use(public.Static(
&public.Options{
Directory: path.Join(setting.StaticRootPath, "public"),
SkipLogging: setting.DisableRouterLog,
ExpiresAfter: time.Hour * 6,
},
))
m.Use(public.StaticHandler(
setting.AvatarUploadPath,
&public.Options{
Prefix: "avatars",
SkipLogging: setting.DisableRouterLog,
ExpiresAfter: time.Hour * 6,
},
))
m.Use(templates.HTMLRenderer())
models.InitMailRender(templates.Mailer())
localeNames, err := options.Dir("locale")
if err != nil {
log.Fatal(4, "Failed to list locale files: %v", err)
}
localFiles := make(map[string][]byte)
for _, name := range localeNames {
localFiles[name], err = options.Locale(name)
if err != nil {
log.Fatal(4, "Failed to load %s locale file. %v", name, err)
}
}
m.Use(i18n.I18n(i18n.Options{
SubURL: setting.AppSubURL,
Files: localFiles,
Langs: setting.Langs,
Names: setting.Names,
DefaultLang: "en-US",
Redirect: false,
}))
m.Use(cache.Cacher(cache.Options{
Adapter: setting.CacheService.Adapter,
AdapterConfig: setting.CacheService.Conn,
Interval: setting.CacheService.Interval,
}))
m.Use(captcha.Captchaer(captcha.Options{
SubURL: setting.AppSubURL,
}))
m.Use(session.Sessioner(setting.SessionConfig))
m.Use(csrf.Csrfer(csrf.Options{
Secret: setting.SecretKey,
Cookie: setting.CSRFCookieName,
SetCookie: true,
Secure: setting.SessionConfig.Secure,
CookieHttpOnly: true,
Header: "X-Csrf-Token",
CookiePath: setting.AppSubURL,
}))
m.Use(toolbox.Toolboxer(m, toolbox.Options{
HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
{
Desc: "Database connection",
Func: models.Ping,
},
},
DisableDebug: !setting.EnablePprof,
}))
m.Use(context.Contexter())
// OK we are now set-up enough to allow us to create a nicer recovery than
// the default macaron recovery
m.Use(context.Recovery())
m.SetAutoHead(true)
return m
}
// RegisterRoutes routes routes to Macaron
func RegisterRoutes(m *macaron.Macaron) {
reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
bindIgnErr := binding.BindIgnErr
validation.AddBindingRules()
openIDSignInEnabled := func(ctx *context.Context) {
if !setting.Service.EnableOpenIDSignIn {
ctx.Error(403)
return
}
}
openIDSignUpEnabled := func(ctx *context.Context) {
if !setting.Service.EnableOpenIDSignUp {
ctx.Error(403)
return
}
}
m.Use(user.GetNotificationCount)
// FIXME: not all routes need go through same middlewares.
// Especially some AJAX requests, we can reduce middleware number to improve performance.
// Routers.
// for health check
m.Head("/", func() string {
return ""
})
m.Get("/", routers.Home)
m.Group("/explore", func() {
m.Get("", func(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL + "/explore/repos")
})
m.Get("/repos", routers.ExploreRepos)
m.Get("/users", routers.ExploreUsers)
m.Get("/organizations", routers.ExploreOrganizations)
m.Get("/code", routers.ExploreCode)
}, ignSignIn)
m.Combo("/install", routers.InstallInit).Get(routers.Install).
Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
// ***** START: User *****
m.Group("/user", func() {
m.Get("/login", user.SignIn)
m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
m.Group("", func() {
m.Combo("/login/openid").
Get(user.SignInOpenID).
Post(bindIgnErr(auth.SignInOpenIDForm{}), user.SignInOpenIDPost)
}, openIDSignInEnabled)
m.Group("/openid", func() {
m.Combo("/connect").
Get(user.ConnectOpenID).
Post(bindIgnErr(auth.ConnectOpenIDForm{}), user.ConnectOpenIDPost)
m.Group("/register", func() {
m.Combo("").
Get(user.RegisterOpenID, openIDSignUpEnabled).
Post(bindIgnErr(auth.SignUpOpenIDForm{}), user.RegisterOpenIDPost)
}, openIDSignUpEnabled)
}, openIDSignInEnabled)
m.Get("/sign_up", user.SignUp)
m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
m.Get("/reset_password", user.ResetPasswd)
m.Post("/reset_password", user.ResetPasswdPost)
m.Group("/oauth2", func() {
m.Get("/:provider", user.SignInOAuth)
m.Get("/:provider/callback", user.SignInOAuthCallback)
})
m.Get("/link_account", user.LinkAccount)
m.Post("/link_account_signin", bindIgnErr(auth.SignInForm{}), user.LinkAccountPostSignIn)
m.Post("/link_account_signup", bindIgnErr(auth.RegisterForm{}), user.LinkAccountPostRegister)
m.Group("/two_factor", func() {
m.Get("", user.TwoFactor)
m.Post("", bindIgnErr(auth.TwoFactorAuthForm{}), user.TwoFactorPost)
m.Get("/scratch", user.TwoFactorScratch)
m.Post("/scratch", bindIgnErr(auth.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost)
})
m.Group("/u2f", func() {
m.Get("", user.U2F)
m.Get("/challenge", user.U2FChallenge)
m.Post("/sign", bindIgnErr(u2f.SignResponse{}), user.U2FSign)
})
}, reqSignOut)
m.Group("/login/oauth", func() {
m.Get("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
m.Post("/grant", bindIgnErr(auth.GrantApplicationForm{}), user.GrantApplicationOAuth)
// TODO manage redirection
m.Post("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
}, ignSignInAndCsrf, reqSignIn)
m.Post("/login/oauth/access_token", bindIgnErr(auth.AccessTokenForm{}), ignSignInAndCsrf, user.AccessTokenOAuth)
m.Group("/user/settings", func() {
m.Get("", userSetting.Profile)
m.Post("", bindIgnErr(auth.UpdateProfileForm{}), userSetting.ProfilePost)
m.Get("/change_password", user.MustChangePassword)
m.Post("/change_password", bindIgnErr(auth.MustChangePasswordForm{}), user.MustChangePasswordPost)
m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), userSetting.AvatarPost)
m.Post("/avatar/delete", userSetting.DeleteAvatar)
m.Group("/account", func() {
m.Combo("").Get(userSetting.Account).Post(bindIgnErr(auth.ChangePasswordForm{}), userSetting.AccountPost)
m.Post("/email", bindIgnErr(auth.AddEmailForm{}), userSetting.EmailPost)
m.Post("/email/delete", userSetting.DeleteEmail)
m.Post("/delete", userSetting.DeleteAccount)
m.Post("/theme", bindIgnErr(auth.UpdateThemeForm{}), userSetting.UpdateUIThemePost)
})
m.Group("/security", func() {
m.Get("", userSetting.Security)
m.Group("/two_factor", func() {
m.Post("/regenerate_scratch", userSetting.RegenerateScratchTwoFactor)
m.Post("/disable", userSetting.DisableTwoFactor)
m.Get("/enroll", userSetting.EnrollTwoFactor)
m.Post("/enroll", bindIgnErr(auth.TwoFactorAuthForm{}), userSetting.EnrollTwoFactorPost)
})
m.Group("/u2f", func() {
m.Post("/request_register", bindIgnErr(auth.U2FRegistrationForm{}), userSetting.U2FRegister)
m.Post("/register", bindIgnErr(u2f.RegisterResponse{}), userSetting.U2FRegisterPost)
m.Post("/delete", bindIgnErr(auth.U2FDeleteForm{}), userSetting.U2FDelete)
})
m.Group("/openid", func() {
m.Post("", bindIgnErr(auth.AddOpenIDForm{}), userSetting.OpenIDPost)
m.Post("/delete", userSetting.DeleteOpenID)
m.Post("/toggle_visibility", userSetting.ToggleOpenIDVisibility)
}, openIDSignInEnabled)
m.Post("/account_link", userSetting.DeleteAccountLink)
})
m.Group("/applications/oauth2", func() {
m.Get("/:id", userSetting.OAuth2ApplicationShow)
m.Post("/:id", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsEdit)
m.Post("/:id/regenerate_secret", userSetting.OAuthApplicationsRegenerateSecret)
m.Post("", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsPost)
m.Post("/delete", userSetting.DeleteOAuth2Application)
})
m.Combo("/applications").Get(userSetting.Applications).
Post(bindIgnErr(auth.NewAccessTokenForm{}), userSetting.ApplicationsPost)
m.Post("/applications/delete", userSetting.DeleteApplication)
m.Combo("/keys").Get(userSetting.Keys).
Post(bindIgnErr(auth.AddKeyForm{}), userSetting.KeysPost)
m.Post("/keys/delete", userSetting.DeleteKey)
m.Get("/organization", userSetting.Organization)
m.Get("/repos", userSetting.Repos)
// redirects from old settings urls to new ones
// TODO: can be removed on next major version
m.Get("/avatar", func(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL+"/user/settings", http.StatusMovedPermanently)
})
m.Get("/email", func(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL+"/user/settings/account", http.StatusMovedPermanently)
})
m.Get("/delete", func(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL+"/user/settings/account", http.StatusMovedPermanently)
})
m.Get("/openid", func(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL+"/user/settings/security", http.StatusMovedPermanently)
})
m.Get("/account_link", func(ctx *context.Context) {
ctx.Redirect(setting.AppSubURL+"/user/settings/security", http.StatusMovedPermanently)
})
}, reqSignIn, func(ctx *context.Context) {
ctx.Data["PageIsUserSettings"] = true
ctx.Data["AllThemes"] = setting.UI.Themes
})
m.Group("/user", func() {
// r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
m.Any("/activate", user.Activate)
m.Any("/activate_email", user.ActivateEmail)
m.Get("/email2user", user.Email2User)
m.Get("/forgot_password", user.ForgotPasswd)
m.Post("/forgot_password", user.ForgotPasswdPost)
m.Get("/logout", user.SignOut)
})
// ***** END: User *****
adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
// ***** START: Admin *****
m.Group("/admin", func() {
m.Get("", adminReq, admin.Dashboard)
m.Get("/config", admin.Config)
m.Post("/config/test_mail", admin.SendTestMail)
m.Get("/monitor", admin.Monitor)
m.Group("/users", func() {
m.Get("", admin.Users)
m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
m.Post("/:userid/delete", admin.DeleteUser)
})
m.Group("/orgs", func() {
m.Get("", admin.Organizations)
})
m.Group("/repos", func() {
m.Get("", admin.Repos)
m.Post("/delete", admin.DeleteRepo)
})
m.Group("/hooks", func() {
m.Get("", admin.DefaultWebhooks)
m.Post("/delete", admin.DeleteDefaultWebhook)
m.Get("/:type/new", repo.WebhooksNew)
m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
})
m.Group("/auths", func() {
m.Get("", admin.Authentications)
m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
m.Combo("/:authid").Get(admin.EditAuthSource).
Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
m.Post("/:authid/delete", admin.DeleteAuthSource)
})
m.Group("/notices", func() {
m.Get("", admin.Notices)
m.Post("/delete", admin.DeleteNotices)
m.Get("/empty", admin.EmptyNotices)
})
}, adminReq)
// ***** END: Admin *****
m.Group("", func() {
m.Group("/:username", func() {
m.Get("", user.Profile)
m.Get("/followers", user.Followers)
m.Get("/following", user.Following)
})
m.Get("/attachments/:uuid", func(ctx *context.Context) {
attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
if err != nil {
if models.IsErrAttachmentNotExist(err) {
ctx.Error(404)
} else {
ctx.ServerError("GetAttachmentByUUID", err)
}
return
}
fr, err := os.Open(attach.LocalPath())
if err != nil {
ctx.ServerError("Open", err)
return
}
defer fr.Close()
if err := attach.IncreaseDownloadCount(); err != nil {
ctx.ServerError("Update", err)
return
}
if err = repo.ServeData(ctx, attach.Name, fr); err != nil {
ctx.ServerError("ServeData", err)
return
}
})
m.Post("/attachments", repo.UploadAttachment)
}, ignSignIn)
m.Group("/:username", func() {
m.Get("/action/:action", user.Action)
}, reqSignIn)
if macaron.Env == macaron.DEV {
m.Get("/template/*", dev.TemplatePreview)
}
reqRepoAdmin := context.RequireRepoAdmin()
reqRepoCodeWriter := context.RequireRepoWriter(models.UnitTypeCode)
reqRepoCodeReader := context.RequireRepoReader(models.UnitTypeCode)
reqRepoReleaseWriter := context.RequireRepoWriter(models.UnitTypeReleases)
reqRepoReleaseReader := context.RequireRepoReader(models.UnitTypeReleases)
reqRepoWikiWriter := context.RequireRepoWriter(models.UnitTypeWiki)
reqRepoIssueReader := context.RequireRepoReader(models.UnitTypeIssues)
reqRepoPullsWriter := context.RequireRepoWriter(models.UnitTypePullRequests)
reqRepoPullsReader := context.RequireRepoReader(models.UnitTypePullRequests)
reqRepoIssuesOrPullsWriter := context.RequireRepoWriterOr(models.UnitTypeIssues, models.UnitTypePullRequests)
reqRepoIssuesOrPullsReader := context.RequireRepoReaderOr(models.UnitTypeIssues, models.UnitTypePullRequests)
reqRepoIssueWriter := func(ctx *context.Context) {
if !ctx.Repo.CanWrite(models.UnitTypeIssues) {
ctx.Error(403)
return
}
}
// ***** START: Organization *****
m.Group("/org", func() {
m.Group("", func() {
m.Get("/create", org.Create)
m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
})
m.Group("/:org", func() {
m.Get("/dashboard", user.Dashboard)
m.Get("/^:type(issues|pulls)$", user.Issues)
m.Get("/members", org.Members)
m.Get("/members/action/:action", org.MembersAction)
m.Get("/teams", org.Teams)
}, context.OrgAssignment(true))
m.Group("/:org", func() {
m.Get("/teams/:team", org.TeamMembers)
m.Get("/teams/:team/repositories", org.TeamRepositories)
m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
}, context.OrgAssignment(true, false, true))
m.Group("/:org", func() {
m.Get("/teams/new", org.NewTeam)
m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
m.Get("/teams/:team/edit", org.EditTeam)
m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
m.Post("/teams/:team/delete", org.DeleteTeam)
m.Group("/settings", func() {
m.Combo("").Get(org.Settings).
Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
m.Post("/avatar/delete", org.SettingsDeleteAvatar)
m.Group("/hooks", func() {
m.Get("", org.Webhooks)
m.Post("/delete", org.DeleteWebhook)
m.Get("/:type/new", repo.WebhooksNew)
m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
})
m.Route("/delete", "GET,POST", org.SettingsDelete)
})
}, context.OrgAssignment(true, true))
}, reqSignIn)
// ***** END: Organization *****
// ***** START: Repository *****
m.Group("/repo", func() {
m.Get("/create", repo.Create)
m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
m.Get("/migrate", repo.Migrate)
m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
m.Group("/fork", func() {
m.Combo("/:repoid").Get(repo.Fork).
Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
}, context.RepoIDAssignment(), context.UnitTypes(), reqRepoCodeReader)
}, reqSignIn)
// ***** Release Attachment Download without Signin
m.Get("/:username/:reponame/releases/download/:vTag/:fileName", ignSignIn, context.RepoAssignment(), repo.MustBeNotEmpty, repo.RedirectDownload)
m.Group("/:username/:reponame", func() {
m.Group("/settings", func() {
m.Combo("").Get(repo.Settings).
Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
m.Group("/collaboration", func() {
m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
m.Post("/delete", repo.DeleteCollaboration)
})
m.Group("/branches", func() {
m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost)
m.Combo("/*").Get(repo.SettingsProtectedBranch).
Post(bindIgnErr(auth.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo.SettingsProtectedBranchPost)
}, repo.MustBeNotEmpty)
m.Group("/hooks", func() {
m.Get("", repo.Webhooks)
m.Post("/delete", repo.DeleteWebhook)
m.Get("/:type/new", repo.WebhooksNew)
m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/:id/test", repo.TestWebhook)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Group("/git", func() {
m.Get("", repo.GitHooks)
m.Combo("/:name").Get(repo.GitHooksEdit).
Post(repo.GitHooksEditPost)
}, context.GitHookService())
})
m.Group("/keys", func() {
m.Combo("").Get(repo.DeployKeys).
Post(bindIgnErr(auth.AddKeyForm{}), repo.DeployKeysPost)
m.Post("/delete", repo.DeleteDeployKey)
})
}, func(ctx *context.Context) {
ctx.Data["PageIsSettings"] = true
})
}, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.UnitTypes(), context.RepoRef())
m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), context.UnitTypes(), context.RepoMustNotBeArchived(), repo.Action)
m.Group("/:username/:reponame", func() {
m.Group("/issues", func() {
m.Combo("/new").Get(context.RepoRef(), repo.NewIssue).
Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
}, context.RepoMustNotBeArchived(), reqRepoIssueReader)
// FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
// So they can apply their own enable/disable logic on routers.
m.Group("/issues", func() {
m.Group("/:index", func() {
m.Post("/title", repo.UpdateIssueTitle)
m.Post("/content", repo.UpdateIssueContent)
m.Post("/watch", repo.IssueWatch)
m.Group("/dependency", func() {
m.Post("/add", repo.AddDependency)
m.Post("/delete", repo.RemoveDependency)
})
m.Combo("/comments").Post(repo.MustAllowUserComment, bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
m.Group("/times", func() {
m.Post("/add", bindIgnErr(auth.AddTimeManuallyForm{}), repo.AddTimeManually)
m.Group("/stopwatch", func() {
m.Post("/toggle", repo.IssueStopwatch)
m.Post("/cancel", repo.CancelStopwatch)
})
})
m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
m.Post("/lock", reqRepoIssueWriter, bindIgnErr(auth.IssueLockForm{}), repo.LockIssue)
m.Post("/unlock", reqRepoIssueWriter, repo.UnlockIssue)
}, context.RepoMustNotBeArchived())
m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
}, context.RepoMustNotBeArchived())
m.Group("/comments/:id", func() {
m.Post("", repo.UpdateCommentContent)
m.Post("/delete", repo.DeleteComment)
m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeCommentReaction)
}, context.RepoMustNotBeArchived())
m.Group("/labels", func() {
m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
m.Post("/delete", repo.DeleteLabel)
m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
}, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
m.Group("/milestones", func() {
m.Combo("/new").Get(repo.NewMilestone).
Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
m.Get("/:id/edit", repo.EditMilestone)
m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
m.Get("/:id/:action", repo.ChangeMilestonStatus)
m.Post("/delete", repo.DeleteMilestone)
}, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
m.Group("/milestone", func() {
m.Get("/:id", repo.MilestoneIssuesAndPulls)
}, reqRepoIssuesOrPullsReader, context.RepoRef())
m.Combo("/compare/*", context.RepoMustNotBeArchived(), reqRepoCodeReader, reqRepoPullsReader, repo.MustAllowPulls, repo.SetEditorconfigIfExists).
Get(repo.SetDiffViewStyle, repo.CompareAndPullRequest).
Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
m.Group("", func() {
m.Group("", func() {
m.Combo("/_edit/*").Get(repo.EditFile).
Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
m.Combo("/_new/*").Get(repo.NewFile).
Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
m.Combo("/_delete/*").Get(repo.DeleteFile).
Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
m.Combo("/_upload/*", repo.MustBeAbleToUpload).
Get(repo.UploadFile).
Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
}, context.RepoRefByType(context.RepoRefBranch), repo.MustBeEditable)
m.Group("", func() {
m.Post("/upload-file", repo.UploadFileToServer)
m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
}, context.RepoRef(), repo.MustBeEditable, repo.MustBeAbleToUpload)
}, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
m.Group("/branches", func() {
m.Group("/_new/", func() {
m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
}, bindIgnErr(auth.NewBranchForm{}))
m.Post("/delete", repo.DeleteBranchPost)
m.Post("/restore", repo.RestoreBranchPost)
}, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
}, reqSignIn, context.RepoAssignment(), context.UnitTypes())
// Releases
m.Group("/:username/:reponame", func() {
m.Group("/releases", func() {
m.Get("/", repo.MustBeNotEmpty, repo.Releases)
}, repo.MustBeNotEmpty, context.RepoRef())
m.Group("/releases", func() {
m.Get("/new", repo.NewRelease)
m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
m.Post("/delete", repo.DeleteRelease)
}, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, context.RepoRef())
m.Group("/releases", func() {
m.Get("/edit/*", repo.EditRelease)
m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
}, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, func(ctx *context.Context) {
var err error
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
if err != nil {
ctx.ServerError("GetBranchCommit", err)
return
}
ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
if err != nil {
ctx.ServerError("GetCommitsCount", err)
return
}
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
})
}, ignSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoReleaseReader)
m.Group("/:username/:reponame", func() {
m.Post("/topics", repo.TopicsPost)
}, context.RepoAssignment(), context.RepoMustNotBeArchived(), reqRepoAdmin)
m.Group("/:username/:reponame", func() {
m.Group("", func() {
m.Get("/^:type(issues|pulls)$", repo.Issues)
m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
m.Get("/labels/", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
m.Get("/milestones", reqRepoIssuesOrPullsReader, repo.Milestones)
}, context.RepoRef())
m.Group("/wiki", func() {
m.Get("/?:page", repo.Wiki)
m.Get("/_pages", repo.WikiPages)
m.Group("", func() {
m.Combo("/_new").Get(repo.NewWiki).
Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
m.Combo("/:page/_edit").Get(repo.EditWiki).
Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
m.Post("/:page/delete", repo.DeleteWikiPagePost)
}, context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter)
}, repo.MustEnableWiki, context.RepoRef())
m.Group("/wiki", func() {
m.Get("/raw/*", repo.WikiRaw)
}, repo.MustEnableWiki)
m.Group("/activity", func() {
m.Get("", repo.Activity)
m.Get("/:period", repo.Activity)
}, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypePullRequests, models.UnitTypeIssues, models.UnitTypeReleases))
m.Get("/archive/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.Download)
m.Group("/branches", func() {
m.Get("", repo.Branches)
}, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
m.Group("/pulls/:index", func() {
m.Get(".diff", repo.DownloadPullDiff)
m.Get(".patch", repo.DownloadPullPatch)
m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
m.Post("/merge", context.RepoMustNotBeArchived(), reqRepoPullsWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest)
m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest)
m.Group("/files", func() {
m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles)
m.Group("/reviews", func() {
m.Post("/comments", bindIgnErr(auth.CodeCommentForm{}), repo.CreateCodeComment)
m.Post("/submit", bindIgnErr(auth.SubmitReviewForm{}), repo.SubmitReview)
}, context.RepoMustNotBeArchived())
})
}, repo.MustAllowPulls)
m.Group("/media", func() {
m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
// "/*" route is deprecated, and kept for backward compatibility
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
}, repo.MustBeNotEmpty, reqRepoCodeReader)
m.Group("/raw", func() {
m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
// "/*" route is deprecated, and kept for backward compatibility
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
}, repo.MustBeNotEmpty, reqRepoCodeReader)
m.Group("/commits", func() {
m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
// "/*" route is deprecated, and kept for backward compatibility
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
}, repo.MustBeNotEmpty, reqRepoCodeReader)
m.Group("", func() {
m.Get("/graph", repo.Graph)
m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
}, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
m.Group("/src", func() {
m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
// "/*" route is deprecated, and kept for backward compatibility
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
}, repo.SetEditorconfigIfExists)
m.Group("", func() {
m.Get("/forks", repo.Forks)
}, context.RepoRef(), reqRepoCodeReader)
m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)",
repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.SetEditorconfigIfExists,
repo.SetDiffViewStyle, repo.MustBeNotEmpty, reqRepoCodeReader, repo.CompareDiff)
}, ignSignIn, context.RepoAssignment(), context.UnitTypes())
m.Group("/:username/:reponame", func() {
m.Get("/stars", repo.Stars)
m.Get("/watchers", repo.Watchers)
m.Get("/search", reqRepoCodeReader, repo.Search)
}, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
m.Group("/:username", func() {
m.Group("/:reponame", func() {
m.Get("", repo.SetEditorconfigIfExists, repo.Home)
m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
}, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
m.Group("/:reponame", func() {
m.Group("\\.git/info/lfs", func() {
m.Post("/objects/batch", lfs.BatchHandler)
m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
m.Any("/objects/:oid", lfs.ObjectOidHandler)
m.Post("/objects", lfs.PostHandler)
m.Post("/verify", lfs.VerifyHandler)
m.Group("/locks", func() {
m.Get("/", lfs.GetListLockHandler)
m.Post("/", lfs.PostLockHandler)
m.Post("/verify", lfs.VerifyLockHandler)
m.Post("/:lid/unlock", lfs.UnLockHandler)
}, context.RepoAssignment())
m.Any("/*", func(ctx *context.Context) {
ctx.NotFound("", nil)
})
}, ignSignInAndCsrf)
m.Any("/*", ignSignInAndCsrf, repo.HTTP)
m.Head("/tasks/trigger", repo.TriggerTask)
})
})
// ***** END: Repository *****
m.Group("/notifications", func() {
m.Get("", user.Notifications)
m.Post("/status", user.NotificationStatusPost)
m.Post("/purge", user.NotificationPurgePost)
}, reqSignIn)
if setting.API.EnableSwagger {
m.Get("/swagger.v1.json", templates.JSONRenderer(), routers.SwaggerV1Json)
}
m.Group("/api", func() {
apiv1.RegisterRoutes(m)
}, ignSignIn)
m.Group("/api/internal", func() {
// package name internal is ideal but Golang is not allowed, so we use private as package name.
private.RegisterRoutes(m)
})
// robots.txt
m.Get("/robots.txt", func(ctx *context.Context) {
if setting.HasRobotsTxt {
ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
} else {
ctx.NotFound("", nil)
}
})
// Progressive Web App
m.Get("/manifest.json", templates.JSONRenderer(), func(ctx *context.Context) {
ctx.HTML(200, "pwa/manifest_json")
})
m.Get("/serviceworker.js", templates.JSRenderer(), func(ctx *context.Context) {
ctx.HTML(200, "pwa/serviceworker_js")
})
// prometheus metrics endpoint
if setting.Metrics.Enabled {
c := metrics.NewCollector()
prometheus.MustRegister(c)
m.Get("/metrics", routers.Metrics)
}
// Not found handler.
m.NotFound(routers.NotFound)
}
| routers/routes/routes.go | 1 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.7748830318450928,
0.01650194078683853,
0.00016060583584476262,
0.00017960468539968133,
0.09264757484197617
] |
{
"id": 2,
"code_window": [
"\n",
"\tm.Group(\"/user\", func() {\n",
"\t\t// r.Get(\"/feeds\", binding.Bind(auth.FeedsForm{}), user.Feeds)\n",
"\t\tm.Any(\"/activate\", user.Activate)\n",
"\t\tm.Any(\"/activate_email\", user.ActivateEmail)\n",
"\t\tm.Get(\"/email2user\", user.Email2User)\n",
"\t\tm.Get(\"/forgot_password\", user.ForgotPasswd)\n",
"\t\tm.Post(\"/forgot_password\", user.ForgotPasswdPost)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tm.Any(\"/activate\", user.Activate, reqSignIn)\n"
],
"file_path": "routers/routes/routes.go",
"type": "replace",
"edit_start_line_idx": 341
} | {{template "base/head" .}}
<div class="repository release">
{{template "repo/header" .}}
<div class="ui container">
{{template "base/alert" .}}
<h2 class="ui header">
{{.i18n.Tr "repo.release.releases"}}
{{if .CanCreateRelease}}
<div class="ui right">
<a class="ui small green button" href="{{$.RepoLink}}/releases/new">
{{.i18n.Tr "repo.release.new_release"}}
</a>
</div>
{{end}}
</h2>
<ul id="release-list">
{{range $release := .Releases}}
<li class="ui grid">
<div class="ui four wide column meta">
{{if .IsTag}}
{{if .CreatedUnix}}<span class="time">{{TimeSinceUnix .CreatedUnix $.Lang}}</span>{{end}}
{{else}}
{{if .IsDraft}}
<span class="ui yellow label">{{$.i18n.Tr "repo.release.draft"}}</span>
{{else if .IsPrerelease}}
<span class="ui orange label">{{$.i18n.Tr "repo.release.prerelease"}}</span>
{{else}}
<span class="ui green label">{{$.i18n.Tr "repo.release.stable"}}</span>
{{end}}
<span class="tag text blue">
<a href="{{$.RepoLink}}/src/tag/{{.TagName | EscapePound}}" rel="nofollow"><i class="tag icon"></i> {{.TagName}}</a>
</span>
<span class="commit">
<a href="{{$.RepoLink}}/src/commit/{{.Sha1}}" rel="nofollow"><i class="code icon"></i> {{ShortSha .Sha1}}</a>
</span>
{{end}}
</div>
<div class="ui twelve wide column detail">
{{if .IsTag}}
<h4>
<a href="{{$.RepoLink}}/src/tag/{{.TagName | EscapePound}}" rel="nofollow"><i class="tag icon"></i> {{.TagName}}</a>
</h4>
<div class="download">
{{if $.Permission.CanRead $.UnitTypeCode}}
<a href="{{$.RepoLink}}/src/commit/{{.Sha1}}" rel="nofollow"><i class="code icon"></i> {{ShortSha .Sha1}}</a>
<a href="{{$.RepoLink}}/archive/{{.TagName | EscapePound}}.zip" rel="nofollow"><i class="octicon octicon-file-zip"></i> ZIP</a>
<a href="{{$.RepoLink}}/archive/{{.TagName | EscapePound}}.tar.gz"><i class="octicon octicon-file-zip"></i> TAR.GZ</a>
{{end}}
</div>
{{else}}
<h3>
<a href="{{$.RepoLink}}/src/tag/{{.TagName | EscapePound}}">{{.Title}}</a>
{{if $.CanCreateRelease}}<small>(<a href="{{$.RepoLink}}/releases/edit/{{.TagName | EscapePound}}" rel="nofollow">{{$.i18n.Tr "repo.release.edit"}}</a>)</small>{{end}}
</h3>
<p class="text grey">
<span class="author">
<img class="img-10" src="{{.Publisher.RelAvatarLink}}">
<a href="{{AppSubUrl}}/{{.Publisher.Name}}">{{.Publisher.Name}}</a>
</span>
{{if .CreatedUnix}}<span class="time">{{TimeSinceUnix .CreatedUnix $.Lang}}</span>{{end}}
<span class="ahead">{{$.i18n.Tr "repo.release.ahead" .NumCommitsBehind .Target | Str2html}}</span>
</p>
<div class="markdown desc">
{{Str2html .Note}}
</div>
<div class="download">
<h2>{{$.i18n.Tr "repo.release.downloads"}}</h2>
<ul class="list">
{{if $.Permission.CanRead $.UnitTypeCode}}
<li>
<a href="{{$.RepoLink}}/archive/{{.TagName | EscapePound}}.zip" rel="nofollow"><strong><i class="octicon octicon-file-zip"></i> {{$.i18n.Tr "repo.release.source_code"}} (ZIP)</strong></a>
</li>
<li>
<a href="{{$.RepoLink}}/archive/{{.TagName | EscapePound}}.tar.gz"><strong><i class="octicon octicon-file-zip"></i> {{$.i18n.Tr "repo.release.source_code"}} (TAR.GZ)</strong></a>
</li>
{{end}}
{{if .Attachments}}
{{range $attachment := .Attachments}}
<li>
<a target="_blank" rel="noopener noreferrer" href="{{$.RepoLink}}/releases/download/{{$release.TagName}}/{{$attachment.Name}}">
<strong><span class="ui image octicon octicon-package" title='{{$attachment.Name}}'></span> {{$attachment.Name}}</strong>
<span class="ui text grey right">{{$attachment.Size | FileSize}}</span>
</a>
</li>
{{end}}
{{end}}
</ul>
</div>
{{end}}
<span class="dot"> </span>
</div>
</li>
{{end}}
</ul>
{{template "base/paginate" .}}
</div>
</div>
{{template "base/footer" .}}
| templates/repo/release/list.tmpl | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.0001749221992213279,
0.00017368237604387105,
0.00017146344180218875,
0.00017394122551195323,
8.950048027145385e-7
] |
{
"id": 2,
"code_window": [
"\n",
"\tm.Group(\"/user\", func() {\n",
"\t\t// r.Get(\"/feeds\", binding.Bind(auth.FeedsForm{}), user.Feeds)\n",
"\t\tm.Any(\"/activate\", user.Activate)\n",
"\t\tm.Any(\"/activate_email\", user.ActivateEmail)\n",
"\t\tm.Get(\"/email2user\", user.Email2User)\n",
"\t\tm.Get(\"/forgot_password\", user.ForgotPasswd)\n",
"\t\tm.Post(\"/forgot_password\", user.ForgotPasswdPost)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tm.Any(\"/activate\", user.Activate, reqSignIn)\n"
],
"file_path": "routers/routes/routes.go",
"type": "replace",
"edit_start_line_idx": 341
} | // Copyright 2018 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gitea
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
// Reference represents a Git reference.
type Reference struct {
Ref string `json:"ref"`
URL string `json:"url"`
Object *GitObject `json:"object"`
}
// GitObject represents a Git object.
type GitObject struct {
Type string `json:"type"`
SHA string `json:"sha"`
URL string `json:"url"`
}
// GetRepoRef get one ref's information of one repository
func (c *Client) GetRepoRef(user, repo, ref string) (*Reference, error) {
ref = strings.TrimPrefix(ref, "refs/")
r := new(Reference)
err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil, &r)
if _, ok := err.(*json.UnmarshalTypeError); ok {
// Multiple refs
return nil, errors.New("no exact match found for this ref")
} else if err != nil {
return nil, err
}
return r, nil
}
// GetRepoRefs get list of ref's information of one repository
func (c *Client) GetRepoRefs(user, repo, ref string) ([]*Reference, error) {
ref = strings.TrimPrefix(ref, "refs/")
resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil)
if err != nil {
return nil, err
}
// Attempt to unmarshal single returned ref.
r := new(Reference)
refErr := json.Unmarshal(resp, r)
if refErr == nil {
return []*Reference{r}, nil
}
// Attempt to unmarshal multiple refs.
var rs []*Reference
refsErr := json.Unmarshal(resp, &rs)
if refsErr == nil {
if len(rs) == 0 {
return nil, errors.New("unexpected response: an array of refs with length 0")
}
return rs, nil
}
return nil, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", refErr, refsErr)
}
| vendor/code.gitea.io/sdk/gitea/repo_refs.go | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.00019192916806787252,
0.00017651717644184828,
0.000166031823027879,
0.00017533314530737698,
0.000007481002739950782
] |
{
"id": 2,
"code_window": [
"\n",
"\tm.Group(\"/user\", func() {\n",
"\t\t// r.Get(\"/feeds\", binding.Bind(auth.FeedsForm{}), user.Feeds)\n",
"\t\tm.Any(\"/activate\", user.Activate)\n",
"\t\tm.Any(\"/activate_email\", user.ActivateEmail)\n",
"\t\tm.Get(\"/email2user\", user.Email2User)\n",
"\t\tm.Get(\"/forgot_password\", user.ForgotPasswd)\n",
"\t\tm.Post(\"/forgot_password\", user.ForgotPasswdPost)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tm.Any(\"/activate\", user.Activate, reqSignIn)\n"
],
"file_path": "routers/routes/routes.go",
"type": "replace",
"edit_start_line_idx": 341
} | # Ignore list for Eagle, a PCB layout tool
# Backup files
*.s#?
*.b#?
*.l#?
*.b$?
*.s$?
*.l$?
# Eagle project file
# It contains a serial number and references to the file structure
# on your computer.
# comment the following line if you want to have your project file included.
eagle.epf
# Autorouter files
*.pro
*.job
# CAM files
*.$$$
*.cmp
*.ly2
*.l15
*.sol
*.plc
*.stc
*.sts
*.crc
*.crs
*.dri
*.drl
*.gpi
*.pls
*.ger
*.xln
*.drd
*.drd.*
*.s#*
*.b#*
*.info
*.eps
# file locks introduced since 7.x
*.lck
| options/gitignore/Eagle | 0 | https://github.com/go-gitea/gitea/commit/ef2a343e27d8af2de0bb696bd60d9a019e1e8b69 | [
0.00017569246119819582,
0.00017478103109169751,
0.00017370008572470397,
0.00017504401330370456,
7.737838245702733e-7
] |
{
"id": 0,
"code_window": [
"\tgithub.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51\n",
"\tgithub.com/mattn/go-colorable v0.1.8\n",
"\tgithub.com/mattn/go-isatty v0.0.13\n",
"\tgithub.com/mattn/go-runewidth v0.0.10\n",
"\tgithub.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d\n",
"\tgithub.com/mitchellh/go-homedir v1.1.0\n",
"\tgithub.com/muesli/termenv v0.8.1\n",
"\tgithub.com/rivo/uniseg v0.2.0\n",
"\tgithub.com/shurcooL/githubv4 v0.0.0-20200928013246-d292edc3691b\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "go.mod",
"type": "replace",
"edit_start_line_idx": 25
} | package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"syscall"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
const (
GH_CONFIG_DIR = "GH_CONFIG_DIR"
XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
XDG_STATE_HOME = "XDG_STATE_HOME"
XDG_DATA_HOME = "XDG_DATA_HOME"
APP_DATA = "AppData"
LOCAL_APP_DATA = "LocalAppData"
)
// Config path precedence
// 1. GH_CONFIG_DIR
// 2. XDG_CONFIG_HOME
// 3. AppData (windows only)
// 4. HOME
func ConfigDir() string {
var path string
if a := os.Getenv(GH_CONFIG_DIR); a != "" {
path = a
} else if b := os.Getenv(XDG_CONFIG_HOME); b != "" {
path = filepath.Join(b, "gh")
} else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" {
path = filepath.Join(c, "GitHub CLI")
} else {
d, _ := os.UserHomeDir()
path = filepath.Join(d, ".config", "gh")
}
// If the path does not exist and the GH_CONFIG_DIR flag is not set try
// migrating config from default paths.
if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" {
_ = autoMigrateConfigDir(path)
}
return path
}
// State path precedence
// 1. XDG_CONFIG_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func StateDir() string {
var path string
if a := os.Getenv(XDG_STATE_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "state", "gh")
}
// If the path does not exist try migrating state from default paths
if !dirExists(path) {
_ = autoMigrateStateDir(path)
}
return path
}
// Data path precedence
// 1. XDG_DATA_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func DataDir() string {
var path string
if a := os.Getenv(XDG_DATA_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "share", "gh")
}
return path
}
var errSamePath = errors.New("same path")
var errNotExist = errors.New("not exist")
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs
// If configs exist then move them to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateConfigDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
return errNotExist
}
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)
// If state file exist then move it to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateStateDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
return errNotExist
}
func migrateFile(oldPath, newPath, file string) error {
if oldPath == newPath {
return errSamePath
}
oldFile := filepath.Join(oldPath, file)
newFile := filepath.Join(newPath, file)
if !fileExists(oldFile) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newFile), 0755)
return os.Rename(oldFile, newFile)
}
func migrateDir(oldPath, newPath string) error {
if oldPath == newPath {
return errSamePath
}
if !dirExists(oldPath) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newPath), 0755)
return os.Rename(oldPath, newPath)
}
func dirExists(path string) bool {
f, err := os.Stat(path)
return err == nil && f.IsDir()
}
func fileExists(path string) bool {
f, err := os.Stat(path)
return err == nil && !f.IsDir()
}
func ConfigFile() string {
return filepath.Join(ConfigDir(), "config.yml")
}
func HostsConfigFile() string {
return filepath.Join(ConfigDir(), "hosts.yml")
}
func ParseDefaultConfig() (Config, error) {
return parseConfig(ConfigFile())
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, subdir), nil
}
return "", err
}
newPath := filepath.Join(homeDir, subdir)
if s, err := os.Stat(newPath); err == nil && s.IsDir() {
return newPath, nil
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, subdir)
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
return legacyPath, nil
}
}
return newPath, nil
}
var ReadConfigFile = func(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, pathError(err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
var WriteConfigFile = func(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return pathError(err)
}
cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup
if err != nil {
return err
}
defer cfgFile.Close()
_, err = cfgFile.Write(data)
return err
}
var BackupConfigFile = func(filename string) error {
return os.Rename(filename, filename+".bak")
}
func parseConfigFile(filename string) ([]byte, *yaml.Node, error) {
data, err := ReadConfigFile(filename)
if err != nil {
return nil, nil, err
}
root, err := parseConfigData(data)
if err != nil {
return nil, nil, err
}
return data, root, err
}
func parseConfigData(data []byte) (*yaml.Node, error) {
var root yaml.Node
err := yaml.Unmarshal(data, &root)
if err != nil {
return nil, err
}
if len(root.Content) == 0 {
return &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
}, nil
}
if root.Content[0].Kind != yaml.MappingNode {
return &root, fmt.Errorf("expected a top level map")
}
return &root, nil
}
func isLegacy(root *yaml.Node) bool {
for _, v := range root.Content[0].Content {
if v.Value == "github.com" {
return true
}
}
return false
}
func migrateConfig(filename string) error {
b, err := ReadConfigFile(filename)
if err != nil {
return err
}
var hosts map[string][]yaml.Node
err = yaml.Unmarshal(b, &hosts)
if err != nil {
return fmt.Errorf("error decoding legacy format: %w", err)
}
cfg := NewBlankConfig()
for hostname, entries := range hosts {
if len(entries) < 1 {
continue
}
mapContent := entries[0].Content
for i := 0; i < len(mapContent)-1; i += 2 {
if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil {
return err
}
}
}
err = BackupConfigFile(filename)
if err != nil {
return fmt.Errorf("failed to back up existing config: %w", err)
}
return cfg.Write()
}
func parseConfig(filename string) (Config, error) {
_, root, err := parseConfigFile(filename)
if err != nil {
if os.IsNotExist(err) {
root = NewBlankRoot()
} else {
return nil, err
}
}
if isLegacy(root) {
err = migrateConfig(filename)
if err != nil {
return nil, fmt.Errorf("error migrating legacy config: %w", err)
}
_, root, err = parseConfigFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to reparse migrated config: %w", err)
}
} else {
if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil {
if len(hostsRoot.Content[0].Content) > 0 {
newContent := []*yaml.Node{
{Value: "hosts"},
hostsRoot.Content[0],
}
restContent := root.Content[0].Content
root.Content[0].Content = append(newContent, restContent...)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return NewConfig(root), nil
}
func pathError(err error) error {
var pathError *os.PathError
if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) {
if p := findRegularFile(pathError.Path); p != "" {
return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p)
}
}
return err
}
func findRegularFile(p string) string {
for {
if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() {
return p
}
newPath := filepath.Dir(p)
if newPath == p || newPath == "/" || newPath == "." {
break
}
p = newPath
}
return ""
}
| internal/config/config_file.go | 1 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.014079544693231583,
0.0007385917124338448,
0.0001611876068636775,
0.00016848003724589944,
0.0023495324421674013
] |
{
"id": 0,
"code_window": [
"\tgithub.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51\n",
"\tgithub.com/mattn/go-colorable v0.1.8\n",
"\tgithub.com/mattn/go-isatty v0.0.13\n",
"\tgithub.com/mattn/go-runewidth v0.0.10\n",
"\tgithub.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d\n",
"\tgithub.com/mitchellh/go-homedir v1.1.0\n",
"\tgithub.com/muesli/termenv v0.8.1\n",
"\tgithub.com/rivo/uniseg v0.2.0\n",
"\tgithub.com/shurcooL/githubv4 v0.0.0-20200928013246-d292edc3691b\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "go.mod",
"type": "replace",
"edit_start_line_idx": 25
} | package cmdutil
import (
"errors"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func MinimumArgs(n int, msg string) cobra.PositionalArgs {
if msg == "" {
return cobra.MinimumNArgs(1)
}
return func(cmd *cobra.Command, args []string) error {
if len(args) < n {
return &FlagError{Err: errors.New(msg)}
}
return nil
}
}
func ExactArgs(n int, msg string) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
if len(args) > n {
return &FlagError{Err: errors.New("too many arguments")}
}
if len(args) < n {
return &FlagError{Err: errors.New(msg)}
}
return nil
}
}
func NoArgsQuoteReminder(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return nil
}
errMsg := fmt.Sprintf("unknown argument %q", args[0])
if len(args) > 1 {
errMsg = fmt.Sprintf("unknown arguments %q", args)
}
hasValueFlag := false
cmd.Flags().Visit(func(f *pflag.Flag) {
if f.Value.Type() != "bool" {
hasValueFlag = true
}
})
if hasValueFlag {
errMsg += "; please quote all values that have spaces"
}
return &FlagError{Err: errors.New(errMsg)}
}
| pkg/cmdutil/args.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.0002242709306301549,
0.00017690713866613805,
0.0001637327077332884,
0.0001690559001872316,
0.000019541501387720928
] |
{
"id": 0,
"code_window": [
"\tgithub.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51\n",
"\tgithub.com/mattn/go-colorable v0.1.8\n",
"\tgithub.com/mattn/go-isatty v0.0.13\n",
"\tgithub.com/mattn/go-runewidth v0.0.10\n",
"\tgithub.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d\n",
"\tgithub.com/mitchellh/go-homedir v1.1.0\n",
"\tgithub.com/muesli/termenv v0.8.1\n",
"\tgithub.com/rivo/uniseg v0.2.0\n",
"\tgithub.com/shurcooL/githubv4 v0.0.0-20200928013246-d292edc3691b\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "go.mod",
"type": "replace",
"edit_start_line_idx": 25
} | package add
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"github.com/cli/cli/internal/config"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/iostreams"
"github.com/spf13/cobra"
)
type AddOptions struct {
IO *iostreams.IOStreams
Config func() (config.Config, error)
HTTPClient func() (*http.Client, error)
KeyFile string
Title string
}
func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command {
opts := &AddOptions{
HTTPClient: f.HttpClient,
Config: f.Config,
IO: f.IOStreams,
}
cmd := &cobra.Command{
Use: "add [<key-file>]",
Short: "Add an SSH key to your GitHub account",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() {
return &cmdutil.FlagError{Err: errors.New("public key file missing")}
}
opts.KeyFile = "-"
} else {
opts.KeyFile = args[0]
}
if runF != nil {
return runF(opts)
}
return runAdd(opts)
},
}
cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Title for the new key")
return cmd
}
func runAdd(opts *AddOptions) error {
httpClient, err := opts.HTTPClient()
if err != nil {
return err
}
var keyReader io.Reader
if opts.KeyFile == "-" {
keyReader = opts.IO.In
defer opts.IO.In.Close()
} else {
f, err := os.Open(opts.KeyFile)
if err != nil {
return err
}
defer f.Close()
keyReader = f
}
cfg, err := opts.Config()
if err != nil {
return err
}
hostname, err := cfg.DefaultHost()
if err != nil {
return err
}
err = SSHKeyUpload(httpClient, hostname, keyReader, opts.Title)
if err != nil {
if errors.Is(err, scopesError) {
cs := opts.IO.ColorScheme()
fmt.Fprint(opts.IO.ErrOut, "Error: insufficient OAuth scopes to list SSH keys\n")
fmt.Fprintf(opts.IO.ErrOut, "Run the following to grant scopes: %s\n", cs.Bold("gh auth refresh -s write:public_key"))
return cmdutil.SilentError
}
return err
}
if opts.IO.IsStdoutTTY() {
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.ErrOut, "%s Public key added to your account\n", cs.SuccessIcon())
}
return nil
}
| pkg/cmd/ssh-key/add/add.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00024659064365550876,
0.000174614557181485,
0.00016337198030669242,
0.00016703172877896577,
0.000022873644411447458
] |
{
"id": 0,
"code_window": [
"\tgithub.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51\n",
"\tgithub.com/mattn/go-colorable v0.1.8\n",
"\tgithub.com/mattn/go-isatty v0.0.13\n",
"\tgithub.com/mattn/go-runewidth v0.0.10\n",
"\tgithub.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d\n",
"\tgithub.com/mitchellh/go-homedir v1.1.0\n",
"\tgithub.com/muesli/termenv v0.8.1\n",
"\tgithub.com/rivo/uniseg v0.2.0\n",
"\tgithub.com/shurcooL/githubv4 v0.0.0-20200928013246-d292edc3691b\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "go.mod",
"type": "replace",
"edit_start_line_idx": 25
} | package logout
import (
"errors"
"fmt"
"net/http"
"github.com/AlecAivazis/survey/v2"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/api"
"github.com/cli/cli/internal/config"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/iostreams"
"github.com/cli/cli/pkg/prompt"
"github.com/spf13/cobra"
)
type LogoutOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Config func() (config.Config, error)
Hostname string
}
func NewCmdLogout(f *cmdutil.Factory, runF func(*LogoutOptions) error) *cobra.Command {
opts := &LogoutOptions{
HttpClient: f.HttpClient,
IO: f.IOStreams,
Config: f.Config,
}
cmd := &cobra.Command{
Use: "logout",
Args: cobra.ExactArgs(0),
Short: "Log out of a GitHub host",
Long: heredoc.Doc(`Remove authentication for a GitHub host.
This command removes the authentication configuration for a host either specified
interactively or via --hostname.
`),
Example: heredoc.Doc(`
$ gh auth logout
# => select what host to log out of via a prompt
$ gh auth logout --hostname enterprise.internal
# => log out of specified host
`),
RunE: func(cmd *cobra.Command, args []string) error {
if opts.Hostname == "" && !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("--hostname required when not running interactively")}
}
if runF != nil {
return runF(opts)
}
return logoutRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname of the GitHub instance to log out of")
return cmd
}
func logoutRun(opts *LogoutOptions) error {
hostname := opts.Hostname
cfg, err := opts.Config()
if err != nil {
return err
}
candidates, err := cfg.Hosts()
if err != nil {
return err
}
if len(candidates) == 0 {
return fmt.Errorf("not logged in to any hosts")
}
if hostname == "" {
if len(candidates) == 1 {
hostname = candidates[0]
} else {
err = prompt.SurveyAskOne(&survey.Select{
Message: "What account do you want to log out of?",
Options: candidates,
}, &hostname)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
}
} else {
var found bool
for _, c := range candidates {
if c == hostname {
found = true
break
}
}
if !found {
return fmt.Errorf("not logged into %s", hostname)
}
}
if err := cfg.CheckWriteable(hostname, "oauth_token"); err != nil {
var roErr *config.ReadOnlyEnvError
if errors.As(err, &roErr) {
fmt.Fprintf(opts.IO.ErrOut, "The value of the %s environment variable is being used for authentication.\n", roErr.Variable)
fmt.Fprint(opts.IO.ErrOut, "To erase credentials stored in GitHub CLI, first clear the value from the environment.\n")
return cmdutil.SilentError
}
return err
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
username, err := api.CurrentLoginName(apiClient, hostname)
if err != nil {
// suppressing; the user is trying to delete this token and it might be bad.
// we'll see if the username is in the config and fall back to that.
username, _ = cfg.Get(hostname, "user")
}
usernameStr := ""
if username != "" {
usernameStr = fmt.Sprintf(" account '%s'", username)
}
if opts.IO.CanPrompt() {
var keepGoing bool
err := prompt.SurveyAskOne(&survey.Confirm{
Message: fmt.Sprintf("Are you sure you want to log out of %s%s?", hostname, usernameStr),
Default: true,
}, &keepGoing)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
if !keepGoing {
return nil
}
}
cfg.UnsetHost(hostname)
err = cfg.Write()
if err != nil {
return fmt.Errorf("failed to write config, authentication configuration not updated: %w", err)
}
isTTY := opts.IO.IsStdinTTY() && opts.IO.IsStdoutTTY()
if isTTY {
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.ErrOut, "%s Logged out of %s%s\n",
cs.SuccessIcon(), cs.Bold(hostname), usernameStr)
}
return nil
}
| pkg/cmd/auth/logout/logout.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.000710445863660425,
0.0002044857683358714,
0.0001621798292035237,
0.00016678901738487184,
0.00012741550744976848
] |
{
"id": 1,
"code_window": [
"github.com/microcosm-cc/bluemonday v1.0.6/go.mod h1:HOT/6NaBlR0f9XlxD3zolN6Z3N8Lp4pvhp+jLS5ihnI=\n",
"github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=\n",
"github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=\n",
"github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\n",
"github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=\n",
"github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\n",
"github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=\n",
"github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=\n",
"github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=\n",
"github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=\n",
"github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "go.sum",
"type": "replace",
"edit_start_line_idx": 261
} | package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"syscall"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
const (
GH_CONFIG_DIR = "GH_CONFIG_DIR"
XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
XDG_STATE_HOME = "XDG_STATE_HOME"
XDG_DATA_HOME = "XDG_DATA_HOME"
APP_DATA = "AppData"
LOCAL_APP_DATA = "LocalAppData"
)
// Config path precedence
// 1. GH_CONFIG_DIR
// 2. XDG_CONFIG_HOME
// 3. AppData (windows only)
// 4. HOME
func ConfigDir() string {
var path string
if a := os.Getenv(GH_CONFIG_DIR); a != "" {
path = a
} else if b := os.Getenv(XDG_CONFIG_HOME); b != "" {
path = filepath.Join(b, "gh")
} else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" {
path = filepath.Join(c, "GitHub CLI")
} else {
d, _ := os.UserHomeDir()
path = filepath.Join(d, ".config", "gh")
}
// If the path does not exist and the GH_CONFIG_DIR flag is not set try
// migrating config from default paths.
if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" {
_ = autoMigrateConfigDir(path)
}
return path
}
// State path precedence
// 1. XDG_CONFIG_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func StateDir() string {
var path string
if a := os.Getenv(XDG_STATE_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "state", "gh")
}
// If the path does not exist try migrating state from default paths
if !dirExists(path) {
_ = autoMigrateStateDir(path)
}
return path
}
// Data path precedence
// 1. XDG_DATA_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func DataDir() string {
var path string
if a := os.Getenv(XDG_DATA_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "share", "gh")
}
return path
}
var errSamePath = errors.New("same path")
var errNotExist = errors.New("not exist")
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs
// If configs exist then move them to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateConfigDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
return errNotExist
}
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)
// If state file exist then move it to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateStateDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
return errNotExist
}
func migrateFile(oldPath, newPath, file string) error {
if oldPath == newPath {
return errSamePath
}
oldFile := filepath.Join(oldPath, file)
newFile := filepath.Join(newPath, file)
if !fileExists(oldFile) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newFile), 0755)
return os.Rename(oldFile, newFile)
}
func migrateDir(oldPath, newPath string) error {
if oldPath == newPath {
return errSamePath
}
if !dirExists(oldPath) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newPath), 0755)
return os.Rename(oldPath, newPath)
}
func dirExists(path string) bool {
f, err := os.Stat(path)
return err == nil && f.IsDir()
}
func fileExists(path string) bool {
f, err := os.Stat(path)
return err == nil && !f.IsDir()
}
func ConfigFile() string {
return filepath.Join(ConfigDir(), "config.yml")
}
func HostsConfigFile() string {
return filepath.Join(ConfigDir(), "hosts.yml")
}
func ParseDefaultConfig() (Config, error) {
return parseConfig(ConfigFile())
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, subdir), nil
}
return "", err
}
newPath := filepath.Join(homeDir, subdir)
if s, err := os.Stat(newPath); err == nil && s.IsDir() {
return newPath, nil
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, subdir)
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
return legacyPath, nil
}
}
return newPath, nil
}
var ReadConfigFile = func(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, pathError(err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
var WriteConfigFile = func(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return pathError(err)
}
cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup
if err != nil {
return err
}
defer cfgFile.Close()
_, err = cfgFile.Write(data)
return err
}
var BackupConfigFile = func(filename string) error {
return os.Rename(filename, filename+".bak")
}
func parseConfigFile(filename string) ([]byte, *yaml.Node, error) {
data, err := ReadConfigFile(filename)
if err != nil {
return nil, nil, err
}
root, err := parseConfigData(data)
if err != nil {
return nil, nil, err
}
return data, root, err
}
func parseConfigData(data []byte) (*yaml.Node, error) {
var root yaml.Node
err := yaml.Unmarshal(data, &root)
if err != nil {
return nil, err
}
if len(root.Content) == 0 {
return &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
}, nil
}
if root.Content[0].Kind != yaml.MappingNode {
return &root, fmt.Errorf("expected a top level map")
}
return &root, nil
}
func isLegacy(root *yaml.Node) bool {
for _, v := range root.Content[0].Content {
if v.Value == "github.com" {
return true
}
}
return false
}
func migrateConfig(filename string) error {
b, err := ReadConfigFile(filename)
if err != nil {
return err
}
var hosts map[string][]yaml.Node
err = yaml.Unmarshal(b, &hosts)
if err != nil {
return fmt.Errorf("error decoding legacy format: %w", err)
}
cfg := NewBlankConfig()
for hostname, entries := range hosts {
if len(entries) < 1 {
continue
}
mapContent := entries[0].Content
for i := 0; i < len(mapContent)-1; i += 2 {
if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil {
return err
}
}
}
err = BackupConfigFile(filename)
if err != nil {
return fmt.Errorf("failed to back up existing config: %w", err)
}
return cfg.Write()
}
func parseConfig(filename string) (Config, error) {
_, root, err := parseConfigFile(filename)
if err != nil {
if os.IsNotExist(err) {
root = NewBlankRoot()
} else {
return nil, err
}
}
if isLegacy(root) {
err = migrateConfig(filename)
if err != nil {
return nil, fmt.Errorf("error migrating legacy config: %w", err)
}
_, root, err = parseConfigFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to reparse migrated config: %w", err)
}
} else {
if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil {
if len(hostsRoot.Content[0].Content) > 0 {
newContent := []*yaml.Node{
{Value: "hosts"},
hostsRoot.Content[0],
}
restContent := root.Content[0].Content
root.Content[0].Content = append(newContent, restContent...)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return NewConfig(root), nil
}
func pathError(err error) error {
var pathError *os.PathError
if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) {
if p := findRegularFile(pathError.Path); p != "" {
return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p)
}
}
return err
}
func findRegularFile(p string) string {
for {
if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() {
return p
}
newPath := filepath.Dir(p)
if newPath == p || newPath == "/" || newPath == "." {
break
}
p = newPath
}
return ""
}
| internal/config/config_file.go | 1 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.04428204894065857,
0.044282034039497375,
0.044281989336013794,
0.04428204894065857,
2.241700158833737e-8
] |
{
"id": 1,
"code_window": [
"github.com/microcosm-cc/bluemonday v1.0.6/go.mod h1:HOT/6NaBlR0f9XlxD3zolN6Z3N8Lp4pvhp+jLS5ihnI=\n",
"github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=\n",
"github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=\n",
"github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\n",
"github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=\n",
"github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\n",
"github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=\n",
"github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=\n",
"github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=\n",
"github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=\n",
"github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "go.sum",
"type": "replace",
"edit_start_line_idx": 261
} | package gist
import (
"github.com/MakeNowJust/heredoc"
gistCloneCmd "github.com/cli/cli/pkg/cmd/gist/clone"
gistCreateCmd "github.com/cli/cli/pkg/cmd/gist/create"
gistDeleteCmd "github.com/cli/cli/pkg/cmd/gist/delete"
gistEditCmd "github.com/cli/cli/pkg/cmd/gist/edit"
gistListCmd "github.com/cli/cli/pkg/cmd/gist/list"
gistViewCmd "github.com/cli/cli/pkg/cmd/gist/view"
"github.com/cli/cli/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdGist(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "gist <command>",
Short: "Manage gists",
Long: `Work with GitHub gists.`,
Annotations: map[string]string{
"IsCore": "true",
"help:arguments": heredoc.Doc(`
A gist can be supplied as argument in either of the following formats:
- by ID, e.g. 5b0e0062eb8e9654adad7bb1d81cc75f
- by URL, e.g. "https://gist.github.com/OWNER/5b0e0062eb8e9654adad7bb1d81cc75f"
`),
},
}
cmd.AddCommand(gistCloneCmd.NewCmdClone(f, nil))
cmd.AddCommand(gistCreateCmd.NewCmdCreate(f, nil))
cmd.AddCommand(gistListCmd.NewCmdList(f, nil))
cmd.AddCommand(gistViewCmd.NewCmdView(f, nil))
cmd.AddCommand(gistEditCmd.NewCmdEdit(f, nil))
cmd.AddCommand(gistDeleteCmd.NewCmdDelete(f, nil))
return cmd
}
| pkg/cmd/gist/gist.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.04428206756711006,
0.04428206756711006,
0.04428206756711006,
0.04428206756711006,
0
] |
{
"id": 1,
"code_window": [
"github.com/microcosm-cc/bluemonday v1.0.6/go.mod h1:HOT/6NaBlR0f9XlxD3zolN6Z3N8Lp4pvhp+jLS5ihnI=\n",
"github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=\n",
"github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=\n",
"github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\n",
"github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=\n",
"github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\n",
"github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=\n",
"github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=\n",
"github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=\n",
"github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=\n",
"github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "go.sum",
"type": "replace",
"edit_start_line_idx": 261
} | package status
import (
"bytes"
"io/ioutil"
"net/http"
"regexp"
"strings"
"testing"
"github.com/cli/cli/context"
"github.com/cli/cli/git"
"github.com/cli/cli/internal/config"
"github.com/cli/cli/internal/ghrepo"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/httpmock"
"github.com/cli/cli/pkg/iostreams"
"github.com/cli/cli/test"
"github.com/google/shlex"
)
func runCommand(rt http.RoundTripper, branch string, isTTY bool, cli string) (*test.CmdOut, error) {
io, _, stdout, stderr := iostreams.Test()
io.SetStdoutTTY(isTTY)
io.SetStdinTTY(isTTY)
io.SetStderrTTY(isTTY)
factory := &cmdutil.Factory{
IOStreams: io,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: rt}, nil
},
Config: func() (config.Config, error) {
return config.NewBlankConfig(), nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
Remotes: func() (context.Remotes, error) {
return context.Remotes{
{
Remote: &git.Remote{Name: "origin"},
Repo: ghrepo.New("OWNER", "REPO"),
},
}, nil
},
Branch: func() (string, error) {
if branch == "" {
return "", git.ErrNotOnAnyBranch
}
return branch, nil
},
}
cmd := NewCmdStatus(factory, nil)
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(cli)
if err != nil {
return nil, err
}
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(ioutil.Discard)
cmd.SetErr(ioutil.Discard)
_, err = cmd.ExecuteC()
return &test.CmdOut{
OutBuf: stdout,
ErrBuf: stderr,
}, err
}
func initFakeHTTP() *httpmock.Registry {
return &httpmock.Registry{}
}
func TestPRStatus(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatus.json"))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedPrs := []*regexp.Regexp{
regexp.MustCompile(`#8.*\[strawberries\]`),
regexp.MustCompile(`#9.*\[apples\]`),
regexp.MustCompile(`#10.*\[blueberries\]`),
regexp.MustCompile(`#11.*\[figs\]`),
}
for _, r := range expectedPrs {
if !r.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/", r)
}
}
}
func TestPRStatus_reviewsAndChecks(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusChecks.json"))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expected := []string{
"β Checks passing + Changes requested",
"- Checks pending β Approved",
"Γ 1/3 checks failing - Review required",
}
for _, line := range expected {
if !strings.Contains(output.String(), line) {
t.Errorf("output did not contain %q: %q", line, output.String())
}
}
}
func TestPRStatus_currentBranch_showTheMostRecentPR(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranch.json"))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#10 Blueberries are certainly a good fruit \[blueberries\]`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
unexpectedLines := []*regexp.Regexp{
regexp.MustCompile(`#9 Blueberries are a good fruit \[blueberries\] - Merged`),
regexp.MustCompile(`#8 Blueberries are probably a good fruit \[blueberries\] - Closed`),
}
for _, r := range unexpectedLines {
if r.MatchString(output.String()) {
t.Errorf("output unexpectedly match regexp /%s/\n> output\n%s\n", r, output)
return
}
}
}
func TestPRStatus_currentBranch_defaultBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranch.json"))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#10 Blueberries are certainly a good fruit \[blueberries\]`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_defaultBranch_repoFlag(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchClosedOnDefaultBranch.json"))
output, err := runCommand(http, "blueberries", true, "-R OWNER/REPO")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#8 Blueberries are a good fruit \[blueberries\]`)
if expectedLine.MatchString(output.String()) {
t.Errorf("output not expected to match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_Closed(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchClosed.json"))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#8 Blueberries are a good fruit \[blueberries\] - Closed`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_Closed_defaultBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchClosedOnDefaultBranch.json"))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`There is no pull request associated with \[blueberries\]`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_Merged(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchMerged.json"))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#8 Blueberries are a good fruit \[blueberries\] - Merged`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_Merged_defaultBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchMergedOnDefaultBranch.json"))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`There is no pull request associated with \[blueberries\]`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_blankSlate(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.StringResponse(`{"data": {}}`))
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expected := `
Relevant pull requests in OWNER/REPO
Current branch
There is no pull request associated with [blueberries]
Created by you
You have no open pull requests
Requesting a code review from you
You have no pull requests to review
`
if output.String() != expected {
t.Errorf("expected %q, got %q", expected, output.String())
}
}
func TestPRStatus_detachedHead(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.StringResponse(`{"data": {}}`))
output, err := runCommand(http, "", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expected := `
Relevant pull requests in OWNER/REPO
Current branch
There is no current branch
Created by you
You have no open pull requests
Requesting a code review from you
You have no pull requests to review
`
if output.String() != expected {
t.Errorf("expected %q, got %q", expected, output.String())
}
}
| pkg/cmd/pr/status/status_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.04428204894065857,
0.04428204894065857,
0.04428204894065857,
0.04428204894065857,
0
] |
{
"id": 1,
"code_window": [
"github.com/microcosm-cc/bluemonday v1.0.6/go.mod h1:HOT/6NaBlR0f9XlxD3zolN6Z3N8Lp4pvhp+jLS5ihnI=\n",
"github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=\n",
"github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=\n",
"github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\n",
"github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=\n",
"github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\n",
"github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=\n",
"github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=\n",
"github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=\n",
"github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=\n",
"github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "go.sum",
"type": "replace",
"edit_start_line_idx": 261
} | // package httpunix provides an http.RoundTripper which dials a server via a unix socket.
package httpunix
import (
"net"
"net/http"
)
// NewRoundTripper returns an http.RoundTripper which sends requests via a unix
// socket at socketPath.
func NewRoundTripper(socketPath string) http.RoundTripper {
dial := func(network, addr string) (net.Conn, error) {
return net.Dial("unix", socketPath)
}
return &http.Transport{
Dial: dial,
DialTLS: dial,
DisableKeepAlives: true,
}
}
| internal/httpunix/transport.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.04428214952349663,
0.04428214952349663,
0.04428214952349663,
0.04428214952349663,
0
] |
{
"id": 2,
"code_window": [
"\t\"os\"\n",
"\t\"path/filepath\"\n",
"\t\"runtime\"\n",
"\t\"syscall\"\n",
"\n",
"\t\"github.com/mitchellh/go-homedir\"\n",
"\t\"gopkg.in/yaml.v3\"\n",
")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 11
} | package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"syscall"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
const (
GH_CONFIG_DIR = "GH_CONFIG_DIR"
XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
XDG_STATE_HOME = "XDG_STATE_HOME"
XDG_DATA_HOME = "XDG_DATA_HOME"
APP_DATA = "AppData"
LOCAL_APP_DATA = "LocalAppData"
)
// Config path precedence
// 1. GH_CONFIG_DIR
// 2. XDG_CONFIG_HOME
// 3. AppData (windows only)
// 4. HOME
func ConfigDir() string {
var path string
if a := os.Getenv(GH_CONFIG_DIR); a != "" {
path = a
} else if b := os.Getenv(XDG_CONFIG_HOME); b != "" {
path = filepath.Join(b, "gh")
} else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" {
path = filepath.Join(c, "GitHub CLI")
} else {
d, _ := os.UserHomeDir()
path = filepath.Join(d, ".config", "gh")
}
// If the path does not exist and the GH_CONFIG_DIR flag is not set try
// migrating config from default paths.
if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" {
_ = autoMigrateConfigDir(path)
}
return path
}
// State path precedence
// 1. XDG_CONFIG_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func StateDir() string {
var path string
if a := os.Getenv(XDG_STATE_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "state", "gh")
}
// If the path does not exist try migrating state from default paths
if !dirExists(path) {
_ = autoMigrateStateDir(path)
}
return path
}
// Data path precedence
// 1. XDG_DATA_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func DataDir() string {
var path string
if a := os.Getenv(XDG_DATA_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "share", "gh")
}
return path
}
var errSamePath = errors.New("same path")
var errNotExist = errors.New("not exist")
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs
// If configs exist then move them to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateConfigDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
return errNotExist
}
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)
// If state file exist then move it to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateStateDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
return errNotExist
}
func migrateFile(oldPath, newPath, file string) error {
if oldPath == newPath {
return errSamePath
}
oldFile := filepath.Join(oldPath, file)
newFile := filepath.Join(newPath, file)
if !fileExists(oldFile) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newFile), 0755)
return os.Rename(oldFile, newFile)
}
func migrateDir(oldPath, newPath string) error {
if oldPath == newPath {
return errSamePath
}
if !dirExists(oldPath) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newPath), 0755)
return os.Rename(oldPath, newPath)
}
func dirExists(path string) bool {
f, err := os.Stat(path)
return err == nil && f.IsDir()
}
func fileExists(path string) bool {
f, err := os.Stat(path)
return err == nil && !f.IsDir()
}
func ConfigFile() string {
return filepath.Join(ConfigDir(), "config.yml")
}
func HostsConfigFile() string {
return filepath.Join(ConfigDir(), "hosts.yml")
}
func ParseDefaultConfig() (Config, error) {
return parseConfig(ConfigFile())
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, subdir), nil
}
return "", err
}
newPath := filepath.Join(homeDir, subdir)
if s, err := os.Stat(newPath); err == nil && s.IsDir() {
return newPath, nil
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, subdir)
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
return legacyPath, nil
}
}
return newPath, nil
}
var ReadConfigFile = func(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, pathError(err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
var WriteConfigFile = func(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return pathError(err)
}
cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup
if err != nil {
return err
}
defer cfgFile.Close()
_, err = cfgFile.Write(data)
return err
}
var BackupConfigFile = func(filename string) error {
return os.Rename(filename, filename+".bak")
}
func parseConfigFile(filename string) ([]byte, *yaml.Node, error) {
data, err := ReadConfigFile(filename)
if err != nil {
return nil, nil, err
}
root, err := parseConfigData(data)
if err != nil {
return nil, nil, err
}
return data, root, err
}
func parseConfigData(data []byte) (*yaml.Node, error) {
var root yaml.Node
err := yaml.Unmarshal(data, &root)
if err != nil {
return nil, err
}
if len(root.Content) == 0 {
return &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
}, nil
}
if root.Content[0].Kind != yaml.MappingNode {
return &root, fmt.Errorf("expected a top level map")
}
return &root, nil
}
func isLegacy(root *yaml.Node) bool {
for _, v := range root.Content[0].Content {
if v.Value == "github.com" {
return true
}
}
return false
}
func migrateConfig(filename string) error {
b, err := ReadConfigFile(filename)
if err != nil {
return err
}
var hosts map[string][]yaml.Node
err = yaml.Unmarshal(b, &hosts)
if err != nil {
return fmt.Errorf("error decoding legacy format: %w", err)
}
cfg := NewBlankConfig()
for hostname, entries := range hosts {
if len(entries) < 1 {
continue
}
mapContent := entries[0].Content
for i := 0; i < len(mapContent)-1; i += 2 {
if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil {
return err
}
}
}
err = BackupConfigFile(filename)
if err != nil {
return fmt.Errorf("failed to back up existing config: %w", err)
}
return cfg.Write()
}
func parseConfig(filename string) (Config, error) {
_, root, err := parseConfigFile(filename)
if err != nil {
if os.IsNotExist(err) {
root = NewBlankRoot()
} else {
return nil, err
}
}
if isLegacy(root) {
err = migrateConfig(filename)
if err != nil {
return nil, fmt.Errorf("error migrating legacy config: %w", err)
}
_, root, err = parseConfigFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to reparse migrated config: %w", err)
}
} else {
if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil {
if len(hostsRoot.Content[0].Content) > 0 {
newContent := []*yaml.Node{
{Value: "hosts"},
hostsRoot.Content[0],
}
restContent := root.Content[0].Content
root.Content[0].Content = append(newContent, restContent...)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return NewConfig(root), nil
}
func pathError(err error) error {
var pathError *os.PathError
if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) {
if p := findRegularFile(pathError.Path); p != "" {
return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p)
}
}
return err
}
func findRegularFile(p string) string {
for {
if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() {
return p
}
newPath := filepath.Dir(p)
if newPath == p || newPath == "/" || newPath == "." {
break
}
p = newPath
}
return ""
}
| internal/config/config_file.go | 1 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.1035434901714325,
0.003827631939202547,
0.00016611859609838575,
0.0003078704758081585,
0.01657870039343834
] |
{
"id": 2,
"code_window": [
"\t\"os\"\n",
"\t\"path/filepath\"\n",
"\t\"runtime\"\n",
"\t\"syscall\"\n",
"\n",
"\t\"github.com/mitchellh/go-homedir\"\n",
"\t\"gopkg.in/yaml.v3\"\n",
")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 11
} | package remove
import (
"bytes"
"fmt"
"net/http"
"testing"
"github.com/cli/cli/internal/config"
"github.com/cli/cli/internal/ghrepo"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/httpmock"
"github.com/cli/cli/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func TestNewCmdRemove(t *testing.T) {
tests := []struct {
name string
cli string
wants RemoveOptions
wantsErr bool
}{
{
name: "no args",
wantsErr: true,
},
{
name: "repo",
cli: "cool",
wants: RemoveOptions{
SecretName: "cool",
},
},
{
name: "org",
cli: "cool --org anOrg",
wants: RemoveOptions{
SecretName: "cool",
OrgName: "anOrg",
},
},
{
name: "env",
cli: "cool --env anEnv",
wants: RemoveOptions{
SecretName: "cool",
EnvName: "anEnv",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: io,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts *RemoveOptions
cmd := NewCmdRemove(f, func(opts *RemoveOptions) error {
gotOpts = opts
return nil
})
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.SecretName, gotOpts.SecretName)
assert.Equal(t, tt.wants.OrgName, gotOpts.OrgName)
assert.Equal(t, tt.wants.EnvName, gotOpts.EnvName)
})
}
}
func Test_removeRun_repo(t *testing.T) {
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("DELETE", "repos/owner/repo/actions/secrets/cool_secret"),
httpmock.StatusStringResponse(204, "No Content"))
io, _, _, _ := iostreams.Test()
opts := &RemoveOptions{
IO: io,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
Config: func() (config.Config, error) {
return config.NewBlankConfig(), nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
SecretName: "cool_secret",
}
err := removeRun(opts)
assert.NoError(t, err)
reg.Verify(t)
}
func Test_removeRun_env(t *testing.T) {
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("DELETE", "repos/owner/repo/environments/development/secrets/cool_secret"),
httpmock.StatusStringResponse(204, "No Content"))
io, _, _, _ := iostreams.Test()
opts := &RemoveOptions{
IO: io,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
Config: func() (config.Config, error) {
return config.NewBlankConfig(), nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
SecretName: "cool_secret",
EnvName: "development",
}
err := removeRun(opts)
assert.NoError(t, err)
reg.Verify(t)
}
func Test_removeRun_org(t *testing.T) {
tests := []struct {
name string
opts *RemoveOptions
}{
{
name: "repo",
opts: &RemoveOptions{},
},
{
name: "org",
opts: &RemoveOptions{
OrgName: "UmbrellaCorporation",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
orgName := tt.opts.OrgName
if orgName == "" {
reg.Register(
httpmock.REST("DELETE", "repos/owner/repo/actions/secrets/tVirus"),
httpmock.StatusStringResponse(204, "No Content"))
} else {
reg.Register(
httpmock.REST("DELETE", fmt.Sprintf("orgs/%s/actions/secrets/tVirus", orgName)),
httpmock.StatusStringResponse(204, "No Content"))
}
io, _, _, _ := iostreams.Test()
tt.opts.Config = func() (config.Config, error) {
return config.NewBlankConfig(), nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.IO = io
tt.opts.SecretName = "tVirus"
err := removeRun(tt.opts)
assert.NoError(t, err)
reg.Verify(t)
})
}
}
| pkg/cmd/secret/remove/remove_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.000247646908974275,
0.00017398459021933377,
0.0001641892158659175,
0.00016994611360132694,
0.000016728165064705536
] |
{
"id": 2,
"code_window": [
"\t\"os\"\n",
"\t\"path/filepath\"\n",
"\t\"runtime\"\n",
"\t\"syscall\"\n",
"\n",
"\t\"github.com/mitchellh/go-homedir\"\n",
"\t\"gopkg.in/yaml.v3\"\n",
")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 11
} | package docs
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/cpuguy83/go-md2man/v2/md2man"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// GenManTree will generate a man page for this command and all descendants
// in the directory given. The header may be nil. This function may not work
// correctly if your command names have `-` in them. If you have `cmd` with two
// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
// it is undefined which help output will be in the file `cmd-sub-third.1`.
func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {
return GenManTreeFromOpts(cmd, GenManTreeOptions{
Header: header,
Path: dir,
CommandSeparator: "-",
})
}
// GenManTreeFromOpts generates a man page for the command and all descendants.
// The pages are written to the opts.Path directory.
func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
header := opts.Header
if header == nil {
header = &GenManHeader{}
}
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
continue
}
if err := GenManTreeFromOpts(c, opts); err != nil {
return err
}
}
section := "1"
if header.Section != "" {
section = header.Section
}
separator := "_"
if opts.CommandSeparator != "" {
separator = opts.CommandSeparator
}
basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)
filename := filepath.Join(opts.Path, basename+"."+section)
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
headerCopy := *header
return GenMan(cmd, &headerCopy, f)
}
// GenManTreeOptions is the options for generating the man pages.
// Used only in GenManTreeFromOpts.
type GenManTreeOptions struct {
Header *GenManHeader
Path string
CommandSeparator string
}
// GenManHeader is a lot like the .TH header at the start of man pages. These
// include the title, section, date, source, and manual. We will use the
// current time if Date is unset.
type GenManHeader struct {
Title string
Section string
Date *time.Time
date string
Source string
Manual string
}
// GenMan will generate a man page for the given command and write it to
// w. The header argument may be nil, however obviously w may not.
func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
if header == nil {
header = &GenManHeader{}
}
if err := fillHeader(header, cmd.CommandPath()); err != nil {
return err
}
b := genMan(cmd, header)
_, err := w.Write(md2man.Render(b))
return err
}
func fillHeader(header *GenManHeader, name string) error {
if header.Title == "" {
header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
}
if header.Section == "" {
header.Section = "1"
}
if header.Date == nil {
now := time.Now()
if epoch := os.Getenv("SOURCE_DATE_EPOCH"); epoch != "" {
unixEpoch, err := strconv.ParseInt(epoch, 10, 64)
if err != nil {
return fmt.Errorf("invalid SOURCE_DATE_EPOCH: %v", err)
}
now = time.Unix(unixEpoch, 0)
}
header.Date = &now
}
header.date = (*header.Date).Format("Jan 2006")
return nil
}
func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) {
description := cmd.Long
if len(description) == 0 {
description = cmd.Short
}
buf.WriteString(fmt.Sprintf(`%% "%s" "%s" "%s" "%s" "%s"
# NAME
`, header.Title, header.Section, header.date, header.Source, header.Manual))
buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))
buf.WriteString("# SYNOPSIS\n")
buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine()))
buf.WriteString("# DESCRIPTION\n")
buf.WriteString(description + "\n\n")
}
func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) {
flags.VisitAll(func(flag *pflag.Flag) {
if len(flag.Deprecated) > 0 || flag.Hidden {
return
}
format := ""
if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name)
} else {
format = fmt.Sprintf("**--%s**", flag.Name)
}
if len(flag.NoOptDefVal) > 0 {
format += "["
}
if flag.Value.Type() == "string" {
// put quotes on the value
format += "=%q"
} else {
format += "=%s"
}
if len(flag.NoOptDefVal) > 0 {
format += "]"
}
format += "\n\t%s\n\n"
buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage))
})
}
func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {
flags := command.NonInheritedFlags()
if flags.HasAvailableFlags() {
buf.WriteString("# OPTIONS\n")
manPrintFlags(buf, flags)
buf.WriteString("\n")
}
flags = command.InheritedFlags()
if flags.HasAvailableFlags() {
buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n")
manPrintFlags(buf, flags)
buf.WriteString("\n")
}
}
func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
cmd.InitDefaultHelpCmd()
cmd.InitDefaultHelpFlag()
// something like `rootcmd-subcmd1-subcmd2`
dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
buf := new(bytes.Buffer)
manPreamble(buf, header, cmd, dashCommandName)
manPrintOptions(buf, cmd)
if len(cmd.Example) > 0 {
buf.WriteString("# EXAMPLE\n")
buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example))
}
if hasSeeAlso(cmd) {
buf.WriteString("# SEE ALSO\n")
seealsos := make([]string, 0)
if cmd.HasParent() {
parentPath := cmd.Parent().CommandPath()
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section)
seealsos = append(seealsos, seealso)
}
children := cmd.Commands()
sort.Sort(byName(children))
for _, c := range children {
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
continue
}
seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
seealsos = append(seealsos, seealso)
}
buf.WriteString(strings.Join(seealsos, ", ") + "\n")
}
return buf.Bytes()
}
// Test to see if we have a reason to print See Also information in docs
// Basically this is a test for a parent command or a subcommand which is
// both not deprecated and not the autogenerated help command.
func hasSeeAlso(cmd *cobra.Command) bool {
if cmd.HasParent() {
return true
}
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
continue
}
return true
}
return false
}
type byName []*cobra.Command
func (s byName) Len() int { return len(s) }
func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
| internal/docs/man.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.0007070396677590907,
0.00024405673320870847,
0.00016321317525580525,
0.0001735259429551661,
0.00014772938448004425
] |
{
"id": 2,
"code_window": [
"\t\"os\"\n",
"\t\"path/filepath\"\n",
"\t\"runtime\"\n",
"\t\"syscall\"\n",
"\n",
"\t\"github.com/mitchellh/go-homedir\"\n",
"\t\"gopkg.in/yaml.v3\"\n",
")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 11
} | package utils
import (
"fmt"
"net/url"
"strings"
"time"
)
func Pluralize(num int, thing string) string {
if num == 1 {
return fmt.Sprintf("%d %s", num, thing)
}
return fmt.Sprintf("%d %ss", num, thing)
}
func fmtDuration(amount int, unit string) string {
return fmt.Sprintf("about %s ago", Pluralize(amount, unit))
}
func FuzzyAgo(ago time.Duration) string {
if ago < time.Minute {
return "less than a minute ago"
}
if ago < time.Hour {
return fmtDuration(int(ago.Minutes()), "minute")
}
if ago < 24*time.Hour {
return fmtDuration(int(ago.Hours()), "hour")
}
if ago < 30*24*time.Hour {
return fmtDuration(int(ago.Hours())/24, "day")
}
if ago < 365*24*time.Hour {
return fmtDuration(int(ago.Hours())/24/30, "month")
}
return fmtDuration(int(ago.Hours()/24/365), "year")
}
func FuzzyAgoAbbr(now time.Time, createdAt time.Time) string {
ago := now.Sub(createdAt)
if ago < time.Hour {
return fmt.Sprintf("%d%s", int(ago.Minutes()), "m")
}
if ago < 24*time.Hour {
return fmt.Sprintf("%d%s", int(ago.Hours()), "h")
}
if ago < 30*24*time.Hour {
return fmt.Sprintf("%d%s", int(ago.Hours())/24, "d")
}
return createdAt.Format("Jan _2, 2006")
}
func Humanize(s string) string {
// Replaces - and _ with spaces.
replace := "_-"
h := func(r rune) rune {
if strings.ContainsRune(replace, r) {
return ' '
}
return r
}
return strings.Map(h, s)
}
func IsURL(s string) bool {
return strings.HasPrefix(s, "http:/") || strings.HasPrefix(s, "https:/")
}
func DisplayURL(urlStr string) string {
u, err := url.Parse(urlStr)
if err != nil {
return urlStr
}
return u.Hostname() + u.Path
}
// Maximum length of a URL: 8192 bytes
func ValidURL(urlStr string) bool {
return len(urlStr) < 8192
}
| utils/utils.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00019201500981580466,
0.00017401232616975904,
0.00016622776456642896,
0.00017049470625352114,
0.000008823571988614276
] |
{
"id": 3,
"code_window": [
"\n",
"var errSamePath = errors.New(\"same path\")\n",
"var errNotExist = errors.New(\"not exist\")\n",
"\n",
"// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs\n",
"// If configs exist then move them to newPath\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"// Check default path, os.UserHomeDir, for existing configs\n"
],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 95
} | package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"syscall"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
const (
GH_CONFIG_DIR = "GH_CONFIG_DIR"
XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
XDG_STATE_HOME = "XDG_STATE_HOME"
XDG_DATA_HOME = "XDG_DATA_HOME"
APP_DATA = "AppData"
LOCAL_APP_DATA = "LocalAppData"
)
// Config path precedence
// 1. GH_CONFIG_DIR
// 2. XDG_CONFIG_HOME
// 3. AppData (windows only)
// 4. HOME
func ConfigDir() string {
var path string
if a := os.Getenv(GH_CONFIG_DIR); a != "" {
path = a
} else if b := os.Getenv(XDG_CONFIG_HOME); b != "" {
path = filepath.Join(b, "gh")
} else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" {
path = filepath.Join(c, "GitHub CLI")
} else {
d, _ := os.UserHomeDir()
path = filepath.Join(d, ".config", "gh")
}
// If the path does not exist and the GH_CONFIG_DIR flag is not set try
// migrating config from default paths.
if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" {
_ = autoMigrateConfigDir(path)
}
return path
}
// State path precedence
// 1. XDG_CONFIG_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func StateDir() string {
var path string
if a := os.Getenv(XDG_STATE_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "state", "gh")
}
// If the path does not exist try migrating state from default paths
if !dirExists(path) {
_ = autoMigrateStateDir(path)
}
return path
}
// Data path precedence
// 1. XDG_DATA_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func DataDir() string {
var path string
if a := os.Getenv(XDG_DATA_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "share", "gh")
}
return path
}
var errSamePath = errors.New("same path")
var errNotExist = errors.New("not exist")
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs
// If configs exist then move them to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateConfigDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
return errNotExist
}
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)
// If state file exist then move it to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateStateDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
return errNotExist
}
func migrateFile(oldPath, newPath, file string) error {
if oldPath == newPath {
return errSamePath
}
oldFile := filepath.Join(oldPath, file)
newFile := filepath.Join(newPath, file)
if !fileExists(oldFile) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newFile), 0755)
return os.Rename(oldFile, newFile)
}
func migrateDir(oldPath, newPath string) error {
if oldPath == newPath {
return errSamePath
}
if !dirExists(oldPath) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newPath), 0755)
return os.Rename(oldPath, newPath)
}
func dirExists(path string) bool {
f, err := os.Stat(path)
return err == nil && f.IsDir()
}
func fileExists(path string) bool {
f, err := os.Stat(path)
return err == nil && !f.IsDir()
}
func ConfigFile() string {
return filepath.Join(ConfigDir(), "config.yml")
}
func HostsConfigFile() string {
return filepath.Join(ConfigDir(), "hosts.yml")
}
func ParseDefaultConfig() (Config, error) {
return parseConfig(ConfigFile())
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, subdir), nil
}
return "", err
}
newPath := filepath.Join(homeDir, subdir)
if s, err := os.Stat(newPath); err == nil && s.IsDir() {
return newPath, nil
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, subdir)
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
return legacyPath, nil
}
}
return newPath, nil
}
var ReadConfigFile = func(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, pathError(err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
var WriteConfigFile = func(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return pathError(err)
}
cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup
if err != nil {
return err
}
defer cfgFile.Close()
_, err = cfgFile.Write(data)
return err
}
var BackupConfigFile = func(filename string) error {
return os.Rename(filename, filename+".bak")
}
func parseConfigFile(filename string) ([]byte, *yaml.Node, error) {
data, err := ReadConfigFile(filename)
if err != nil {
return nil, nil, err
}
root, err := parseConfigData(data)
if err != nil {
return nil, nil, err
}
return data, root, err
}
func parseConfigData(data []byte) (*yaml.Node, error) {
var root yaml.Node
err := yaml.Unmarshal(data, &root)
if err != nil {
return nil, err
}
if len(root.Content) == 0 {
return &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
}, nil
}
if root.Content[0].Kind != yaml.MappingNode {
return &root, fmt.Errorf("expected a top level map")
}
return &root, nil
}
func isLegacy(root *yaml.Node) bool {
for _, v := range root.Content[0].Content {
if v.Value == "github.com" {
return true
}
}
return false
}
func migrateConfig(filename string) error {
b, err := ReadConfigFile(filename)
if err != nil {
return err
}
var hosts map[string][]yaml.Node
err = yaml.Unmarshal(b, &hosts)
if err != nil {
return fmt.Errorf("error decoding legacy format: %w", err)
}
cfg := NewBlankConfig()
for hostname, entries := range hosts {
if len(entries) < 1 {
continue
}
mapContent := entries[0].Content
for i := 0; i < len(mapContent)-1; i += 2 {
if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil {
return err
}
}
}
err = BackupConfigFile(filename)
if err != nil {
return fmt.Errorf("failed to back up existing config: %w", err)
}
return cfg.Write()
}
func parseConfig(filename string) (Config, error) {
_, root, err := parseConfigFile(filename)
if err != nil {
if os.IsNotExist(err) {
root = NewBlankRoot()
} else {
return nil, err
}
}
if isLegacy(root) {
err = migrateConfig(filename)
if err != nil {
return nil, fmt.Errorf("error migrating legacy config: %w", err)
}
_, root, err = parseConfigFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to reparse migrated config: %w", err)
}
} else {
if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil {
if len(hostsRoot.Content[0].Content) > 0 {
newContent := []*yaml.Node{
{Value: "hosts"},
hostsRoot.Content[0],
}
restContent := root.Content[0].Content
root.Content[0].Content = append(newContent, restContent...)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return NewConfig(root), nil
}
func pathError(err error) error {
var pathError *os.PathError
if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) {
if p := findRegularFile(pathError.Path); p != "" {
return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p)
}
}
return err
}
func findRegularFile(p string) string {
for {
if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() {
return p
}
newPath := filepath.Dir(p)
if newPath == p || newPath == "/" || newPath == "." {
break
}
p = newPath
}
return ""
}
| internal/config/config_file.go | 1 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.9989995360374451,
0.2160048931837082,
0.00016638697707094252,
0.0007864731596782804,
0.40451523661613464
] |
{
"id": 3,
"code_window": [
"\n",
"var errSamePath = errors.New(\"same path\")\n",
"var errNotExist = errors.New(\"not exist\")\n",
"\n",
"// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs\n",
"// If configs exist then move them to newPath\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"// Check default path, os.UserHomeDir, for existing configs\n"
],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 95
} | {
"data": {
"node": {
"comments": {
"nodes": [
{
"author": {
"login": "monalisa"
},
"authorAssociation": "NONE",
"body": "Comment 1",
"createdAt": "2020-01-01T12:00:00Z",
"includesCreatedEdit": true,
"reactionGroups": [
{
"content": "CONFUSED",
"users": {
"totalCount": 1
}
},
{
"content": "EYES",
"users": {
"totalCount": 2
}
},
{
"content": "HEART",
"users": {
"totalCount": 3
}
},
{
"content": "HOORAY",
"users": {
"totalCount": 4
}
},
{
"content": "LAUGH",
"users": {
"totalCount": 5
}
},
{
"content": "ROCKET",
"users": {
"totalCount": 6
}
},
{
"content": "THUMBS_DOWN",
"users": {
"totalCount": 7
}
},
{
"content": "THUMBS_UP",
"users": {
"totalCount": 8
}
}
]
},
{
"author": {
"login": "johnnytest"
},
"authorAssociation": "CONTRIBUTOR",
"body": "Comment 2",
"createdAt": "2020-01-01T12:00:00Z",
"includesCreatedEdit": false,
"reactionGroups": [
{
"content": "CONFUSED",
"users": {
"totalCount": 0
}
},
{
"content": "EYES",
"users": {
"totalCount": 0
}
},
{
"content": "HEART",
"users": {
"totalCount": 0
}
},
{
"content": "HOORAY",
"users": {
"totalCount": 0
}
},
{
"content": "LAUGH",
"users": {
"totalCount": 0
}
},
{
"content": "ROCKET",
"users": {
"totalCount": 0
}
},
{
"content": "THUMBS_DOWN",
"users": {
"totalCount": 0
}
},
{
"content": "THUMBS_UP",
"users": {
"totalCount": 0
}
}
]
},
{
"author": {
"login": "elvisp"
},
"authorAssociation": "MEMBER",
"body": "Comment 3",
"createdAt": "2020-01-01T12:00:00Z",
"includesCreatedEdit": false,
"reactionGroups": [
{
"content": "CONFUSED",
"users": {
"totalCount": 0
}
},
{
"content": "EYES",
"users": {
"totalCount": 0
}
},
{
"content": "HEART",
"users": {
"totalCount": 0
}
},
{
"content": "HOORAY",
"users": {
"totalCount": 0
}
},
{
"content": "LAUGH",
"users": {
"totalCount": 0
}
},
{
"content": "ROCKET",
"users": {
"totalCount": 0
}
},
{
"content": "THUMBS_DOWN",
"users": {
"totalCount": 0
}
},
{
"content": "THUMBS_UP",
"users": {
"totalCount": 0
}
}
]
},
{
"author": {
"login": "loislane"
},
"authorAssociation": "OWNER",
"body": "Comment 4",
"createdAt": "2020-01-01T12:00:00Z",
"includesCreatedEdit": false,
"reactionGroups": [
{
"content": "CONFUSED",
"users": {
"totalCount": 0
}
},
{
"content": "EYES",
"users": {
"totalCount": 0
}
},
{
"content": "HEART",
"users": {
"totalCount": 0
}
},
{
"content": "HOORAY",
"users": {
"totalCount": 0
}
},
{
"content": "LAUGH",
"users": {
"totalCount": 0
}
},
{
"content": "ROCKET",
"users": {
"totalCount": 0
}
},
{
"content": "THUMBS_DOWN",
"users": {
"totalCount": 0
}
},
{
"content": "THUMBS_UP",
"users": {
"totalCount": 0
}
}
]
},
{
"author": {
"login": "sam-spam"
},
"authorAssociation": "NONE",
"body": "Spam comment",
"createdAt": "2020-01-01T12:00:00Z",
"includesCreatedEdit": true,
"isMinimized": true,
"minimizedReason": "spam",
"reactionGroups": []
},
{
"author": {
"login": "marseilles"
},
"authorAssociation": "COLLABORATOR",
"body": "Comment 5",
"createdAt": "2020-01-01T12:00:00Z",
"includesCreatedEdit": false,
"reactionGroups": [
{
"content": "CONFUSED",
"users": {
"totalCount": 0
}
},
{
"content": "EYES",
"users": {
"totalCount": 0
}
},
{
"content": "HEART",
"users": {
"totalCount": 0
}
},
{
"content": "HOORAY",
"users": {
"totalCount": 0
}
},
{
"content": "LAUGH",
"users": {
"totalCount": 0
}
},
{
"content": "ROCKET",
"users": {
"totalCount": 0
}
},
{
"content": "THUMBS_DOWN",
"users": {
"totalCount": 0
}
},
{
"content": "THUMBS_UP",
"users": {
"totalCount": 0
}
}
]
}
],
"totalCount": 6
}
}
}
}
| pkg/cmd/issue/view/fixtures/issueView_previewFullComments.json | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00017345893138553947,
0.000169804974575527,
0.00016632447659503669,
0.00016955920727923512,
0.0000016312847037625033
] |
{
"id": 3,
"code_window": [
"\n",
"var errSamePath = errors.New(\"same path\")\n",
"var errNotExist = errors.New(\"not exist\")\n",
"\n",
"// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs\n",
"// If configs exist then move them to newPath\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"// Check default path, os.UserHomeDir, for existing configs\n"
],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 95
} | package sync
import (
"github.com/stretchr/testify/mock"
)
type mockGitClient struct {
mock.Mock
}
func (g *mockGitClient) BranchRemote(a string) (string, error) {
args := g.Called(a)
return args.String(0), args.Error(1)
}
func (g *mockGitClient) UpdateBranch(b, r string) error {
args := g.Called(b, r)
return args.Error(0)
}
func (g *mockGitClient) CreateBranch(b, r, u string) error {
args := g.Called(b, r, u)
return args.Error(0)
}
func (g *mockGitClient) CurrentBranch() (string, error) {
args := g.Called()
return args.String(0), args.Error(1)
}
func (g *mockGitClient) Fetch(a, b string) error {
args := g.Called(a, b)
return args.Error(0)
}
func (g *mockGitClient) HasLocalBranch(a string) bool {
args := g.Called(a)
return args.Bool(0)
}
func (g *mockGitClient) IsAncestor(a, b string) (bool, error) {
args := g.Called(a, b)
return args.Bool(0), args.Error(1)
}
func (g *mockGitClient) IsDirty() (bool, error) {
args := g.Called()
return args.Bool(0), args.Error(1)
}
func (g *mockGitClient) MergeFastForward(a string) error {
args := g.Called(a)
return args.Error(0)
}
func (g *mockGitClient) ResetHard(a string) error {
args := g.Called(a)
return args.Error(0)
}
| pkg/cmd/repo/sync/mocks.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00017067737644538283,
0.00016906058590393513,
0.00016785987827461213,
0.00016907043755054474,
9.324726306658704e-7
] |
{
"id": 3,
"code_window": [
"\n",
"var errSamePath = errors.New(\"same path\")\n",
"var errNotExist = errors.New(\"not exist\")\n",
"\n",
"// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs\n",
"// If configs exist then move them to newPath\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"// Check default path, os.UserHomeDir, for existing configs\n"
],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 95
} | package main
import (
"bytes"
"errors"
"fmt"
"net"
"testing"
"github.com/cli/cli/pkg/cmdutil"
"github.com/spf13/cobra"
)
func Test_printError(t *testing.T) {
cmd := &cobra.Command{}
type args struct {
err error
cmd *cobra.Command
debug bool
}
tests := []struct {
name string
args args
wantOut string
}{
{
name: "generic error",
args: args{
err: errors.New("the app exploded"),
cmd: nil,
debug: false,
},
wantOut: "the app exploded\n",
},
{
name: "DNS error",
args: args{
err: fmt.Errorf("DNS oopsie: %w", &net.DNSError{
Name: "api.github.com",
}),
cmd: nil,
debug: false,
},
wantOut: `error connecting to api.github.com
check your internet connection or githubstatus.com
`,
},
{
name: "Cobra flag error",
args: args{
err: &cmdutil.FlagError{Err: errors.New("unknown flag --foo")},
cmd: cmd,
debug: false,
},
wantOut: "unknown flag --foo\n\nUsage:\n\n",
},
{
name: "unknown Cobra command error",
args: args{
err: errors.New("unknown command foo"),
cmd: cmd,
debug: false,
},
wantOut: "unknown command foo\n\nUsage:\n\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
out := &bytes.Buffer{}
printError(out, tt.args.err, tt.args.cmd, tt.args.debug)
if gotOut := out.String(); gotOut != tt.wantOut {
t.Errorf("printError() = %q, want %q", gotOut, tt.wantOut)
}
})
}
}
| cmd/gh/main_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00017131242202594876,
0.00016887302626855671,
0.00016738679551053792,
0.00016881825285963714,
0.0000011664366184049868
] |
{
"id": 4,
"code_window": [
"// If configs exist then move them to newPath\n",
"// TODO: Remove support for homedir.Dir location in v2\n",
"func autoMigrateConfigDir(newPath string) error {\n",
"\tpath, err := os.UserHomeDir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 97
} | package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"syscall"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
const (
GH_CONFIG_DIR = "GH_CONFIG_DIR"
XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
XDG_STATE_HOME = "XDG_STATE_HOME"
XDG_DATA_HOME = "XDG_DATA_HOME"
APP_DATA = "AppData"
LOCAL_APP_DATA = "LocalAppData"
)
// Config path precedence
// 1. GH_CONFIG_DIR
// 2. XDG_CONFIG_HOME
// 3. AppData (windows only)
// 4. HOME
func ConfigDir() string {
var path string
if a := os.Getenv(GH_CONFIG_DIR); a != "" {
path = a
} else if b := os.Getenv(XDG_CONFIG_HOME); b != "" {
path = filepath.Join(b, "gh")
} else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" {
path = filepath.Join(c, "GitHub CLI")
} else {
d, _ := os.UserHomeDir()
path = filepath.Join(d, ".config", "gh")
}
// If the path does not exist and the GH_CONFIG_DIR flag is not set try
// migrating config from default paths.
if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" {
_ = autoMigrateConfigDir(path)
}
return path
}
// State path precedence
// 1. XDG_CONFIG_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func StateDir() string {
var path string
if a := os.Getenv(XDG_STATE_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "state", "gh")
}
// If the path does not exist try migrating state from default paths
if !dirExists(path) {
_ = autoMigrateStateDir(path)
}
return path
}
// Data path precedence
// 1. XDG_DATA_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func DataDir() string {
var path string
if a := os.Getenv(XDG_DATA_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "share", "gh")
}
return path
}
var errSamePath = errors.New("same path")
var errNotExist = errors.New("not exist")
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs
// If configs exist then move them to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateConfigDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
return errNotExist
}
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)
// If state file exist then move it to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateStateDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
return errNotExist
}
func migrateFile(oldPath, newPath, file string) error {
if oldPath == newPath {
return errSamePath
}
oldFile := filepath.Join(oldPath, file)
newFile := filepath.Join(newPath, file)
if !fileExists(oldFile) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newFile), 0755)
return os.Rename(oldFile, newFile)
}
func migrateDir(oldPath, newPath string) error {
if oldPath == newPath {
return errSamePath
}
if !dirExists(oldPath) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newPath), 0755)
return os.Rename(oldPath, newPath)
}
func dirExists(path string) bool {
f, err := os.Stat(path)
return err == nil && f.IsDir()
}
func fileExists(path string) bool {
f, err := os.Stat(path)
return err == nil && !f.IsDir()
}
func ConfigFile() string {
return filepath.Join(ConfigDir(), "config.yml")
}
func HostsConfigFile() string {
return filepath.Join(ConfigDir(), "hosts.yml")
}
func ParseDefaultConfig() (Config, error) {
return parseConfig(ConfigFile())
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, subdir), nil
}
return "", err
}
newPath := filepath.Join(homeDir, subdir)
if s, err := os.Stat(newPath); err == nil && s.IsDir() {
return newPath, nil
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, subdir)
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
return legacyPath, nil
}
}
return newPath, nil
}
var ReadConfigFile = func(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, pathError(err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
var WriteConfigFile = func(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return pathError(err)
}
cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup
if err != nil {
return err
}
defer cfgFile.Close()
_, err = cfgFile.Write(data)
return err
}
var BackupConfigFile = func(filename string) error {
return os.Rename(filename, filename+".bak")
}
func parseConfigFile(filename string) ([]byte, *yaml.Node, error) {
data, err := ReadConfigFile(filename)
if err != nil {
return nil, nil, err
}
root, err := parseConfigData(data)
if err != nil {
return nil, nil, err
}
return data, root, err
}
func parseConfigData(data []byte) (*yaml.Node, error) {
var root yaml.Node
err := yaml.Unmarshal(data, &root)
if err != nil {
return nil, err
}
if len(root.Content) == 0 {
return &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
}, nil
}
if root.Content[0].Kind != yaml.MappingNode {
return &root, fmt.Errorf("expected a top level map")
}
return &root, nil
}
func isLegacy(root *yaml.Node) bool {
for _, v := range root.Content[0].Content {
if v.Value == "github.com" {
return true
}
}
return false
}
func migrateConfig(filename string) error {
b, err := ReadConfigFile(filename)
if err != nil {
return err
}
var hosts map[string][]yaml.Node
err = yaml.Unmarshal(b, &hosts)
if err != nil {
return fmt.Errorf("error decoding legacy format: %w", err)
}
cfg := NewBlankConfig()
for hostname, entries := range hosts {
if len(entries) < 1 {
continue
}
mapContent := entries[0].Content
for i := 0; i < len(mapContent)-1; i += 2 {
if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil {
return err
}
}
}
err = BackupConfigFile(filename)
if err != nil {
return fmt.Errorf("failed to back up existing config: %w", err)
}
return cfg.Write()
}
func parseConfig(filename string) (Config, error) {
_, root, err := parseConfigFile(filename)
if err != nil {
if os.IsNotExist(err) {
root = NewBlankRoot()
} else {
return nil, err
}
}
if isLegacy(root) {
err = migrateConfig(filename)
if err != nil {
return nil, fmt.Errorf("error migrating legacy config: %w", err)
}
_, root, err = parseConfigFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to reparse migrated config: %w", err)
}
} else {
if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil {
if len(hostsRoot.Content[0].Content) > 0 {
newContent := []*yaml.Node{
{Value: "hosts"},
hostsRoot.Content[0],
}
restContent := root.Content[0].Content
root.Content[0].Content = append(newContent, restContent...)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return NewConfig(root), nil
}
func pathError(err error) error {
var pathError *os.PathError
if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) {
if p := findRegularFile(pathError.Path); p != "" {
return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p)
}
}
return err
}
func findRegularFile(p string) string {
for {
if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() {
return p
}
newPath := filepath.Dir(p)
if newPath == p || newPath == "/" || newPath == "." {
break
}
p = newPath
}
return ""
}
| internal/config/config_file.go | 1 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.9992033839225769,
0.4161956310272217,
0.00017032393952831626,
0.05475359410047531,
0.46404531598091125
] |
{
"id": 4,
"code_window": [
"// If configs exist then move them to newPath\n",
"// TODO: Remove support for homedir.Dir location in v2\n",
"func autoMigrateConfigDir(newPath string) error {\n",
"\tpath, err := os.UserHomeDir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 97
} | package httpmock
import (
"fmt"
)
// TODO: clean up methods in this file when there are no more callers
func (r *Registry) StubRepoInfoResponse(owner, repo, branch string) {
r.Register(
GraphQL(`query RepositoryInfo\b`),
StringResponse(fmt.Sprintf(`
{ "data": { "repository": {
"id": "REPOID",
"name": "%s",
"owner": {"login": "%s"},
"description": "",
"defaultBranchRef": {"name": "%s"},
"hasIssuesEnabled": true,
"viewerPermission": "WRITE"
} } }
`, repo, owner, branch)))
}
func (r *Registry) StubRepoResponse(owner, repo string) {
r.StubRepoResponseWithPermission(owner, repo, "WRITE")
}
func (r *Registry) StubRepoResponseWithPermission(owner, repo, permission string) {
r.Register(GraphQL(`query RepositoryNetwork\b`), StringResponse(RepoNetworkStubResponse(owner, repo, "master", permission)))
}
func RepoNetworkStubResponse(owner, repo, defaultBranch, permission string) string {
return fmt.Sprintf(`
{ "data": { "repo_000": {
"id": "REPOID",
"name": "%s",
"owner": {"login": "%s"},
"defaultBranchRef": {
"name": "%s"
},
"viewerPermission": "%s"
} } }
`, repo, owner, defaultBranch, permission)
}
| pkg/httpmock/legacy.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.0002190672094002366,
0.00017855000623967499,
0.00016547074483241886,
0.00016874524590093642,
0.00002034501994785387
] |
{
"id": 4,
"code_window": [
"// If configs exist then move them to newPath\n",
"// TODO: Remove support for homedir.Dir location in v2\n",
"func autoMigrateConfigDir(newPath string) error {\n",
"\tpath, err := os.UserHomeDir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 97
} | 6f1a2405cace1633d89a79c74c65f22fe78f9659
| git/fixtures/simple.git/refs/heads/main | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.0001657300308579579,
0.0001657300308579579,
0.0001657300308579579,
0.0001657300308579579,
0
] |
{
"id": 4,
"code_window": [
"// If configs exist then move them to newPath\n",
"// TODO: Remove support for homedir.Dir location in v2\n",
"func autoMigrateConfigDir(newPath string) error {\n",
"\tpath, err := os.UserHomeDir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 97
} | package add
import (
"net/http"
"testing"
"github.com/cli/cli/internal/config"
"github.com/cli/cli/pkg/httpmock"
"github.com/cli/cli/pkg/iostreams"
"github.com/stretchr/testify/assert"
)
func Test_runAdd(t *testing.T) {
io, stdin, stdout, stderr := iostreams.Test()
io.SetStdinTTY(false)
io.SetStdoutTTY(true)
io.SetStderrTTY(true)
stdin.WriteString("PUBKEY")
tr := httpmock.Registry{}
defer tr.Verify(t)
tr.Register(
httpmock.REST("POST", "user/keys"),
httpmock.StringResponse(`{}`))
err := runAdd(&AddOptions{
IO: io,
Config: func() (config.Config, error) {
return config.NewBlankConfig(), nil
},
HTTPClient: func() (*http.Client, error) {
return &http.Client{Transport: &tr}, nil
},
KeyFile: "-",
Title: "my sacred key",
})
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "β Public key added to your account\n", stderr.String())
}
| pkg/cmd/ssh-key/add/add_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.005674980115145445,
0.0012875994434580207,
0.00016660017718095332,
0.00017113790090661496,
0.0021939703729003668
] |
{
"id": 5,
"code_window": [
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n",
"\t}\n",
"\n",
"\tpath, err = homedir.Dir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n",
"\t}\n",
"\n",
"\treturn errNotExist\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 104
} | module github.com/cli/cli
go 1.13
require (
github.com/AlecAivazis/survey/v2 v2.2.14
github.com/MakeNowJust/heredoc v1.0.0
github.com/briandowns/spinner v1.11.1
github.com/charmbracelet/glamour v0.3.0
github.com/cli/browser v1.1.0
github.com/cli/oauth v0.8.0
github.com/cli/safeexec v1.0.0
github.com/cpuguy83/go-md2man/v2 v2.0.0
github.com/creack/pty v1.1.13
github.com/gabriel-vasile/mimetype v1.1.2
github.com/google/go-cmp v0.5.5
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
github.com/hashicorp/go-version v1.2.1
github.com/henvic/httpretty v0.0.6
github.com/itchyny/gojq v0.12.4
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/mattn/go-colorable v0.1.8
github.com/mattn/go-isatty v0.0.13
github.com/mattn/go-runewidth v0.0.10
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d
github.com/mitchellh/go-homedir v1.1.0
github.com/muesli/termenv v0.8.1
github.com/rivo/uniseg v0.2.0
github.com/shurcooL/githubv4 v0.0.0-20200928013246-d292edc3691b
github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f
github.com/spf13/cobra v1.2.1
github.com/spf13/pflag v1.0.5
github.com/stretchr/objx v0.1.1 // indirect
github.com/stretchr/testify v1.7.0
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/sys v0.0.0-20210601080250-7ecdf8ef093b
golang.org/x/term v0.0.0-20210503060354-a79de5458b56
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
)
replace github.com/shurcooL/graphql => github.com/cli/shurcooL-graphql v0.0.0-20200707151639-0f7232a2bf7e
| go.mod | 1 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.0001759959413902834,
0.00017090063192881644,
0.00016205986321438104,
0.00017176108667626977,
0.000004770245141116902
] |
{
"id": 5,
"code_window": [
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n",
"\t}\n",
"\n",
"\tpath, err = homedir.Dir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n",
"\t}\n",
"\n",
"\treturn errNotExist\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 104
} | package set
import (
"bytes"
"io/ioutil"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/internal/config"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/extensions"
"github.com/cli/cli/pkg/iostreams"
"github.com/cli/cli/test"
"github.com/google/shlex"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func runCommand(cfg config.Config, isTTY bool, cli string, in string) (*test.CmdOut, error) {
io, stdin, stdout, stderr := iostreams.Test()
io.SetStdoutTTY(isTTY)
io.SetStdinTTY(isTTY)
io.SetStderrTTY(isTTY)
stdin.WriteString(in)
factory := &cmdutil.Factory{
IOStreams: io,
Config: func() (config.Config, error) {
return cfg, nil
},
ExtensionManager: &extensions.ExtensionManagerMock{
ListFunc: func(bool) []extensions.Extension {
return []extensions.Extension{}
},
},
}
cmd := NewCmdSet(factory, nil)
// fake command nesting structure needed for validCommand
rootCmd := &cobra.Command{}
rootCmd.AddCommand(cmd)
prCmd := &cobra.Command{Use: "pr"}
prCmd.AddCommand(&cobra.Command{Use: "checkout"})
prCmd.AddCommand(&cobra.Command{Use: "status"})
rootCmd.AddCommand(prCmd)
issueCmd := &cobra.Command{Use: "issue"}
issueCmd.AddCommand(&cobra.Command{Use: "list"})
rootCmd.AddCommand(issueCmd)
apiCmd := &cobra.Command{Use: "api"}
apiCmd.AddCommand(&cobra.Command{Use: "graphql"})
rootCmd.AddCommand(apiCmd)
argv, err := shlex.Split("set " + cli)
if err != nil {
return nil, err
}
rootCmd.SetArgs(argv)
rootCmd.SetIn(stdin)
rootCmd.SetOut(ioutil.Discard)
rootCmd.SetErr(ioutil.Discard)
_, err = rootCmd.ExecuteC()
return &test.CmdOut{
OutBuf: stdout,
ErrBuf: stderr,
}, err
}
func TestAliasSet_gh_command(t *testing.T) {
defer config.StubWriteConfig(ioutil.Discard, ioutil.Discard)()
cfg := config.NewFromString(``)
_, err := runCommand(cfg, true, "pr 'pr status'", "")
assert.EqualError(t, err, `could not create alias: "pr" is already a gh command`)
}
func TestAliasSet_empty_aliases(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(heredoc.Doc(`
aliases:
editor: vim
`))
output, err := runCommand(cfg, true, "co 'pr checkout'", "")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), "Added alias")
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.String(), "")
expected := `aliases:
co: pr checkout
editor: vim
`
assert.Equal(t, expected, mainBuf.String())
}
func TestAliasSet_existing_alias(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(heredoc.Doc(`
aliases:
co: pr checkout
`))
output, err := runCommand(cfg, true, "co 'pr checkout -Rcool/repo'", "")
require.NoError(t, err)
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), "Changed alias.*co.*from.*pr checkout.*to.*pr checkout -Rcool/repo")
}
func TestAliasSet_space_args(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(``)
output, err := runCommand(cfg, true, `il 'issue list -l "cool story"'`, "")
require.NoError(t, err)
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), `Adding alias for.*il.*issue list -l "cool story"`)
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, mainBuf.String(), `il: issue list -l "cool story"`)
}
func TestAliasSet_arg_processing(t *testing.T) {
cases := []struct {
Cmd string
ExpectedOutputLine string
ExpectedConfigLine string
}{
{`il "issue list"`, "- Adding alias for.*il.*issue list", "il: issue list"},
{`iz 'issue list'`, "- Adding alias for.*iz.*issue list", "iz: issue list"},
{`ii 'issue list --author="$1" --label="$2"'`,
`- Adding alias for.*ii.*issue list --author="\$1" --label="\$2"`,
`ii: issue list --author="\$1" --label="\$2"`},
{`ix "issue list --author='\$1' --label='\$2'"`,
`- Adding alias for.*ix.*issue list --author='\$1' --label='\$2'`,
`ix: issue list --author='\$1' --label='\$2'`},
}
for _, c := range cases {
t.Run(c.Cmd, func(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(``)
output, err := runCommand(cfg, true, c.Cmd, "")
if err != nil {
t.Fatalf("got unexpected error running %s: %s", c.Cmd, err)
}
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), c.ExpectedOutputLine)
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, mainBuf.String(), c.ExpectedConfigLine)
})
}
}
func TestAliasSet_init_alias_cfg(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(heredoc.Doc(`
editor: vim
`))
output, err := runCommand(cfg, true, "diff 'pr diff'", "")
require.NoError(t, err)
expected := `editor: vim
aliases:
diff: pr diff
`
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), "Adding alias for.*diff.*pr diff", "Added alias.")
assert.Equal(t, expected, mainBuf.String())
}
func TestAliasSet_existing_aliases(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(heredoc.Doc(`
aliases:
foo: bar
`))
output, err := runCommand(cfg, true, "view 'pr view'", "")
require.NoError(t, err)
expected := `aliases:
foo: bar
view: pr view
`
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), "Adding alias for.*view.*pr view", "Added alias.")
assert.Equal(t, expected, mainBuf.String())
}
func TestAliasSet_invalid_command(t *testing.T) {
defer config.StubWriteConfig(ioutil.Discard, ioutil.Discard)()
cfg := config.NewFromString(``)
_, err := runCommand(cfg, true, "co 'pe checkout'", "")
assert.EqualError(t, err, "could not create alias: pe checkout does not correspond to a gh command")
}
func TestShellAlias_flag(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(``)
output, err := runCommand(cfg, true, "--shell igrep 'gh issue list | grep'", "")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), "Adding alias for.*igrep")
expected := `aliases:
igrep: '!gh issue list | grep'
`
assert.Equal(t, expected, mainBuf.String())
}
func TestShellAlias_bang(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(``)
output, err := runCommand(cfg, true, "igrep '!gh issue list | grep'", "")
require.NoError(t, err)
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), "Adding alias for.*igrep")
expected := `aliases:
igrep: '!gh issue list | grep'
`
assert.Equal(t, expected, mainBuf.String())
}
func TestShellAlias_from_stdin(t *testing.T) {
mainBuf := bytes.Buffer{}
defer config.StubWriteConfig(&mainBuf, ioutil.Discard)()
cfg := config.NewFromString(``)
output, err := runCommand(cfg, true, "users -", `api graphql -F name="$1" -f query='
query ($name: String!) {
user(login: $name) {
name
}
}'`)
require.NoError(t, err)
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.Stderr(), "Adding alias for.*users")
expected := `aliases:
users: |-
api graphql -F name="$1" -f query='
query ($name: String!) {
user(login: $name) {
name
}
}'
`
assert.Equal(t, expected, mainBuf.String())
}
func TestShellAlias_getExpansion(t *testing.T) {
tests := []struct {
name string
want string
expansionArg string
stdin string
}{
{
name: "co",
want: "pr checkout",
expansionArg: "pr checkout",
},
{
name: "co",
want: "pr checkout",
expansionArg: "pr checkout",
stdin: "api graphql -F name=\"$1\"",
},
{
name: "stdin",
expansionArg: "-",
want: "api graphql -F name=\"$1\"",
stdin: "api graphql -F name=\"$1\"",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, stdin, _, _ := iostreams.Test()
io.SetStdinTTY(false)
_, err := stdin.WriteString(tt.stdin)
assert.NoError(t, err)
expansion, err := getExpansion(&SetOptions{
Expansion: tt.expansionArg,
IO: io,
})
assert.NoError(t, err)
assert.Equal(t, expansion, tt.want)
})
}
}
| pkg/cmd/alias/set/set_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.0031714888755232096,
0.00039111499791033566,
0.00015899738355074078,
0.00017494973144493997,
0.0006720423698425293
] |
{
"id": 5,
"code_window": [
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n",
"\t}\n",
"\n",
"\tpath, err = homedir.Dir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n",
"\t}\n",
"\n",
"\treturn errNotExist\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 104
} | package config
import (
"fmt"
"gopkg.in/yaml.v3"
)
// This interface describes interacting with some persistent configuration for gh.
type Config interface {
Get(string, string) (string, error)
GetWithSource(string, string) (string, string, error)
Set(string, string, string) error
UnsetHost(string)
Hosts() ([]string, error)
DefaultHost() (string, error)
DefaultHostWithSource() (string, string, error)
Aliases() (*AliasConfig, error)
CheckWriteable(string, string) error
Write() error
}
type ConfigOption struct {
Key string
Description string
DefaultValue string
AllowedValues []string
}
var configOptions = []ConfigOption{
{
Key: "git_protocol",
Description: "the protocol to use for git clone and push operations",
DefaultValue: "https",
AllowedValues: []string{"https", "ssh"},
},
{
Key: "editor",
Description: "the text editor program to use for authoring text",
DefaultValue: "",
},
{
Key: "prompt",
Description: "toggle interactive prompting in the terminal",
DefaultValue: "enabled",
AllowedValues: []string{"enabled", "disabled"},
},
{
Key: "pager",
Description: "the terminal pager program to send standard output to",
DefaultValue: "",
},
{
Key: "http_unix_socket",
Description: "the path to a unix socket through which to make HTTP connection",
DefaultValue: "",
},
}
func ConfigOptions() []ConfigOption {
return configOptions
}
func ValidateKey(key string) error {
for _, configKey := range configOptions {
if key == configKey.Key {
return nil
}
}
return fmt.Errorf("invalid key")
}
type InvalidValueError struct {
ValidValues []string
}
func (e InvalidValueError) Error() string {
return "invalid value"
}
func ValidateValue(key, value string) error {
var validValues []string
for _, v := range configOptions {
if v.Key == key {
validValues = v.AllowedValues
break
}
}
if validValues == nil {
return nil
}
for _, v := range validValues {
if v == value {
return nil
}
}
return &InvalidValueError{ValidValues: validValues}
}
func NewConfig(root *yaml.Node) Config {
return &fileConfig{
ConfigMap: ConfigMap{Root: root.Content[0]},
documentRoot: root,
}
}
// NewFromString initializes a Config from a yaml string
func NewFromString(str string) Config {
root, err := parseConfigData([]byte(str))
if err != nil {
panic(err)
}
return NewConfig(root)
}
// NewBlankConfig initializes a config file pre-populated with comments and default values
func NewBlankConfig() Config {
return NewConfig(NewBlankRoot())
}
func NewBlankRoot() *yaml.Node {
return &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{
{
Kind: yaml.MappingNode,
Content: []*yaml.Node{
{
HeadComment: "What protocol to use when performing git operations. Supported values: ssh, https",
Kind: yaml.ScalarNode,
Value: "git_protocol",
},
{
Kind: yaml.ScalarNode,
Value: "https",
},
{
HeadComment: "What editor gh should run when creating issues, pull requests, etc. If blank, will refer to environment.",
Kind: yaml.ScalarNode,
Value: "editor",
},
{
Kind: yaml.ScalarNode,
Value: "",
},
{
HeadComment: "When to interactively prompt. This is a global config that cannot be overridden by hostname. Supported values: enabled, disabled",
Kind: yaml.ScalarNode,
Value: "prompt",
},
{
Kind: yaml.ScalarNode,
Value: "enabled",
},
{
HeadComment: "A pager program to send command output to, e.g. \"less\". Set the value to \"cat\" to disable the pager.",
Kind: yaml.ScalarNode,
Value: "pager",
},
{
Kind: yaml.ScalarNode,
Value: "",
},
{
HeadComment: "Aliases allow you to create nicknames for gh commands",
Kind: yaml.ScalarNode,
Value: "aliases",
},
{
Kind: yaml.MappingNode,
Content: []*yaml.Node{
{
Kind: yaml.ScalarNode,
Value: "co",
},
{
Kind: yaml.ScalarNode,
Value: "pr checkout",
},
},
},
{
HeadComment: "The path to a unix socket through which send HTTP connections. If blank, HTTP traffic will be handled by net/http.DefaultTransport.",
Kind: yaml.ScalarNode,
Value: "http_unix_socket",
},
{
Kind: yaml.ScalarNode,
Value: "",
},
},
},
},
}
}
| internal/config/config_type.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.001884348806925118,
0.0003009653009939939,
0.0001649004261707887,
0.00017018496873788536,
0.0004141581302974373
] |
{
"id": 5,
"code_window": [
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n",
"\t}\n",
"\n",
"\tpath, err = homedir.Dir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateDir(oldPath, newPath)\n",
"\t}\n",
"\n",
"\treturn errNotExist\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 104
} | package view
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"testing"
"github.com/cli/cli/api"
"github.com/cli/cli/internal/ghrepo"
"github.com/cli/cli/internal/run"
"github.com/cli/cli/pkg/cmd/pr/shared"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/httpmock"
"github.com/cli/cli/pkg/iostreams"
"github.com/cli/cli/test"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdView(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want ViewOptions
wantErr string
}{
{
name: "number argument",
args: "123",
isTTY: true,
want: ViewOptions{
SelectorArg: "123",
BrowserMode: false,
},
},
{
name: "no argument",
args: "",
isTTY: true,
want: ViewOptions{
SelectorArg: "",
BrowserMode: false,
},
},
{
name: "web mode",
args: "123 -w",
isTTY: true,
want: ViewOptions{
SelectorArg: "123",
BrowserMode: true,
},
},
{
name: "no argument with --repo override",
args: "-R owner/repo",
isTTY: true,
wantErr: "argument required when using the --repo flag",
},
{
name: "comments",
args: "123 -c",
isTTY: true,
want: ViewOptions{
SelectorArg: "123",
Comments: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, _, _, _ := iostreams.Test()
io.SetStdoutTTY(tt.isTTY)
io.SetStdinTTY(tt.isTTY)
io.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: io,
}
var opts *ViewOptions
cmd := NewCmdView(f, func(o *ViewOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(ioutil.Discard)
cmd.SetErr(ioutil.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.SelectorArg, opts.SelectorArg)
})
}
}
func runCommand(rt http.RoundTripper, branch string, isTTY bool, cli string) (*test.CmdOut, error) {
io, _, stdout, stderr := iostreams.Test()
io.SetStdoutTTY(isTTY)
io.SetStdinTTY(isTTY)
io.SetStderrTTY(isTTY)
browser := &cmdutil.TestBrowser{}
factory := &cmdutil.Factory{
IOStreams: io,
Browser: browser,
}
cmd := NewCmdView(factory, nil)
argv, err := shlex.Split(cli)
if err != nil {
return nil, err
}
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(ioutil.Discard)
cmd.SetErr(ioutil.Discard)
_, err = cmd.ExecuteC()
return &test.CmdOut{
OutBuf: stdout,
ErrBuf: stderr,
BrowsedURL: browser.BrowsedURL(),
}, err
}
// hack for compatibility with old JSON fixture files
func prFromFixtures(fixtures map[string]string) (*api.PullRequest, error) {
var response struct {
Data struct {
Repository struct {
PullRequest *api.PullRequest
}
}
}
ff, err := os.Open(fixtures["PullRequestByNumber"])
if err != nil {
return nil, err
}
defer ff.Close()
dec := json.NewDecoder(ff)
err = dec.Decode(&response)
if err != nil {
return nil, err
}
for name := range fixtures {
switch name {
case "PullRequestByNumber":
case "ReviewsForPullRequest", "CommentsForPullRequest":
ff, err := os.Open(fixtures[name])
if err != nil {
return nil, err
}
defer ff.Close()
dec := json.NewDecoder(ff)
err = dec.Decode(&response)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unrecognized fixture type: %q", name)
}
}
return response.Data.Repository.PullRequest, nil
}
func TestPRView_Preview_nontty(t *testing.T) {
tests := map[string]struct {
branch string
args string
fixtures map[string]string
expectedOutputs []string
}{
"Open PR without metadata": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreview.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`state:\tOPEN\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`reviewers:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`url:\thttps://github.com/OWNER/REPO/pull/12\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`number:\t12\n`,
`blueberries taste good`,
},
},
"Open PR with metadata by number": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithMetadataByNumber.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`reviewers:\t1 \(Requested\)\n`,
`assignees:\tmarseilles, monaco\n`,
`labels:\tone, two, three, four, five\n`,
`projects:\tProject 1 \(column A\), Project 2 \(column B\), Project 3 \(column C\), Project 4 \(Awaiting triage\)\n`,
`milestone:\tuluru\n`,
`\*\*blueberries taste good\*\*`,
},
},
"Open PR with reviewers by number": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithReviewersByNumber.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewManyReviews.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`state:\tOPEN\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`reviewers:\tDEF \(Commented\), def \(Changes requested\), ghost \(Approved\), hubot \(Commented\), xyz \(Approved\), 123 \(Requested\), abc \(Requested\), my-org\/team-1 \(Requested\)\n`,
`\*\*blueberries taste good\*\*`,
},
},
"Closed PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewClosedState.json",
},
expectedOutputs: []string{
`state:\tCLOSED\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`reviewers:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`\*\*blueberries taste good\*\*`,
},
},
"Merged PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewMergedState.json",
},
expectedOutputs: []string{
`state:\tMERGED\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`reviewers:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`\*\*blueberries taste good\*\*`,
},
},
"Draft PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewDraftState.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`state:\tDRAFT\n`,
`author:\tnobody\n`,
`labels:`,
`assignees:`,
`reviewers:`,
`projects:`,
`milestone:`,
`additions:\t100\n`,
`deletions:\t10\n`,
`\*\*blueberries taste good\*\*`,
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
pr, err := prFromFixtures(tc.fixtures)
require.NoError(t, err)
shared.RunCommandFinder("12", pr, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, tc.branch, false, tc.args)
if err != nil {
t.Errorf("error running command `%v`: %v", tc.args, err)
}
assert.Equal(t, "", output.Stderr())
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.String(), tc.expectedOutputs...)
})
}
}
func TestPRView_Preview(t *testing.T) {
tests := map[string]struct {
branch string
args string
fixtures map[string]string
expectedOutputs []string
}{
"Open PR without metadata": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreview.json",
},
expectedOutputs: []string{
`Blueberries are from a fork #12`,
`Open.*nobody wants to merge 12 commits into master from blueberries.+100.-10`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with metadata by number": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithMetadataByNumber.json",
},
expectedOutputs: []string{
`Blueberries are from a fork #12`,
`Open.*nobody wants to merge 12 commits into master from blueberries.+100.-10`,
`Reviewers:.*1 \(.*Requested.*\)\n`,
`Assignees:.*marseilles, monaco\n`,
`Labels:.*one, two, three, four, five\n`,
`Projects:.*Project 1 \(column A\), Project 2 \(column B\), Project 3 \(column C\), Project 4 \(Awaiting triage\)\n`,
`Milestone:.*uluru\n`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with reviewers by number": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithReviewersByNumber.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewManyReviews.json",
},
expectedOutputs: []string{
`Blueberries are from a fork #12`,
`Reviewers: DEF \(Commented\), def \(Changes requested\), ghost \(Approved\), hubot \(Commented\), xyz \(Approved\), 123 \(Requested\), abc \(Requested\), my-org\/team-1 \(Requested\)`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Closed PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewClosedState.json",
},
expectedOutputs: []string{
`Blueberries are from a fork #12`,
`Closed.*nobody wants to merge 12 commits into master from blueberries.+100.-10`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Merged PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewMergedState.json",
},
expectedOutputs: []string{
`Blueberries are from a fork #12`,
`Merged.*nobody wants to merge 12 commits into master from blueberries.+100.-10`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Draft PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewDraftState.json",
},
expectedOutputs: []string{
`Blueberries are from a fork #12`,
`Draft.*nobody wants to merge 12 commits into master from blueberries.+100.-10`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
pr, err := prFromFixtures(tc.fixtures)
require.NoError(t, err)
shared.RunCommandFinder("12", pr, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, tc.branch, true, tc.args)
if err != nil {
t.Errorf("error running command `%v`: %v", tc.args, err)
}
assert.Equal(t, "", output.Stderr())
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.String(), tc.expectedOutputs...)
})
}
}
func TestPRView_web_currentBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.RunCommandFinder("", &api.PullRequest{URL: "https://github.com/OWNER/REPO/pull/10"}, ghrepo.New("OWNER", "REPO"))
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
output, err := runCommand(http, "blueberries", true, "-w")
if err != nil {
t.Errorf("error running command `pr view`: %v", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, "Opening github.com/OWNER/REPO/pull/10 in your browser.\n", output.Stderr())
assert.Equal(t, "https://github.com/OWNER/REPO/pull/10", output.BrowsedURL)
}
func TestPRView_web_noResultsForBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.RunCommandFinder("", nil, nil)
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
_, err := runCommand(http, "blueberries", true, "-w")
if err == nil || err.Error() != `no pull requests found` {
t.Errorf("error running command `pr view`: %v", err)
}
}
func TestPRView_tty_Comments(t *testing.T) {
tests := map[string]struct {
branch string
cli string
fixtures map[string]string
expectedOutputs []string
wantsErr bool
}{
"without comments flag": {
branch: "master",
cli: "123",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewSingleComment.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewReviews.json",
},
expectedOutputs: []string{
`some title #12`,
`1 \x{1f615} β’ 2 \x{1f440} β’ 3 \x{2764}\x{fe0f}`,
`some body`,
`ββββββββ Not showing 9 comments ββββββββ`,
`marseilles \(Collaborator\) β’ Jan 9, 2020 β’ Newest comment`,
`4 \x{1f389} β’ 5 \x{1f604} β’ 6 \x{1f680}`,
`Comment 5`,
`Use --comments to view the full conversation`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"with comments flag": {
branch: "master",
cli: "123 --comments",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewSingleComment.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewReviews.json",
"CommentsForPullRequest": "./fixtures/prViewPreviewFullComments.json",
},
expectedOutputs: []string{
`some title #12`,
`some body`,
`monalisa β’ Jan 1, 2020 β’ Edited`,
`1 \x{1f615} β’ 2 \x{1f440} β’ 3 \x{2764}\x{fe0f} β’ 4 \x{1f389} β’ 5 \x{1f604} β’ 6 \x{1f680} β’ 7 \x{1f44e} β’ 8 \x{1f44d}`,
`Comment 1`,
`sam commented β’ Jan 2, 2020`,
`1 \x{1f44e} β’ 1 \x{1f44d}`,
`Review 1`,
`View the full review: https://github.com/OWNER/REPO/pull/12#pullrequestreview-1`,
`johnnytest \(Contributor\) β’ Jan 3, 2020`,
`Comment 2`,
`matt requested changes \(Owner\) β’ Jan 4, 2020`,
`1 \x{1f615} β’ 1 \x{1f440}`,
`Review 2`,
`View the full review: https://github.com/OWNER/REPO/pull/12#pullrequestreview-2`,
`elvisp \(Member\) β’ Jan 5, 2020`,
`Comment 3`,
`leah approved \(Member\) β’ Jan 6, 2020 β’ Edited`,
`Review 3`,
`View the full review: https://github.com/OWNER/REPO/pull/12#pullrequestreview-3`,
`loislane \(Owner\) β’ Jan 7, 2020`,
`Comment 4`,
`louise dismissed β’ Jan 8, 2020`,
`Review 4`,
`View the full review: https://github.com/OWNER/REPO/pull/12#pullrequestreview-4`,
`sam-spam β’ This comment has been marked as spam`,
`marseilles \(Collaborator\) β’ Jan 9, 2020 β’ Newest comment`,
`Comment 5`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"with invalid comments flag": {
branch: "master",
cli: "123 --comments 3",
wantsErr: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
if len(tt.fixtures) > 0 {
pr, err := prFromFixtures(tt.fixtures)
require.NoError(t, err)
shared.RunCommandFinder("123", pr, ghrepo.New("OWNER", "REPO"))
} else {
shared.RunCommandFinder("123", nil, nil)
}
output, err := runCommand(http, tt.branch, true, tt.cli)
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, "", output.Stderr())
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.String(), tt.expectedOutputs...)
})
}
}
func TestPRView_nontty_Comments(t *testing.T) {
tests := map[string]struct {
branch string
cli string
fixtures map[string]string
expectedOutputs []string
wantsErr bool
}{
"without comments flag": {
branch: "master",
cli: "123",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewSingleComment.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewReviews.json",
},
expectedOutputs: []string{
`title:\tsome title`,
`state:\tOPEN`,
`author:\tnobody`,
`url:\thttps://github.com/OWNER/REPO/pull/12`,
`some body`,
},
},
"with comments flag": {
branch: "master",
cli: "123 --comments",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewSingleComment.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewReviews.json",
"CommentsForPullRequest": "./fixtures/prViewPreviewFullComments.json",
},
expectedOutputs: []string{
`author:\tmonalisa`,
`association:\tnone`,
`edited:\ttrue`,
`status:\tnone`,
`Comment 1`,
`author:\tsam`,
`association:\tnone`,
`edited:\tfalse`,
`status:\tcommented`,
`Review 1`,
`author:\tjohnnytest`,
`association:\tcontributor`,
`edited:\tfalse`,
`status:\tnone`,
`Comment 2`,
`author:\tmatt`,
`association:\towner`,
`edited:\tfalse`,
`status:\tchanges requested`,
`Review 2`,
`author:\telvisp`,
`association:\tmember`,
`edited:\tfalse`,
`status:\tnone`,
`Comment 3`,
`author:\tleah`,
`association:\tmember`,
`edited:\ttrue`,
`status:\tapproved`,
`Review 3`,
`author:\tloislane`,
`association:\towner`,
`edited:\tfalse`,
`status:\tnone`,
`Comment 4`,
`author:\tlouise`,
`association:\tnone`,
`edited:\tfalse`,
`status:\tdismissed`,
`Review 4`,
`author:\tmarseilles`,
`association:\tcollaborator`,
`edited:\tfalse`,
`status:\tnone`,
`Comment 5`,
},
},
"with invalid comments flag": {
branch: "master",
cli: "123 --comments 3",
wantsErr: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
if len(tt.fixtures) > 0 {
pr, err := prFromFixtures(tt.fixtures)
require.NoError(t, err)
shared.RunCommandFinder("123", pr, ghrepo.New("OWNER", "REPO"))
} else {
shared.RunCommandFinder("123", nil, nil)
}
output, err := runCommand(http, tt.branch, false, tt.cli)
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, "", output.Stderr())
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.String(), tt.expectedOutputs...)
})
}
}
| pkg/cmd/pr/view/view_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00018355059728492051,
0.0001720835716696456,
0.00016064794908743352,
0.00017343671061098576,
0.000004348454694991233
] |
{
"id": 6,
"code_window": [
"\treturn errNotExist\n",
"}\n",
"\n",
"// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)\n",
"// If state file exist then move it to newPath\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"// Check default path, os.UserHomeDir, for existing state file (state.yml)\n"
],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 112
} | package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"syscall"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
const (
GH_CONFIG_DIR = "GH_CONFIG_DIR"
XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
XDG_STATE_HOME = "XDG_STATE_HOME"
XDG_DATA_HOME = "XDG_DATA_HOME"
APP_DATA = "AppData"
LOCAL_APP_DATA = "LocalAppData"
)
// Config path precedence
// 1. GH_CONFIG_DIR
// 2. XDG_CONFIG_HOME
// 3. AppData (windows only)
// 4. HOME
func ConfigDir() string {
var path string
if a := os.Getenv(GH_CONFIG_DIR); a != "" {
path = a
} else if b := os.Getenv(XDG_CONFIG_HOME); b != "" {
path = filepath.Join(b, "gh")
} else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" {
path = filepath.Join(c, "GitHub CLI")
} else {
d, _ := os.UserHomeDir()
path = filepath.Join(d, ".config", "gh")
}
// If the path does not exist and the GH_CONFIG_DIR flag is not set try
// migrating config from default paths.
if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" {
_ = autoMigrateConfigDir(path)
}
return path
}
// State path precedence
// 1. XDG_CONFIG_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func StateDir() string {
var path string
if a := os.Getenv(XDG_STATE_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "state", "gh")
}
// If the path does not exist try migrating state from default paths
if !dirExists(path) {
_ = autoMigrateStateDir(path)
}
return path
}
// Data path precedence
// 1. XDG_DATA_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func DataDir() string {
var path string
if a := os.Getenv(XDG_DATA_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "share", "gh")
}
return path
}
var errSamePath = errors.New("same path")
var errNotExist = errors.New("not exist")
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs
// If configs exist then move them to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateConfigDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
return errNotExist
}
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)
// If state file exist then move it to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateStateDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
return errNotExist
}
func migrateFile(oldPath, newPath, file string) error {
if oldPath == newPath {
return errSamePath
}
oldFile := filepath.Join(oldPath, file)
newFile := filepath.Join(newPath, file)
if !fileExists(oldFile) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newFile), 0755)
return os.Rename(oldFile, newFile)
}
func migrateDir(oldPath, newPath string) error {
if oldPath == newPath {
return errSamePath
}
if !dirExists(oldPath) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newPath), 0755)
return os.Rename(oldPath, newPath)
}
func dirExists(path string) bool {
f, err := os.Stat(path)
return err == nil && f.IsDir()
}
func fileExists(path string) bool {
f, err := os.Stat(path)
return err == nil && !f.IsDir()
}
func ConfigFile() string {
return filepath.Join(ConfigDir(), "config.yml")
}
func HostsConfigFile() string {
return filepath.Join(ConfigDir(), "hosts.yml")
}
func ParseDefaultConfig() (Config, error) {
return parseConfig(ConfigFile())
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, subdir), nil
}
return "", err
}
newPath := filepath.Join(homeDir, subdir)
if s, err := os.Stat(newPath); err == nil && s.IsDir() {
return newPath, nil
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, subdir)
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
return legacyPath, nil
}
}
return newPath, nil
}
var ReadConfigFile = func(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, pathError(err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
var WriteConfigFile = func(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return pathError(err)
}
cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup
if err != nil {
return err
}
defer cfgFile.Close()
_, err = cfgFile.Write(data)
return err
}
var BackupConfigFile = func(filename string) error {
return os.Rename(filename, filename+".bak")
}
func parseConfigFile(filename string) ([]byte, *yaml.Node, error) {
data, err := ReadConfigFile(filename)
if err != nil {
return nil, nil, err
}
root, err := parseConfigData(data)
if err != nil {
return nil, nil, err
}
return data, root, err
}
func parseConfigData(data []byte) (*yaml.Node, error) {
var root yaml.Node
err := yaml.Unmarshal(data, &root)
if err != nil {
return nil, err
}
if len(root.Content) == 0 {
return &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
}, nil
}
if root.Content[0].Kind != yaml.MappingNode {
return &root, fmt.Errorf("expected a top level map")
}
return &root, nil
}
func isLegacy(root *yaml.Node) bool {
for _, v := range root.Content[0].Content {
if v.Value == "github.com" {
return true
}
}
return false
}
func migrateConfig(filename string) error {
b, err := ReadConfigFile(filename)
if err != nil {
return err
}
var hosts map[string][]yaml.Node
err = yaml.Unmarshal(b, &hosts)
if err != nil {
return fmt.Errorf("error decoding legacy format: %w", err)
}
cfg := NewBlankConfig()
for hostname, entries := range hosts {
if len(entries) < 1 {
continue
}
mapContent := entries[0].Content
for i := 0; i < len(mapContent)-1; i += 2 {
if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil {
return err
}
}
}
err = BackupConfigFile(filename)
if err != nil {
return fmt.Errorf("failed to back up existing config: %w", err)
}
return cfg.Write()
}
func parseConfig(filename string) (Config, error) {
_, root, err := parseConfigFile(filename)
if err != nil {
if os.IsNotExist(err) {
root = NewBlankRoot()
} else {
return nil, err
}
}
if isLegacy(root) {
err = migrateConfig(filename)
if err != nil {
return nil, fmt.Errorf("error migrating legacy config: %w", err)
}
_, root, err = parseConfigFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to reparse migrated config: %w", err)
}
} else {
if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil {
if len(hostsRoot.Content[0].Content) > 0 {
newContent := []*yaml.Node{
{Value: "hosts"},
hostsRoot.Content[0],
}
restContent := root.Content[0].Content
root.Content[0].Content = append(newContent, restContent...)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return NewConfig(root), nil
}
func pathError(err error) error {
var pathError *os.PathError
if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) {
if p := findRegularFile(pathError.Path); p != "" {
return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p)
}
}
return err
}
func findRegularFile(p string) string {
for {
if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() {
return p
}
newPath := filepath.Dir(p)
if newPath == p || newPath == "/" || newPath == "." {
break
}
p = newPath
}
return ""
}
| internal/config/config_file.go | 1 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.6198556423187256,
0.019128594547510147,
0.000168169557582587,
0.0009230301948264241,
0.09883694350719452
] |
{
"id": 6,
"code_window": [
"\treturn errNotExist\n",
"}\n",
"\n",
"// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)\n",
"// If state file exist then move it to newPath\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"// Check default path, os.UserHomeDir, for existing state file (state.yml)\n"
],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 112
} | package cmdutil
import (
"os"
"sort"
"strings"
"github.com/cli/cli/internal/ghrepo"
"github.com/spf13/cobra"
)
func executeParentHooks(cmd *cobra.Command, args []string) error {
for cmd.HasParent() {
cmd = cmd.Parent()
if cmd.PersistentPreRunE != nil {
return cmd.PersistentPreRunE(cmd, args)
}
}
return nil
}
func EnableRepoOverride(cmd *cobra.Command, f *Factory) {
cmd.PersistentFlags().StringP("repo", "R", "", "Select another repository using the `[HOST/]OWNER/REPO` format")
_ = cmd.RegisterFlagCompletionFunc("repo", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
remotes, err := f.Remotes()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
config, err := f.Config()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
defaultHost, err := config.DefaultHost()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var results []string
for _, remote := range remotes {
repo := remote.RepoOwner() + "/" + remote.RepoName()
if !strings.EqualFold(remote.RepoHost(), defaultHost) {
repo = remote.RepoHost() + "/" + repo
}
if strings.HasPrefix(repo, toComplete) {
results = append(results, repo)
}
}
sort.Strings(results)
return results, cobra.ShellCompDirectiveNoFileComp
})
cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if err := executeParentHooks(cmd, args); err != nil {
return err
}
repoOverride, _ := cmd.Flags().GetString("repo")
f.BaseRepo = OverrideBaseRepoFunc(f, repoOverride)
return nil
}
}
func OverrideBaseRepoFunc(f *Factory, override string) func() (ghrepo.Interface, error) {
if override == "" {
override = os.Getenv("GH_REPO")
}
if override != "" {
return func() (ghrepo.Interface, error) {
return ghrepo.FromFullName(override)
}
}
return f.BaseRepo
}
| pkg/cmdutil/repo_override.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00018449759227223694,
0.00017259585729334503,
0.00016599603986833245,
0.00017025598208419979,
0.000006402293365681544
] |
{
"id": 6,
"code_window": [
"\treturn errNotExist\n",
"}\n",
"\n",
"// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)\n",
"// If state file exist then move it to newPath\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"// Check default path, os.UserHomeDir, for existing state file (state.yml)\n"
],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 112
} | package list
import (
"net/http"
"reflect"
"testing"
"github.com/cli/cli/internal/ghrepo"
prShared "github.com/cli/cli/pkg/cmd/pr/shared"
"github.com/cli/cli/pkg/httpmock"
)
func Test_listPullRequests(t *testing.T) {
type args struct {
repo ghrepo.Interface
filters prShared.FilterOptions
limit int
}
tests := []struct {
name string
args args
httpStub func(*testing.T, *httpmock.Registry)
wantErr bool
}{
{
name: "default",
args: args{
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "open",
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"owner": "OWNER",
"repo": "REPO",
"state": []interface{}{"OPEN"},
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
{
name: "closed",
args: args{
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "closed",
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"owner": "OWNER",
"repo": "REPO",
"state": []interface{}{"CLOSED", "MERGED"},
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
{
name: "with labels",
args: args{
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "open",
Labels: []string{"hello", "one world"},
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"q": `repo:OWNER/REPO is:pr is:open label:hello label:"one world"`,
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
{
name: "with author",
args: args{
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "open",
Author: "monalisa",
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"q": "repo:OWNER/REPO is:pr is:open author:monalisa",
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
{
name: "with search",
args: args{
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "open",
Search: "one world in:title",
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"q": "repo:OWNER/REPO is:pr is:open one world in:title",
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStub != nil {
tt.httpStub(t, reg)
}
httpClient := &http.Client{Transport: reg}
_, err := listPullRequests(httpClient, tt.args.repo, tt.args.filters, tt.args.limit)
if (err != nil) != tt.wantErr {
t.Errorf("listPullRequests() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
| pkg/cmd/pr/list/http_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.0002162477612728253,
0.00017353885050397366,
0.00016526514082215726,
0.00016810590750537813,
0.000012708600479527377
] |
{
"id": 6,
"code_window": [
"\treturn errNotExist\n",
"}\n",
"\n",
"// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)\n",
"// If state file exist then move it to newPath\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"// Check default path, os.UserHomeDir, for existing state file (state.yml)\n"
],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 112
} | package api
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPullRequest_ChecksStatus(t *testing.T) {
pr := PullRequest{}
payload := `
{ "statusCheckRollup": { "nodes": [{ "commit": {
"statusCheckRollup": {
"contexts": {
"nodes": [
{ "state": "SUCCESS" },
{ "state": "PENDING" },
{ "state": "FAILURE" },
{ "status": "IN_PROGRESS",
"conclusion": null },
{ "status": "COMPLETED",
"conclusion": "SUCCESS" },
{ "status": "COMPLETED",
"conclusion": "FAILURE" },
{ "status": "COMPLETED",
"conclusion": "ACTION_REQUIRED" },
{ "status": "COMPLETED",
"conclusion": "STALE" }
]
}
}
} }] } }
`
err := json.Unmarshal([]byte(payload), &pr)
assert.NoError(t, err)
checks := pr.ChecksStatus()
assert.Equal(t, 8, checks.Total)
assert.Equal(t, 3, checks.Pending)
assert.Equal(t, 3, checks.Failing)
assert.Equal(t, 2, checks.Passing)
}
| api/pull_request_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00026792538119480014,
0.0001868393737822771,
0.00016245903680101037,
0.00016786948253866285,
0.00004061014988110401
] |
{
"id": 7,
"code_window": [
"// If state file exist then move it to newPath\n",
"// TODO: Remove support for homedir.Dir location in v2\n",
"func autoMigrateStateDir(newPath string) error {\n",
"\tpath, err := os.UserHomeDir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 114
} | package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"syscall"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
const (
GH_CONFIG_DIR = "GH_CONFIG_DIR"
XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
XDG_STATE_HOME = "XDG_STATE_HOME"
XDG_DATA_HOME = "XDG_DATA_HOME"
APP_DATA = "AppData"
LOCAL_APP_DATA = "LocalAppData"
)
// Config path precedence
// 1. GH_CONFIG_DIR
// 2. XDG_CONFIG_HOME
// 3. AppData (windows only)
// 4. HOME
func ConfigDir() string {
var path string
if a := os.Getenv(GH_CONFIG_DIR); a != "" {
path = a
} else if b := os.Getenv(XDG_CONFIG_HOME); b != "" {
path = filepath.Join(b, "gh")
} else if c := os.Getenv(APP_DATA); runtime.GOOS == "windows" && c != "" {
path = filepath.Join(c, "GitHub CLI")
} else {
d, _ := os.UserHomeDir()
path = filepath.Join(d, ".config", "gh")
}
// If the path does not exist and the GH_CONFIG_DIR flag is not set try
// migrating config from default paths.
if !dirExists(path) && os.Getenv(GH_CONFIG_DIR) == "" {
_ = autoMigrateConfigDir(path)
}
return path
}
// State path precedence
// 1. XDG_CONFIG_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func StateDir() string {
var path string
if a := os.Getenv(XDG_STATE_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "state", "gh")
}
// If the path does not exist try migrating state from default paths
if !dirExists(path) {
_ = autoMigrateStateDir(path)
}
return path
}
// Data path precedence
// 1. XDG_DATA_HOME
// 2. LocalAppData (windows only)
// 3. HOME
func DataDir() string {
var path string
if a := os.Getenv(XDG_DATA_HOME); a != "" {
path = filepath.Join(a, "gh")
} else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" {
path = filepath.Join(b, "GitHub CLI")
} else {
c, _ := os.UserHomeDir()
path = filepath.Join(c, ".local", "share", "gh")
}
return path
}
var errSamePath = errors.New("same path")
var errNotExist = errors.New("not exist")
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing configs
// If configs exist then move them to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateConfigDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateDir(oldPath, newPath)
}
return errNotExist
}
// Check default paths (os.UserHomeDir, and homedir.Dir) for existing state file (state.yml)
// If state file exist then move it to newPath
// TODO: Remove support for homedir.Dir location in v2
func autoMigrateStateDir(newPath string) error {
path, err := os.UserHomeDir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
path, err = homedir.Dir()
if oldPath := filepath.Join(path, ".config", "gh"); err == nil && dirExists(oldPath) {
return migrateFile(oldPath, newPath, "state.yml")
}
return errNotExist
}
func migrateFile(oldPath, newPath, file string) error {
if oldPath == newPath {
return errSamePath
}
oldFile := filepath.Join(oldPath, file)
newFile := filepath.Join(newPath, file)
if !fileExists(oldFile) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newFile), 0755)
return os.Rename(oldFile, newFile)
}
func migrateDir(oldPath, newPath string) error {
if oldPath == newPath {
return errSamePath
}
if !dirExists(oldPath) {
return errNotExist
}
_ = os.MkdirAll(filepath.Dir(newPath), 0755)
return os.Rename(oldPath, newPath)
}
func dirExists(path string) bool {
f, err := os.Stat(path)
return err == nil && f.IsDir()
}
func fileExists(path string) bool {
f, err := os.Stat(path)
return err == nil && !f.IsDir()
}
func ConfigFile() string {
return filepath.Join(ConfigDir(), "config.yml")
}
func HostsConfigFile() string {
return filepath.Join(ConfigDir(), "hosts.yml")
}
func ParseDefaultConfig() (Config, error) {
return parseConfig(ConfigFile())
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, subdir), nil
}
return "", err
}
newPath := filepath.Join(homeDir, subdir)
if s, err := os.Stat(newPath); err == nil && s.IsDir() {
return newPath, nil
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, subdir)
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
return legacyPath, nil
}
}
return newPath, nil
}
var ReadConfigFile = func(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, pathError(err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
var WriteConfigFile = func(filename string, data []byte) error {
err := os.MkdirAll(filepath.Dir(filename), 0771)
if err != nil {
return pathError(err)
}
cfgFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) // cargo coded from setup
if err != nil {
return err
}
defer cfgFile.Close()
_, err = cfgFile.Write(data)
return err
}
var BackupConfigFile = func(filename string) error {
return os.Rename(filename, filename+".bak")
}
func parseConfigFile(filename string) ([]byte, *yaml.Node, error) {
data, err := ReadConfigFile(filename)
if err != nil {
return nil, nil, err
}
root, err := parseConfigData(data)
if err != nil {
return nil, nil, err
}
return data, root, err
}
func parseConfigData(data []byte) (*yaml.Node, error) {
var root yaml.Node
err := yaml.Unmarshal(data, &root)
if err != nil {
return nil, err
}
if len(root.Content) == 0 {
return &yaml.Node{
Kind: yaml.DocumentNode,
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
}, nil
}
if root.Content[0].Kind != yaml.MappingNode {
return &root, fmt.Errorf("expected a top level map")
}
return &root, nil
}
func isLegacy(root *yaml.Node) bool {
for _, v := range root.Content[0].Content {
if v.Value == "github.com" {
return true
}
}
return false
}
func migrateConfig(filename string) error {
b, err := ReadConfigFile(filename)
if err != nil {
return err
}
var hosts map[string][]yaml.Node
err = yaml.Unmarshal(b, &hosts)
if err != nil {
return fmt.Errorf("error decoding legacy format: %w", err)
}
cfg := NewBlankConfig()
for hostname, entries := range hosts {
if len(entries) < 1 {
continue
}
mapContent := entries[0].Content
for i := 0; i < len(mapContent)-1; i += 2 {
if err := cfg.Set(hostname, mapContent[i].Value, mapContent[i+1].Value); err != nil {
return err
}
}
}
err = BackupConfigFile(filename)
if err != nil {
return fmt.Errorf("failed to back up existing config: %w", err)
}
return cfg.Write()
}
func parseConfig(filename string) (Config, error) {
_, root, err := parseConfigFile(filename)
if err != nil {
if os.IsNotExist(err) {
root = NewBlankRoot()
} else {
return nil, err
}
}
if isLegacy(root) {
err = migrateConfig(filename)
if err != nil {
return nil, fmt.Errorf("error migrating legacy config: %w", err)
}
_, root, err = parseConfigFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to reparse migrated config: %w", err)
}
} else {
if _, hostsRoot, err := parseConfigFile(HostsConfigFile()); err == nil {
if len(hostsRoot.Content[0].Content) > 0 {
newContent := []*yaml.Node{
{Value: "hosts"},
hostsRoot.Content[0],
}
restContent := root.Content[0].Content
root.Content[0].Content = append(newContent, restContent...)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return NewConfig(root), nil
}
func pathError(err error) error {
var pathError *os.PathError
if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) {
if p := findRegularFile(pathError.Path); p != "" {
return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p)
}
}
return err
}
func findRegularFile(p string) string {
for {
if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() {
return p
}
newPath := filepath.Dir(p)
if newPath == p || newPath == "/" || newPath == "." {
break
}
p = newPath
}
return ""
}
| internal/config/config_file.go | 1 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.9986530542373657,
0.3461856245994568,
0.0001660781999817118,
0.0155770443379879,
0.4376184642314911
] |
{
"id": 7,
"code_window": [
"// If state file exist then move it to newPath\n",
"// TODO: Remove support for homedir.Dir location in v2\n",
"func autoMigrateStateDir(newPath string) error {\n",
"\tpath, err := os.UserHomeDir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 114
} | MIT License
Copyright (c) 2019 GitHub Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| LICENSE | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00017484533600509167,
0.00017000244406517595,
0.00016669680189806968,
0.0001684651942923665,
0.0000034997149214177625
] |
{
"id": 7,
"code_window": [
"// If state file exist then move it to newPath\n",
"// TODO: Remove support for homedir.Dir location in v2\n",
"func autoMigrateStateDir(newPath string) error {\n",
"\tpath, err := os.UserHomeDir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 114
} | # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
| .github/CODE-OF-CONDUCT.md | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.0001713191159069538,
0.0001696278341114521,
0.00016647664597257972,
0.0001702758891042322,
0.000001750731939864636
] |
{
"id": 7,
"code_window": [
"// If state file exist then move it to newPath\n",
"// TODO: Remove support for homedir.Dir location in v2\n",
"func autoMigrateStateDir(newPath string) error {\n",
"\tpath, err := os.UserHomeDir()\n",
"\tif oldPath := filepath.Join(path, \".config\", \"gh\"); err == nil && dirExists(oldPath) {\n",
"\t\treturn migrateFile(oldPath, newPath, \"state.yml\")\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "internal/config/config_file.go",
"type": "replace",
"edit_start_line_idx": 114
} | package view
import (
"archive/zip"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/internal/ghrepo"
"github.com/cli/cli/pkg/cmd/run/shared"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/httpmock"
"github.com/cli/cli/pkg/iostreams"
"github.com/cli/cli/pkg/prompt"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func TestNewCmdView(t *testing.T) {
tests := []struct {
name string
cli string
tty bool
wants ViewOptions
wantsErr bool
}{
{
name: "blank nontty",
wantsErr: true,
},
{
name: "blank tty",
tty: true,
wants: ViewOptions{
Prompt: true,
},
},
{
name: "web tty",
tty: true,
cli: "--web",
wants: ViewOptions{
Prompt: true,
Web: true,
},
},
{
name: "web nontty",
cli: "1234 --web",
wants: ViewOptions{
Web: true,
RunID: "1234",
},
},
{
name: "disallow web and log",
tty: true,
cli: "-w --log",
wantsErr: true,
},
{
name: "disallow log and log-failed",
tty: true,
cli: "--log --log-failed",
wantsErr: true,
},
{
name: "exit status",
cli: "--exit-status 1234",
wants: ViewOptions{
RunID: "1234",
ExitStatus: true,
},
},
{
name: "verbosity",
cli: "-v",
tty: true,
wants: ViewOptions{
Verbose: true,
Prompt: true,
},
},
{
name: "with arg nontty",
cli: "1234",
wants: ViewOptions{
RunID: "1234",
},
},
{
name: "job id passed",
cli: "--job 1234",
wants: ViewOptions{
JobID: "1234",
},
},
{
name: "log passed",
tty: true,
cli: "--log",
wants: ViewOptions{
Prompt: true,
Log: true,
},
},
{
name: "tolerates both run and job id",
cli: "1234 --job 4567",
wants: ViewOptions{
JobID: "4567",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, _, _, _ := iostreams.Test()
io.SetStdinTTY(tt.tty)
io.SetStdoutTTY(tt.tty)
f := &cmdutil.Factory{
IOStreams: io,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts *ViewOptions
cmd := NewCmdView(f, func(opts *ViewOptions) error {
gotOpts = opts
return nil
})
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(ioutil.Discard)
cmd.SetErr(ioutil.Discard)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.RunID, gotOpts.RunID)
assert.Equal(t, tt.wants.Prompt, gotOpts.Prompt)
assert.Equal(t, tt.wants.ExitStatus, gotOpts.ExitStatus)
assert.Equal(t, tt.wants.Verbose, gotOpts.Verbose)
})
}
}
func TestViewRun(t *testing.T) {
tests := []struct {
name string
httpStubs func(*httpmock.Registry)
askStubs func(*prompt.AskStubber)
opts *ViewOptions
tty bool
wantErr bool
wantOut string
browsedURL string
errMsg string
}{
{
name: "associate with PR",
tty: true,
opts: &ViewOptions{
RunID: "3",
Prompt: false,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"),
httpmock.StringResponse(`{}`))
reg.Register(
httpmock.GraphQL(`query PullRequestForRun`),
httpmock.StringResponse(`{"data": {
"repository": {
"pullRequests": {
"nodes": [
{"number": 2898,
"headRepository": {
"owner": {
"login": "OWNER"
},
"name": "REPO"}}
]}}}}`))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"),
httpmock.JSONResponse([]shared.Annotation{}))
},
wantOut: "\nβ trunk successful #2898 Β· 3\nTriggered via push about 59 minutes ago\n\nJOBS\nβ cool job in 4m34s (ID 10)\n\nFor more information about a job, try: gh run view --job=<job-id>\nView this run on GitHub: https://github.com/runs/3\n",
},
{
name: "exit status, failed run",
opts: &ViewOptions{
RunID: "1234",
ExitStatus: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"),
httpmock.JSONResponse(shared.FailedRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/artifacts"),
httpmock.StringResponse(`{}`))
reg.Register(
httpmock.GraphQL(`query PullRequestForRun`),
httpmock.StringResponse(``))
reg.Register(
httpmock.REST("GET", "runs/1234/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/20/annotations"),
httpmock.JSONResponse(shared.FailedJobAnnotations))
},
wantOut: "\nX trunk failed Β· 1234\nTriggered via push about 59 minutes ago\n\nJOBS\nX sad job in 4m34s (ID 20)\n β barf the quux\n X quux the barf\n\nANNOTATIONS\nX the job is sad\nsad job: blaze.py#420\n\n\nTo see what failed, try: gh run view 1234 --log-failed\nView this run on GitHub: https://github.com/runs/1234\n",
wantErr: true,
},
{
name: "with artifacts",
opts: &ViewOptions{
RunID: "3",
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"),
httpmock.JSONResponse(map[string][]shared.Artifact{
"artifacts": {
shared.Artifact{Name: "artifact-1", Expired: false},
shared.Artifact{Name: "artifact-2", Expired: true},
shared.Artifact{Name: "artifact-3", Expired: false},
},
}))
reg.Register(
httpmock.GraphQL(`query PullRequestForRun`),
httpmock.StringResponse(``))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{}))
},
wantOut: heredoc.Doc(`
β trunk successful Β· 3
Triggered via push about 59 minutes ago
JOBS
ARTIFACTS
artifact-1
artifact-2 (expired)
artifact-3
For more information about a job, try: gh run view --job=<job-id>
View this run on GitHub: https://github.com/runs/3
`),
},
{
name: "exit status, successful run",
opts: &ViewOptions{
RunID: "3",
ExitStatus: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"),
httpmock.StringResponse(`{}`))
reg.Register(
httpmock.GraphQL(`query PullRequestForRun`),
httpmock.StringResponse(``))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"),
httpmock.JSONResponse([]shared.Annotation{}))
},
wantOut: "\nβ trunk successful Β· 3\nTriggered via push about 59 minutes ago\n\nJOBS\nβ cool job in 4m34s (ID 10)\n\nFor more information about a job, try: gh run view --job=<job-id>\nView this run on GitHub: https://github.com/runs/3\n",
},
{
name: "verbose",
tty: true,
opts: &ViewOptions{
RunID: "1234",
Prompt: false,
Verbose: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"),
httpmock.JSONResponse(shared.FailedRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/artifacts"),
httpmock.StringResponse(`{}`))
reg.Register(
httpmock.GraphQL(`query PullRequestForRun`),
httpmock.StringResponse(``))
reg.Register(
httpmock.REST("GET", "runs/1234/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"),
httpmock.JSONResponse([]shared.Annotation{}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/20/annotations"),
httpmock.JSONResponse(shared.FailedJobAnnotations))
},
wantOut: "\nX trunk failed Β· 1234\nTriggered via push about 59 minutes ago\n\nJOBS\nβ cool job in 4m34s (ID 10)\n β fob the barz\n β barz the fob\nX sad job in 4m34s (ID 20)\n β barf the quux\n X quux the barf\n\nANNOTATIONS\nX the job is sad\nsad job: blaze.py#420\n\n\nTo see what failed, try: gh run view 1234 --log-failed\nView this run on GitHub: https://github.com/runs/1234\n",
},
{
name: "prompts for choice, one job",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"),
httpmock.JSONResponse(shared.RunsPayload{
WorkflowRuns: shared.TestRuns,
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"),
httpmock.StringResponse(`{}`))
reg.Register(
httpmock.GraphQL(`query PullRequestForRun`),
httpmock.StringResponse(``))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"),
httpmock.JSONResponse([]shared.Annotation{}))
},
askStubs: func(as *prompt.AskStubber) {
as.StubOne(2)
},
opts: &ViewOptions{
Prompt: true,
},
wantOut: "\nβ trunk successful Β· 3\nTriggered via push about 59 minutes ago\n\nJOBS\nβ cool job in 4m34s (ID 10)\n\nFor more information about a job, try: gh run view --job=<job-id>\nView this run on GitHub: https://github.com/runs/3\n",
},
{
name: "interactive with log",
tty: true,
opts: &ViewOptions{
Prompt: true,
Log: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"),
httpmock.JSONResponse(shared.RunsPayload{
WorkflowRuns: shared.TestRuns,
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/logs"),
httpmock.FileResponse("./fixtures/run_log.zip"))
},
askStubs: func(as *prompt.AskStubber) {
as.StubOne(2)
as.StubOne(1)
},
wantOut: coolJobRunLogOutput,
},
{
name: "noninteractive with log",
opts: &ViewOptions{
JobID: "10",
Log: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/10"),
httpmock.JSONResponse(shared.SuccessfulJob))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/logs"),
httpmock.FileResponse("./fixtures/run_log.zip"))
},
wantOut: coolJobRunLogOutput,
},
{
name: "interactive with run log",
tty: true,
opts: &ViewOptions{
Prompt: true,
Log: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"),
httpmock.JSONResponse(shared.RunsPayload{
WorkflowRuns: shared.TestRuns,
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/logs"),
httpmock.FileResponse("./fixtures/run_log.zip"))
},
askStubs: func(as *prompt.AskStubber) {
as.StubOne(2)
as.StubOne(0)
},
wantOut: expectedRunLogOutput,
},
{
name: "noninteractive with run log",
tty: true,
opts: &ViewOptions{
RunID: "3",
Log: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/logs"),
httpmock.FileResponse("./fixtures/run_log.zip"))
},
wantOut: expectedRunLogOutput,
},
{
name: "interactive with log-failed",
tty: true,
opts: &ViewOptions{
Prompt: true,
LogFailed: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"),
httpmock.JSONResponse(shared.RunsPayload{
WorkflowRuns: shared.TestRuns,
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"),
httpmock.JSONResponse(shared.FailedRun))
reg.Register(
httpmock.REST("GET", "runs/1234/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/logs"),
httpmock.FileResponse("./fixtures/run_log.zip"))
},
askStubs: func(as *prompt.AskStubber) {
as.StubOne(4)
as.StubOne(2)
},
wantOut: quuxTheBarfLogOutput,
},
{
name: "noninteractive with log-failed",
opts: &ViewOptions{
JobID: "20",
LogFailed: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/20"),
httpmock.JSONResponse(shared.FailedJob))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"),
httpmock.JSONResponse(shared.FailedRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/logs"),
httpmock.FileResponse("./fixtures/run_log.zip"))
},
wantOut: quuxTheBarfLogOutput,
},
{
name: "interactive with run log-failed",
tty: true,
opts: &ViewOptions{
Prompt: true,
LogFailed: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"),
httpmock.JSONResponse(shared.RunsPayload{
WorkflowRuns: shared.TestRuns,
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"),
httpmock.JSONResponse(shared.FailedRun))
reg.Register(
httpmock.REST("GET", "runs/1234/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/logs"),
httpmock.FileResponse("./fixtures/run_log.zip"))
},
askStubs: func(as *prompt.AskStubber) {
as.StubOne(4)
as.StubOne(0)
},
wantOut: quuxTheBarfLogOutput,
},
{
name: "noninteractive with run log-failed",
tty: true,
opts: &ViewOptions{
RunID: "1234",
LogFailed: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"),
httpmock.JSONResponse(shared.FailedRun))
reg.Register(
httpmock.REST("GET", "runs/1234/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/logs"),
httpmock.FileResponse("./fixtures/run_log.zip"))
},
wantOut: quuxTheBarfLogOutput,
},
{
name: "run log but run is not done",
tty: true,
opts: &ViewOptions{
RunID: "2",
Log: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/2"),
httpmock.JSONResponse(shared.TestRun("in progress", 2, shared.InProgress, "")))
reg.Register(
httpmock.REST("GET", "runs/2/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{},
}))
},
wantErr: true,
errMsg: "run 2 is still in progress; logs will be available when it is complete",
},
{
name: "job log but job is not done",
tty: true,
opts: &ViewOptions{
JobID: "20",
Log: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/20"),
httpmock.JSONResponse(shared.Job{
ID: 20,
Status: shared.InProgress,
RunID: 2,
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/2"),
httpmock.JSONResponse(shared.TestRun("in progress", 2, shared.InProgress, "")))
},
wantErr: true,
errMsg: "job 20 is still in progress; logs will be available when it is complete",
},
{
name: "noninteractive with job",
opts: &ViewOptions{
JobID: "10",
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/10"),
httpmock.JSONResponse(shared.SuccessfulJob))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"),
httpmock.JSONResponse([]shared.Annotation{}))
},
wantOut: "\nβ trunk successful Β· 3\nTriggered via push about 59 minutes ago\n\nβ cool job in 4m34s (ID 10)\n β fob the barz\n β barz the fob\n\nTo see the full job log, try: gh run view --log --job=10\nView this run on GitHub: https://github.com/runs/3\n",
},
{
name: "interactive, multiple jobs, choose all jobs",
tty: true,
opts: &ViewOptions{
Prompt: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"),
httpmock.JSONResponse(shared.RunsPayload{
WorkflowRuns: shared.TestRuns,
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"),
httpmock.StringResponse(`{}`))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"),
httpmock.JSONResponse([]shared.Annotation{}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/20/annotations"),
httpmock.JSONResponse(shared.FailedJobAnnotations))
},
askStubs: func(as *prompt.AskStubber) {
as.StubOne(2)
as.StubOne(0)
},
wantOut: "\nβ trunk successful Β· 3\nTriggered via push about 59 minutes ago\n\nJOBS\nβ cool job in 4m34s (ID 10)\nX sad job in 4m34s (ID 20)\n β barf the quux\n X quux the barf\n\nANNOTATIONS\nX the job is sad\nsad job: blaze.py#420\n\n\nFor more information about a job, try: gh run view --job=<job-id>\nView this run on GitHub: https://github.com/runs/3\n",
},
{
name: "interactive, multiple jobs, choose specific jobs",
tty: true,
opts: &ViewOptions{
Prompt: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"),
httpmock.JSONResponse(shared.RunsPayload{
WorkflowRuns: shared.TestRuns,
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
reg.Register(
httpmock.REST("GET", "runs/3/jobs"),
httpmock.JSONResponse(shared.JobsPayload{
Jobs: []shared.Job{
shared.SuccessfulJob,
shared.FailedJob,
},
}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"),
httpmock.JSONResponse([]shared.Annotation{}))
},
askStubs: func(as *prompt.AskStubber) {
as.StubOne(2)
as.StubOne(1)
},
wantOut: "\nβ trunk successful Β· 3\nTriggered via push about 59 minutes ago\n\nβ cool job in 4m34s (ID 10)\n β fob the barz\n β barz the fob\n\nTo see the full job log, try: gh run view --log --job=10\nView this run on GitHub: https://github.com/runs/3\n",
},
{
name: "web run",
tty: true,
opts: &ViewOptions{
RunID: "3",
Web: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
},
browsedURL: "https://github.com/runs/3",
wantOut: "Opening github.com/runs/3 in your browser.\n",
},
{
name: "web job",
tty: true,
opts: &ViewOptions{
JobID: "10",
Web: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/10"),
httpmock.JSONResponse(shared.SuccessfulJob))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"),
httpmock.JSONResponse(shared.SuccessfulRun))
},
browsedURL: "https://github.com/jobs/10?check_suite_focus=true",
wantOut: "Opening github.com/jobs/10 in your browser.\n",
},
{
name: "hide job header, failure",
tty: true,
opts: &ViewOptions{
RunID: "123",
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/123"),
httpmock.JSONResponse(shared.TestRun("failed no job", 123, shared.Completed, shared.Failure)))
reg.Register(
httpmock.REST("GET", "runs/123/jobs"),
httpmock.JSONResponse(shared.JobsPayload{Jobs: []shared.Job{}}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/123/artifacts"),
httpmock.StringResponse(`{}`))
},
wantOut: "\nX trunk failed no job Β· 123\nTriggered via push about 59 minutes ago\n\nX This run likely failed because of a workflow file issue.\n\nFor more information, see: https://github.com/runs/123\n",
},
{
name: "hide job header, startup_failure",
tty: true,
opts: &ViewOptions{
RunID: "123",
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/123"),
httpmock.JSONResponse(shared.TestRun("failed no job", 123, shared.Completed, shared.StartupFailure)))
reg.Register(
httpmock.REST("GET", "runs/123/jobs"),
httpmock.JSONResponse(shared.JobsPayload{Jobs: []shared.Job{}}))
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/123/artifacts"),
httpmock.StringResponse(`{}`))
},
wantOut: "\nX trunk failed no job Β· 123\nTriggered via push about 59 minutes ago\n\nX This run likely failed because of a workflow file issue.\n\nFor more information, see: https://github.com/runs/123\n",
},
}
for _, tt := range tests {
reg := &httpmock.Registry{}
tt.httpStubs(reg)
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.Now = func() time.Time {
notnow, _ := time.Parse("2006-01-02 15:04:05", "2021-02-23 05:50:00")
return notnow
}
io, _, stdout, _ := iostreams.Test()
io.SetStdoutTTY(tt.tty)
tt.opts.IO = io
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
}
as, teardown := prompt.InitAskStubber()
defer teardown()
if tt.askStubs != nil {
tt.askStubs(as)
}
browser := &cmdutil.TestBrowser{}
tt.opts.Browser = browser
rlc := testRunLogCache{}
tt.opts.RunLogCache = rlc
t.Run(tt.name, func(t *testing.T) {
err := runView(tt.opts)
if tt.wantErr {
assert.Error(t, err)
if tt.errMsg != "" {
assert.Equal(t, tt.errMsg, err.Error())
}
if !tt.opts.ExitStatus {
return
}
}
if !tt.opts.ExitStatus {
assert.NoError(t, err)
}
assert.Equal(t, tt.wantOut, stdout.String())
if tt.browsedURL != "" {
assert.Equal(t, tt.browsedURL, browser.BrowsedURL())
}
reg.Verify(t)
})
}
}
// Structure of fixture zip file
// run log/
// βββ cool job/
// β βββ 1_fob the barz.txt
// β βββ 2_barz the fob.txt
// βββ sad job/
// βββ 1_barf the quux.txt
// βββ 2_quux the barf.txt
func Test_attachRunLog(t *testing.T) {
tests := []struct {
name string
job shared.Job
wantMatch bool
wantFilename string
}{
{
name: "matching job name and step number 1",
job: shared.Job{
Name: "cool job",
Steps: []shared.Step{{
Name: "fob the barz",
Number: 1,
}},
},
wantMatch: true,
wantFilename: "cool job/1_fob the barz.txt",
},
{
name: "matching job name and step number 2",
job: shared.Job{
Name: "cool job",
Steps: []shared.Step{{
Name: "barz the fob",
Number: 2,
}},
},
wantMatch: true,
wantFilename: "cool job/2_barz the fob.txt",
},
{
name: "matching job name and step number and mismatch step name",
job: shared.Job{
Name: "cool job",
Steps: []shared.Step{{
Name: "mismatch",
Number: 1,
}},
},
wantMatch: true,
wantFilename: "cool job/1_fob the barz.txt",
},
{
name: "matching job name and mismatch step number",
job: shared.Job{
Name: "cool job",
Steps: []shared.Step{{
Name: "fob the barz",
Number: 3,
}},
},
wantMatch: false,
},
{
name: "escape metacharacters in job name",
job: shared.Job{
Name: "metacharacters .+*?()|[]{}^$ job",
Steps: []shared.Step{{
Name: "fob the barz",
Number: 0,
}},
},
wantMatch: false,
},
{
name: "mismatching job name",
job: shared.Job{
Name: "mismatch",
Steps: []shared.Step{{
Name: "fob the barz",
Number: 1,
}},
},
wantMatch: false,
},
}
rlz, _ := zip.OpenReader("./fixtures/run_log.zip")
defer rlz.Close()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
attachRunLog(rlz, []shared.Job{tt.job})
for _, step := range tt.job.Steps {
log := step.Log
logPresent := log != nil
assert.Equal(t, tt.wantMatch, logPresent)
if logPresent {
assert.Equal(t, tt.wantFilename, log.Name)
}
}
})
}
}
type testRunLogCache struct{}
func (testRunLogCache) Exists(path string) bool {
return false
}
func (testRunLogCache) Create(path string, content io.ReadCloser) error {
return nil
}
func (testRunLogCache) Open(path string) (*zip.ReadCloser, error) {
return zip.OpenReader("./fixtures/run_log.zip")
}
var barfTheFobLogOutput = heredoc.Doc(`
cool job barz the fob log line 1
cool job barz the fob log line 2
cool job barz the fob log line 3
`)
var fobTheBarzLogOutput = heredoc.Doc(`
cool job fob the barz log line 1
cool job fob the barz log line 2
cool job fob the barz log line 3
`)
var barfTheQuuxLogOutput = heredoc.Doc(`
sad job barf the quux log line 1
sad job barf the quux log line 2
sad job barf the quux log line 3
`)
var quuxTheBarfLogOutput = heredoc.Doc(`
sad job quux the barf log line 1
sad job quux the barf log line 2
sad job quux the barf log line 3
`)
var coolJobRunLogOutput = fmt.Sprintf("%s%s", fobTheBarzLogOutput, barfTheFobLogOutput)
var sadJobRunLogOutput = fmt.Sprintf("%s%s", barfTheQuuxLogOutput, quuxTheBarfLogOutput)
var expectedRunLogOutput = fmt.Sprintf("%s%s", coolJobRunLogOutput, sadJobRunLogOutput)
| pkg/cmd/run/view/view_test.go | 0 | https://github.com/cli/cli/commit/315c6e4eb7ec8c3db45b10e24ac37f3b1ea2743c | [
0.00026369449915364385,
0.00017317644960712641,
0.00016516084724571556,
0.00017134477093350142,
0.00001269503900402924
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.