repo stringlengths 5 67 | sha stringlengths 40 40 | path stringlengths 4 234 | url stringlengths 85 339 | language stringclasses 6 values | split stringclasses 3 values | doc stringlengths 3 51.2k | sign stringlengths 5 8.01k | problem stringlengths 13 51.2k | output stringlengths 0 3.87M |
|---|---|---|---|---|---|---|---|---|---|
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1481-L1487 | go | train | // tempfile returns a temporary file for use | func tempfile() (*os.File, error) | // tempfile returns a temporary file for use
func tempfile() (*os.File, error) | {
f, err := ioutil.TempFile("", "rqlilte-snap-")
if err != nil {
return nil, err
}
return f, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/transport.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/transport.go#L30-L32 | go | train | // Dial creates a new network connection. | func (t *Transport) Dial(addr raft.ServerAddress, timeout time.Duration) (net.Conn, error) | // Dial creates a new network connection.
func (t *Transport) Dial(addr raft.ServerAddress, timeout time.Duration) (net.Conn, error) | {
return t.ln.Dial(string(addr), timeout)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L190-L199 | go | train | // New returns an uninitialized HTTP service. If credentials is nil, then
// the service performs no authentication and authorization checks. | func New(addr string, store Store, credentials CredentialStore) *Service | // New returns an uninitialized HTTP service. If credentials is nil, then
// the service performs no authentication and authorization checks.
func New(addr string, store Store, credentials CredentialStore) *Service | {
return &Service{
addr: addr,
store: store,
start: time.Now(),
statuses: make(map[string]Statuser),
credentialStore: credentials,
logger: log.New(os.Stderr, "[http] ", log.LstdFlags),
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L202-L236 | go | train | // Start starts the service. | func (s *Service) Start() error | // Start starts the service.
func (s *Service) Start() error | {
server := http.Server{
Handler: s,
}
var ln net.Listener
var err error
if s.CertFile == "" || s.KeyFile == "" {
ln, err = net.Listen("tcp", s.addr)
if err != nil {
return err
}
} else {
config, err := createTLSConfig(s.CertFile, s.KeyFile)
if err != nil {
return err
}
ln, err = tls.Listen("tcp", s.addr, config)
if err != nil {
return err
}
s.logger.Printf("secure HTTPS server enabled with cert %s, key %s", s.CertFile, s.KeyFile)
}
s.ln = ln
go func() {
err := server.Serve(s.ln)
if err != nil {
s.logger.Println("HTTP service Serve() returned:", err.Error())
}
}()
s.logger.Println("service listening on", s.addr)
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L245-L247 | go | train | // ServeHTTP allows Service to serve HTTP requests. | func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) | // ServeHTTP allows Service to serve HTTP requests.
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) | {
s.rootHandler.Handler(s).ServeHTTP(w, r)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L250-L260 | go | train | // RegisterStatus allows other modules to register status for serving over HTTP. | func (s *Service) RegisterStatus(key string, stat Statuser) error | // RegisterStatus allows other modules to register status for serving over HTTP.
func (s *Service) RegisterStatus(key string, stat Statuser) error | {
s.statusMu.Lock()
defer s.statusMu.Unlock()
if _, ok := s.statuses[key]; ok {
return fmt.Errorf("status already registered with key %s", key)
}
s.statuses[key] = stat
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L263-L294 | go | train | // createConnection creates a connection and returns its ID. | func (s *Service) createConnection(w http.ResponseWriter, r *http.Request) | // createConnection creates a connection and returns its ID.
func (s *Service) createConnection(w http.ResponseWriter, r *http.Request) | {
opts := store.ConnectionOptions{
IdleTimeout: s.ConnIdleTimeout,
TxTimeout: s.ConnTxTimeout,
}
d, b, err := txTimeout(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if b {
opts.TxTimeout = d
}
d, b, err = idleTimeout(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if b {
opts.IdleTimeout = d
}
conn, err := s.store.Connect(&opts)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
w.Header().Set("Location", s.FormConnectionURL(r, conn.ID))
w.WriteHeader(http.StatusCreated)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L298-L304 | go | train | // deleteConnection closes a connection and makes it unavailable for
// future use. | func (s *Service) deleteConnection(id uint64) error | // deleteConnection closes a connection and makes it unavailable for
// future use.
func (s *Service) deleteConnection(id uint64) error | {
conn, ok := s.store.Connection(id)
if !ok {
return nil
}
return conn.Close()
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L307-L356 | go | train | // handleJoin handles cluster-join requests from other nodes. | func (s *Service) handleJoin(w http.ResponseWriter, r *http.Request) | // handleJoin handles cluster-join requests from other nodes.
func (s *Service) handleJoin(w http.ResponseWriter, r *http.Request) | {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
md := map[string]interface{}{}
if err := json.Unmarshal(b, &md); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteID, ok := md["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteAddr, ok := md["addr"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
var m map[string]string
if _, ok := md["meta"].(map[string]interface{}); ok {
m = make(map[string]string)
for k, v := range md["meta"].(map[string]interface{}) {
m[k] = v.(string)
}
}
if err := s.store.Join(remoteID.(string), remoteAddr.(string), m); err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
b := bytes.NewBufferString(err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write(b.Bytes())
return
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L359-L399 | go | train | // handleRemove handles cluster-remove requests. | func (s *Service) handleRemove(w http.ResponseWriter, r *http.Request) | // handleRemove handles cluster-remove requests.
func (s *Service) handleRemove(w http.ResponseWriter, r *http.Request) | {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
m := map[string]string{}
if err := json.Unmarshal(b, &m); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if len(m) != 1 {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteID, ok := m["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := s.store.Remove(remoteID); err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
w.WriteHeader(http.StatusInternalServerError)
return
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L402-L422 | go | train | // handleBackup returns the consistent database snapshot. | func (s *Service) handleBackup(w http.ResponseWriter, r *http.Request) | // handleBackup returns the consistent database snapshot.
func (s *Service) handleBackup(w http.ResponseWriter, r *http.Request) | {
noLeader, err := noLeader(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
bf, err := backupFormat(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = s.store.Backup(!noLeader, bf, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.lastBackup = time.Now()
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L425-L463 | go | train | // handleLoad loads the state contained in a .dump output. | func (s *Service) handleLoad(w http.ResponseWriter, r *http.Request) | // handleLoad loads the state contained in a .dump output.
func (s *Service) handleLoad(w http.ResponseWriter, r *http.Request) | {
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var resp Response
queries := []string{string(b)}
results, err := s.store.ExecuteOrAbort(&store.ExecuteRequest{queries, timings, false})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Results
if timings {
resp.Time = results.Time
}
resp.Raft = &results.Raft
}
writeResponse(w, r, &resp)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L466-L538 | go | train | // handleStatus returns status on the system. | func (s *Service) handleStatus(w http.ResponseWriter, r *http.Request) | // handleStatus returns status on the system.
func (s *Service) handleStatus(w http.ResponseWriter, r *http.Request) | {
results, err := s.store.Stats()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
rt := map[string]interface{}{
"GOARCH": runtime.GOARCH,
"GOOS": runtime.GOOS,
"GOMAXPROCS": runtime.GOMAXPROCS(0),
"num_cpu": runtime.NumCPU(),
"num_goroutine": runtime.NumGoroutine(),
"version": runtime.Version(),
}
httpStatus := map[string]interface{}{
"addr": s.Addr().String(),
"auth": prettyEnabled(s.credentialStore != nil),
"redirect": s.leaderAPIAddr(),
"conn_idle_timeout": s.ConnIdleTimeout.String(),
"conn_tx_timeout": s.ConnTxTimeout.String(),
}
nodeStatus := map[string]interface{}{
"start_time": s.start,
"uptime": time.Since(s.start).String(),
}
// Build the status response.
status := map[string]interface{}{
"runtime": rt,
"store": results,
"http": httpStatus,
"node": nodeStatus,
}
if !s.lastBackup.IsZero() {
status["last_backup_time"] = s.lastBackup
}
if s.BuildInfo != nil {
status["build"] = s.BuildInfo
}
// Add any registered statusers.
func() {
s.statusMu.RLock()
defer s.statusMu.RUnlock()
for k, v := range s.statuses {
stat, err := v.Stats()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
status[k] = stat
}
}()
pretty, _ := isPretty(r)
var b []byte
if pretty {
b, err = json.MarshalIndent(status, "", " ")
} else {
b, err = json.Marshal(status)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
_, err = w.Write([]byte(b))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L541-L603 | go | train | // handleExecute handles queries that modify the database. | func (s *Service) handleExecute(connID uint64, w http.ResponseWriter, r *http.Request) | // handleExecute handles queries that modify the database.
func (s *Service) handleExecute(connID uint64, w http.ResponseWriter, r *http.Request) | {
isAtomic, err := isAtomic(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
queries := []string{}
if err := json.Unmarshal(b, &queries); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get the right executer object.
var execer Execer
if connID == defaultConnID {
execer = s.store
} else {
c, ok := s.store.Connection(connID)
if !ok {
http.Error(w, "connection not found", http.StatusNotFound)
return
}
execer = c
}
var resp Response
results, err := execer.Execute(&store.ExecuteRequest{queries, timings, isAtomic})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Results
if timings {
resp.Time = results.Time
}
resp.Raft = &results.Raft
}
writeResponse(w, r, &resp)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L606-L668 | go | train | // handleQuery handles queries that do not modify the database. | func (s *Service) handleQuery(connID uint64, w http.ResponseWriter, r *http.Request) | // handleQuery handles queries that do not modify the database.
func (s *Service) handleQuery(connID uint64, w http.ResponseWriter, r *http.Request) | {
isAtomic, err := isAtomic(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
lvl, err := level(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get the query statement(s), and do tx if necessary.
queries, err := requestQueries(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Get the right queryer object.
var queryer Queryer
if connID == defaultConnID {
queryer = s.store
} else {
c, ok := s.store.Connection(connID)
if !ok {
http.Error(w, "connection not found", http.StatusNotFound)
return
}
queryer = c
}
var resp Response
results, err := queryer.Query(&store.QueryRequest{queries, timings, isAtomic, lvl})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Rows
if timings {
resp.Time = results.Time
}
resp.Raft = results.Raft
}
writeResponse(w, r, &resp)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L676-L682 | go | train | // FormRedirect returns the value for the "Location" header for a 301 response. | func (s *Service) FormRedirect(r *http.Request, host string) string | // FormRedirect returns the value for the "Location" header for a 301 response.
func (s *Service) FormRedirect(r *http.Request, host string) string | {
rq := r.URL.RawQuery
if rq != "" {
rq = fmt.Sprintf("?%s", rq)
}
return fmt.Sprintf("%s://%s%s%s", s.protocol(), host, r.URL.Path, rq)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L685-L687 | go | train | // FormConnectionURL returns the URL of the new connection. | func (s *Service) FormConnectionURL(r *http.Request, id uint64) string | // FormConnectionURL returns the URL of the new connection.
func (s *Service) FormConnectionURL(r *http.Request, id uint64) string | {
return fmt.Sprintf("%s://%s/db/connections/%d", s.protocol(), r.Host, id)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L691-L701 | go | train | // CheckRequestPerm returns true if authentication is enabled and the user contained
// in the BasicAuth request has either PermAll, or the given perm. | func (s *Service) CheckRequestPerm(r *http.Request, perm string) bool | // CheckRequestPerm returns true if authentication is enabled and the user contained
// in the BasicAuth request has either PermAll, or the given perm.
func (s *Service) CheckRequestPerm(r *http.Request, perm string) bool | {
if s.credentialStore == nil {
return true
}
username, _, ok := r.BasicAuth()
if !ok {
return false
}
return s.credentialStore.HasAnyPerm(username, perm, PermAll)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L712-L719 | go | train | // addBuildVersion adds the build version to the HTTP response. | func (s *Service) addBuildVersion(w http.ResponseWriter) | // addBuildVersion adds the build version to the HTTP response.
func (s *Service) addBuildVersion(w http.ResponseWriter) | {
// Add version header to every response, if available.
version := "unknown"
if v, ok := s.BuildInfo["version"].(string); ok {
version = v
}
w.Header().Add(VersionHTTPHeader, version)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L788-L797 | go | train | // queryParam returns whether the given query param is set to true. | func queryParam(req *http.Request, param string) (bool, error) | // queryParam returns whether the given query param is set to true.
func queryParam(req *http.Request, param string) (bool, error) | {
err := req.ParseForm()
if err != nil {
return false, err
}
if _, ok := req.Form[param]; ok {
return true, nil
}
return false, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L800-L811 | go | train | // durationParam returns the duration of the given query param, if set. | func durationParam(req *http.Request, param string) (time.Duration, bool, error) | // durationParam returns the duration of the given query param, if set.
func durationParam(req *http.Request, param string) (time.Duration, bool, error) | {
q := req.URL.Query()
t := strings.TrimSpace(q.Get(param))
if t == "" {
return 0, false, nil
}
dur, err := time.ParseDuration(t)
if err != nil {
return 0, false, err
}
return dur, true, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L814-L817 | go | train | // stmtParam returns the value for URL param 'q', if present. | func stmtParam(req *http.Request) (string, error) | // stmtParam returns the value for URL param 'q', if present.
func stmtParam(req *http.Request) (string, error) | {
q := req.URL.Query()
return strings.TrimSpace(q.Get("q")), nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L831-L840 | go | train | // isAtomic returns whether the HTTP request is an atomic request. | func isAtomic(req *http.Request) (bool, error) | // isAtomic returns whether the HTTP request is an atomic request.
func isAtomic(req *http.Request) (bool, error) | {
// "transaction" is checked for backwards compatibility with
// client libraries.
for _, q := range []string{"atomic", "transaction"} {
if a, err := queryParam(req, q); err != nil || a {
return a, err
}
}
return false, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L853-L855 | go | train | // txTimeout returns the duration of any transaction timeout set. | func txTimeout(req *http.Request) (time.Duration, bool, error) | // txTimeout returns the duration of any transaction timeout set.
func txTimeout(req *http.Request) (time.Duration, bool, error) | {
return durationParam(req, "tx_timeout")
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L863-L877 | go | train | // level returns the requested consistency level for a query | func level(req *http.Request) (store.ConsistencyLevel, error) | // level returns the requested consistency level for a query
func level(req *http.Request) (store.ConsistencyLevel, error) | {
q := req.URL.Query()
lvl := strings.TrimSpace(q.Get("level"))
switch strings.ToLower(lvl) {
case "none":
return store.None, nil
case "weak":
return store.Weak, nil
case "strong":
return store.Strong, nil
default:
return store.Weak, nil
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L881-L892 | go | train | // backuFormat returns the request backup format, setting the response header
// accordingly. | func backupFormat(w http.ResponseWriter, r *http.Request) (store.BackupFormat, error) | // backuFormat returns the request backup format, setting the response header
// accordingly.
func backupFormat(w http.ResponseWriter, r *http.Request) (store.BackupFormat, error) | {
fmt, err := fmtParam(r)
if err != nil {
return store.BackupBinary, err
}
if fmt == "sql" {
w.Header().Set("Content-Type", "application/sql")
return store.BackupSQL, nil
}
w.Header().Set("Content-Type", "application/octet-stream")
return store.BackupBinary, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | http/service.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L903-L908 | go | train | // NormalizeAddr ensures that the given URL has a HTTP protocol prefix.
// If none is supplied, it prefixes the URL with "http://". | func NormalizeAddr(addr string) string | // NormalizeAddr ensures that the given URL has a HTTP protocol prefix.
// If none is supplied, it prefixes the URL with "http://".
func NormalizeAddr(addr string) string | {
if !strings.HasPrefix(addr, "http://") && !strings.HasPrefix(addr, "https://") {
return fmt.Sprintf("http://%s", addr)
}
return addr
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L75-L102 | go | train | // New returns an instance of the database at path. If the database
// has already been created and opened, this database will share
// the data of that database when connected. | func New(path, dsnQuery string, memory bool) (*DB, error) | // New returns an instance of the database at path. If the database
// has already been created and opened, this database will share
// the data of that database when connected.
func New(path, dsnQuery string, memory bool) (*DB, error) | {
q, err := url.ParseQuery(dsnQuery)
if err != nil {
return nil, err
}
if memory {
q.Set("mode", "memory")
q.Set("cache", "shared")
}
if !strings.HasPrefix(path, "file:") {
path = fmt.Sprintf("file:%s", path)
}
var fqdsn string
if len(q) > 0 {
fqdsn = fmt.Sprintf("%s?%s", path, q.Encode())
} else {
fqdsn = path
}
return &DB{
path: path,
dsnQuery: dsnQuery,
memory: memory,
fqdsn: fqdsn,
}, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L105-L115 | go | train | // Connect returns a connection to the database. | func (d *DB) Connect() (*Conn, error) | // Connect returns a connection to the database.
func (d *DB) Connect() (*Conn, error) | {
drv := sqlite3.SQLiteDriver{}
c, err := drv.Open(d.fqdsn)
if err != nil {
return nil, err
}
return &Conn{
sqlite: c.(*sqlite3.SQLiteConn),
}, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L133-L136 | go | train | // AbortTransaction aborts -- rolls back -- any active transaction. Calling code
// should know exactly what it is doing if it decides to call this function. It
// can be used to clean up any dangling state that may result from certain
// error scenarios. | func (c *Conn) AbortTransaction() error | // AbortTransaction aborts -- rolls back -- any active transaction. Calling code
// should know exactly what it is doing if it decides to call this function. It
// can be used to clean up any dangling state that may result from certain
// error scenarios.
func (c *Conn) AbortTransaction() error | {
_, err := c.Execute([]string{`ROLLBACK`}, false, false)
return err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L139-L239 | go | train | // Execute executes queries that modify the database. | func (c *Conn) Execute(queries []string, tx, xTime bool) ([]*Result, error) | // Execute executes queries that modify the database.
func (c *Conn) Execute(queries []string, tx, xTime bool) ([]*Result, error) | {
stats.Add(numExecutions, int64(len(queries)))
if tx {
stats.Add(numETx, 1)
}
type Execer interface {
Exec(query string, args []driver.Value) (driver.Result, error)
}
var allResults []*Result
err := func() error {
var execer Execer
var rollback bool
var t driver.Tx
var err error
// Check for the err, if set rollback.
defer func() {
if t != nil {
if rollback {
t.Rollback()
return
}
t.Commit()
}
}()
// handleError sets the error field on the given result. It returns
// whether the caller should continue processing or break.
handleError := func(result *Result, err error) bool {
stats.Add(numExecutionErrors, 1)
result.Error = err.Error()
allResults = append(allResults, result)
if tx {
rollback = true // Will trigger the rollback.
return false
}
return true
}
execer = c.sqlite
// Create the correct execution object, depending on whether a
// transaction was requested.
if tx {
t, err = c.sqlite.Begin()
if err != nil {
return err
}
}
// Execute each query.
for _, q := range queries {
if q == "" {
continue
}
result := &Result{}
start := time.Now()
r, err := execer.Exec(q, nil)
if err != nil {
if handleError(result, err) {
continue
}
break
}
if r == nil {
continue
}
lid, err := r.LastInsertId()
if err != nil {
if handleError(result, err) {
continue
}
break
}
result.LastInsertID = lid
ra, err := r.RowsAffected()
if err != nil {
if handleError(result, err) {
continue
}
break
}
result.RowsAffected = ra
if xTime {
result.Time = time.Now().Sub(start).Seconds()
}
allResults = append(allResults, result)
}
return nil
}()
return allResults, err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L242-L320 | go | train | // Query executes queries that return rows, but don't modify the database. | func (c *Conn) Query(queries []string, tx, xTime bool) ([]*Rows, error) | // Query executes queries that return rows, but don't modify the database.
func (c *Conn) Query(queries []string, tx, xTime bool) ([]*Rows, error) | {
stats.Add(numQueries, int64(len(queries)))
if tx {
stats.Add(numQTx, 1)
}
type Queryer interface {
Query(query string, args []driver.Value) (driver.Rows, error)
}
var allRows []*Rows
err := func() (err error) {
var queryer Queryer
var t driver.Tx
defer func() {
// XXX THIS DOESN'T ACTUALLY WORK! Might as WELL JUST COMMIT?
if t != nil {
if err != nil {
t.Rollback()
return
}
t.Commit()
}
}()
queryer = c.sqlite
// Create the correct query object, depending on whether a
// transaction was requested.
if tx {
t, err = c.sqlite.Begin()
if err != nil {
return err
}
}
for _, q := range queries {
if q == "" {
continue
}
rows := &Rows{}
start := time.Now()
rs, err := queryer.Query(q, nil)
if err != nil {
rows.Error = err.Error()
allRows = append(allRows, rows)
continue
}
defer rs.Close()
columns := rs.Columns()
rows.Columns = columns
rows.Types = rs.(*sqlite3.SQLiteRows).DeclTypes()
dest := make([]driver.Value, len(rows.Columns))
for {
err := rs.Next(dest)
if err != nil {
if err != io.EOF {
rows.Error = err.Error()
}
break
}
values := normalizeRowValues(dest, rows.Types)
rows.Values = append(rows.Values, values)
}
if xTime {
rows.Time = time.Now().Sub(start).Seconds()
}
allRows = append(allRows, rows)
}
return nil
}()
return allRows, err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L323-L330 | go | train | // EnableFKConstraints allows control of foreign key constraint checks. | func (c *Conn) EnableFKConstraints(e bool) error | // EnableFKConstraints allows control of foreign key constraint checks.
func (c *Conn) EnableFKConstraints(e bool) error | {
q := fkChecksEnabled
if !e {
q = fkChecksDisabled
}
_, err := c.sqlite.Exec(q, nil)
return err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L333-L350 | go | train | // FKConstraints returns whether FK constraints are set or not. | func (c *Conn) FKConstraints() (bool, error) | // FKConstraints returns whether FK constraints are set or not.
func (c *Conn) FKConstraints() (bool, error) | {
r, err := c.sqlite.Query(fkChecks, nil)
if err != nil {
return false, err
}
dest := make([]driver.Value, len(r.Columns()))
types := r.(*sqlite3.SQLiteRows).DeclTypes()
if err := r.Next(dest); err != nil {
return false, err
}
values := normalizeRowValues(dest, types)
if values[0] == int64(1) {
return true, nil
}
return false, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L356-L358 | go | train | // Load loads the connected database from the database connected to src.
// It overwrites the data contained in this database. It is the caller's
// responsibility to ensure that no other connections to this database
// are accessed while this operation is in progress. | func (c *Conn) Load(src *Conn) error | // Load loads the connected database from the database connected to src.
// It overwrites the data contained in this database. It is the caller's
// responsibility to ensure that no other connections to this database
// are accessed while this operation is in progress.
func (c *Conn) Load(src *Conn) error | {
return copyDatabase(c.sqlite, src.sqlite)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L366-L368 | go | train | // Backup writes a snapshot of the database over the given database
// connection, erasing all the contents of the destination database.
// The consistency of the snapshot is READ_COMMITTED relative to any
// other connections currently open to this database. The caller must
// ensure that all connections to the destination database are not
// accessed during this operation. | func (c *Conn) Backup(dst *Conn) error | // Backup writes a snapshot of the database over the given database
// connection, erasing all the contents of the destination database.
// The consistency of the snapshot is READ_COMMITTED relative to any
// other connections currently open to this database. The caller must
// ensure that all connections to the destination database are not
// accessed during this operation.
func (c *Conn) Backup(dst *Conn) error | {
return copyDatabase(dst.sqlite, c.sqlite)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L373-L450 | go | train | // Dump writes a snapshot of the database in SQL text format. The consistency
// of the snapshot is READ_COMMITTED relative to any other connections
// currently open to this database. | func (c *Conn) Dump(w io.Writer) error | // Dump writes a snapshot of the database in SQL text format. The consistency
// of the snapshot is READ_COMMITTED relative to any other connections
// currently open to this database.
func (c *Conn) Dump(w io.Writer) error | {
if _, err := w.Write([]byte("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n")); err != nil {
return err
}
// Get the schema.
query := `SELECT "name", "type", "sql" FROM "sqlite_master"
WHERE "sql" NOT NULL AND "type" == 'table' ORDER BY "name"`
rows, err := c.Query([]string{query}, false, false)
if err != nil {
return err
}
row := rows[0]
for _, v := range row.Values {
table := v[0].(string)
var stmt string
if table == "sqlite_sequence" {
stmt = `DELETE FROM "sqlite_sequence";`
} else if table == "sqlite_stat1" {
stmt = `ANALYZE "sqlite_master";`
} else if strings.HasPrefix(table, "sqlite_") {
continue
} else {
stmt = v[2].(string)
}
if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", stmt))); err != nil {
return err
}
tableIndent := strings.Replace(table, `"`, `""`, -1)
query = fmt.Sprintf(`PRAGMA table_info("%s")`, tableIndent)
r, err := c.Query([]string{query}, false, false)
if err != nil {
return err
}
var columnNames []string
for _, w := range r[0].Values {
columnNames = append(columnNames, fmt.Sprintf(`'||quote("%s")||'`, w[1].(string)))
}
query = fmt.Sprintf(`SELECT 'INSERT INTO "%s" VALUES(%s)' FROM "%s";`,
tableIndent,
strings.Join(columnNames, ","),
tableIndent)
r, err = c.Query([]string{query}, false, false)
if err != nil {
return err
}
for _, x := range r[0].Values {
y := fmt.Sprintf("%s;\n", x[0].(string))
if _, err := w.Write([]byte(y)); err != nil {
return err
}
}
}
// Do indexes, triggers, and views.
query = `SELECT "name", "type", "sql" FROM "sqlite_master"
WHERE "sql" NOT NULL AND "type" IN ('index', 'trigger', 'view')`
rows, err = c.Query([]string{query}, false, false)
if err != nil {
return err
}
row = rows[0]
for _, v := range row.Values {
if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", v[2]))); err != nil {
return err
}
}
if _, err := w.Write([]byte("COMMIT;\n")); err != nil {
return err
}
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L453-L458 | go | train | // Close closes the connection. | func (c *Conn) Close() error | // Close closes the connection.
func (c *Conn) Close() error | {
if c != nil {
return c.sqlite.Close()
}
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L485-L500 | go | train | // normalizeRowValues performs some normalization of values in the returned rows.
// Text values come over (from sqlite-go) as []byte instead of strings
// for some reason, so we have explicitly convert (but only when type
// is "text" so we don't affect BLOB types) | func normalizeRowValues(row []driver.Value, types []string) []interface{} | // normalizeRowValues performs some normalization of values in the returned rows.
// Text values come over (from sqlite-go) as []byte instead of strings
// for some reason, so we have explicitly convert (but only when type
// is "text" so we don't affect BLOB types)
func normalizeRowValues(row []driver.Value, types []string) []interface{} | {
values := make([]interface{}, len(types))
for i, v := range row {
if isTextType(types[i]) {
switch val := v.(type) {
case []byte:
values[i] = string(val)
default:
values[i] = val
}
} else {
values[i] = v
}
}
return values
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | db/db.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L504-L514 | go | train | // isTextType returns whether the given type has a SQLite text affinity.
// http://www.sqlite.org/datatype3.html | func isTextType(t string) bool | // isTextType returns whether the given type has a SQLite text affinity.
// http://www.sqlite.org/datatype3.html
func isTextType(t string) bool | {
return t == "text" ||
t == "json" ||
t == "" ||
strings.HasPrefix(t, "varchar") ||
strings.HasPrefix(t, "varying character") ||
strings.HasPrefix(t, "nchar") ||
strings.HasPrefix(t, "native character") ||
strings.HasPrefix(t, "nvarchar") ||
strings.HasPrefix(t, "clob")
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | cmd/rqlite/main.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlite/main.go#L233-L289 | go | train | // cliJSON fetches JSON from a URL, and displays it at the CLI. | func cliJSON(ctx *cli.Context, cmd, line, url string, argv *argT) error | // cliJSON fetches JSON from a URL, and displays it at the CLI.
func cliJSON(ctx *cli.Context, cmd, line, url string, argv *argT) error | {
// Recursive JSON printer.
var pprint func(indent int, m map[string]interface{})
pprint = func(indent int, m map[string]interface{}) {
indentation := " "
for k, v := range m {
if v == nil {
continue
}
switch v.(type) {
case map[string]interface{}:
for i := 0; i < indent; i++ {
fmt.Print(indentation)
}
fmt.Printf("%s:\n", k)
pprint(indent+1, v.(map[string]interface{}))
default:
for i := 0; i < indent; i++ {
fmt.Print(indentation)
}
fmt.Printf("%s: %v\n", k, v)
}
}
}
client := http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: argv.Insecure},
}}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return fmt.Errorf("unauthorized")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
ret := make(map[string]interface{})
if err := json.Unmarshal(body, &ret); err != nil {
return err
}
// Specific key requested?
parts := strings.Split(line, " ")
if len(parts) >= 2 {
ret = map[string]interface{}{parts[1]: ret[parts[1]]}
}
pprint(0, ret)
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | disco/client.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/disco/client.go#L29-L34 | go | train | // New returns an initialized Discovery Service client. | func New(url string) *Client | // New returns an initialized Discovery Service client.
func New(url string) *Client | {
return &Client{
url: url,
logger: log.New(os.Stderr, "[discovery] ", log.LstdFlags),
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | disco/client.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/disco/client.go#L43-L88 | go | train | // Register attempts to register with the Discovery Service, using the given
// address. | func (c *Client) Register(id, addr string) (*Response, error) | // Register attempts to register with the Discovery Service, using the given
// address.
func (c *Client) Register(id, addr string) (*Response, error) | {
m := map[string]string{
"addr": addr,
}
url := c.registrationURL(c.url, id)
client := &http.Client{}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
for {
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
c.logger.Printf("discovery client attempting registration of %s at %s", addr, url)
resp, err := client.Post(url, "application-type/json", bytes.NewReader(b))
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusOK:
r := &Response{}
if err := json.Unmarshal(b, r); err != nil {
return nil, err
}
c.logger.Printf("discovery client successfully registered %s at %s", addr, url)
return r, nil
case http.StatusMovedPermanently:
url = resp.Header.Get("location")
c.logger.Println("discovery client redirecting to", url)
continue
default:
return nil, errors.New(resp.Status)
}
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | cmd/rqlited/main.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlited/main.go#L374-L394 | go | train | // startProfile initializes the CPU and memory profile, if specified. | func startProfile(cpuprofile, memprofile string) | // startProfile initializes the CPU and memory profile, if specified.
func startProfile(cpuprofile, memprofile string) | {
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
log.Fatalf("failed to create CPU profile file at %s: %s", cpuprofile, err.Error())
}
log.Printf("writing CPU profile to: %s\n", cpuprofile)
prof.cpu = f
pprof.StartCPUProfile(prof.cpu)
}
if memprofile != "" {
f, err := os.Create(memprofile)
if err != nil {
log.Fatalf("failed to create memory profile file at %s: %s", cpuprofile, err.Error())
}
log.Printf("writing memory profile to: %s\n", memprofile)
prof.mem = f
runtime.MemProfileRate = 4096
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | cmd/rqlited/main.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlited/main.go#L397-L408 | go | train | // stopProfile closes the CPU and memory profiles if they are running. | func stopProfile() | // stopProfile closes the CPU and memory profiles if they are running.
func stopProfile() | {
if prof.cpu != nil {
pprof.StopCPUProfile()
prof.cpu.Close()
log.Println("CPU profiling stopped")
}
if prof.mem != nil {
pprof.Lookup("heap").WriteTo(prof.mem, 0)
prof.mem.Close()
log.Println("memory profiling stopped")
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | cluster/join.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cluster/join.go#L25-L43 | go | train | // Join attempts to join the cluster at one of the addresses given in joinAddr.
// It walks through joinAddr in order, and sets the node ID and Raft address of
// the joining node as id addr respectively. It returns the endpoint
// successfully used to join the cluster. | func Join(joinAddr []string, id, addr string, meta map[string]string, skip bool) (string, error) | // Join attempts to join the cluster at one of the addresses given in joinAddr.
// It walks through joinAddr in order, and sets the node ID and Raft address of
// the joining node as id addr respectively. It returns the endpoint
// successfully used to join the cluster.
func Join(joinAddr []string, id, addr string, meta map[string]string, skip bool) (string, error) | {
var err error
var j string
logger := log.New(os.Stderr, "[cluster-join] ", log.LstdFlags)
for i := 0; i < numAttempts; i++ {
for _, a := range joinAddr {
j, err = join(a, id, addr, meta, skip)
if err == nil {
// Success!
return j, nil
}
}
logger.Printf("failed to join cluster at %s, sleeping %s before retry", joinAddr, attemptInterval)
time.Sleep(attemptInterval)
}
logger.Printf("failed to join cluster at %s, after %d attempts", joinAddr, numAttempts)
return "", err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | cmd/rqlite/query.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlite/query.go#L33-L52 | go | train | // Get implements textutil.Table interface | func (r *Rows) Get(i, j int) string | // Get implements textutil.Table interface
func (r *Rows) Get(i, j int) string | {
if i == 0 {
if j >= len(r.Columns) {
return ""
}
return r.Columns[j]
}
if r.Values == nil {
return "NULL"
}
if i-1 >= len(r.Values) {
return "NULL"
}
if j >= len(r.Values[i-1]) {
return "NULL"
}
return fmt.Sprintf("%v", r.Values[i-1][j])
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | auth/credential_store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L31-L36 | go | train | // NewCredentialsStore returns a new instance of a CredentialStore. | func NewCredentialsStore() *CredentialsStore | // NewCredentialsStore returns a new instance of a CredentialStore.
func NewCredentialsStore() *CredentialsStore | {
return &CredentialsStore{
store: make(map[string]string),
perms: make(map[string]map[string]bool),
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | auth/credential_store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L39-L67 | go | train | // Load loads credential information from a reader. | func (c *CredentialsStore) Load(r io.Reader) error | // Load loads credential information from a reader.
func (c *CredentialsStore) Load(r io.Reader) error | {
dec := json.NewDecoder(r)
// Read open bracket
_, err := dec.Token()
if err != nil {
return err
}
var cred Credential
for dec.More() {
err := dec.Decode(&cred)
if err != nil {
return err
}
c.store[cred.Username] = cred.Password
c.perms[cred.Username] = make(map[string]bool, len(cred.Perms))
for _, p := range cred.Perms {
c.perms[cred.Username][p] = true
}
}
// Read closing bracket.
_, err = dec.Token()
if err != nil {
return err
}
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | auth/credential_store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L70-L77 | go | train | // Check returns true if the password is correct for the given username. | func (c *CredentialsStore) Check(username, password string) bool | // Check returns true if the password is correct for the given username.
func (c *CredentialsStore) Check(username, password string) bool | {
pw, ok := c.store[username]
if !ok {
return false
}
return password == pw ||
bcrypt.CompareHashAndPassword([]byte(pw), []byte(password)) == nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | auth/credential_store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L80-L86 | go | train | // CheckRequest returns true if b contains a valid username and password. | func (c *CredentialsStore) CheckRequest(b BasicAuther) bool | // CheckRequest returns true if b contains a valid username and password.
func (c *CredentialsStore) CheckRequest(b BasicAuther) bool | {
username, password, ok := b.BasicAuth()
if !ok || !c.Check(username, password) {
return false
}
return true
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | auth/credential_store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L90-L100 | go | train | // HasPerm returns true if username has the given perm. It does not
// perform any password checking. | func (c *CredentialsStore) HasPerm(username string, perm string) bool | // HasPerm returns true if username has the given perm. It does not
// perform any password checking.
func (c *CredentialsStore) HasPerm(username string, perm string) bool | {
m, ok := c.perms[username]
if !ok {
return false
}
if _, ok := m[perm]; !ok {
return false
}
return true
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | auth/credential_store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L104-L113 | go | train | // HasAnyPerm returns true if username has at least one of the given perms.
// It does not perform any password checking. | func (c *CredentialsStore) HasAnyPerm(username string, perm ...string) bool | // HasAnyPerm returns true if username has at least one of the given perms.
// It does not perform any password checking.
func (c *CredentialsStore) HasAnyPerm(username string, perm ...string) bool | {
return func(p []string) bool {
for i := range p {
if c.HasPerm(username, p[i]) {
return true
}
}
return false
}(perm)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | auth/credential_store.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L118-L124 | go | train | // HasPermRequest returns true if the username returned by b has the givem perm.
// It does not perform any password checking, but if there is no username
// in the request, it returns false. | func (c *CredentialsStore) HasPermRequest(b BasicAuther, perm string) bool | // HasPermRequest returns true if the username returned by b has the givem perm.
// It does not perform any password checking, but if there is no username
// in the request, it returns false.
func (c *CredentialsStore) HasPermRequest(b BasicAuther, perm string) bool | {
username, _, ok := b.BasicAuth()
if !ok {
return false
}
return c.HasPerm(username, perm)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L41-L54 | go | train | // NewConnection returns a connection to the database. | func NewConnection(c *sdb.Conn, s *Store, id uint64, it, tt time.Duration) *Connection | // NewConnection returns a connection to the database.
func NewConnection(c *sdb.Conn, s *Store, id uint64, it, tt time.Duration) *Connection | {
now := time.Now()
conn := Connection{
db: c,
store: s,
ID: id,
CreatedAt: now,
LastUsedAt: now,
IdleTimeout: it,
TxTimeout: tt,
logger: log.New(os.Stderr, connectionLogPrefix(id), log.LstdFlags),
}
return &conn
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L57-L63 | go | train | // Restore prepares a partially ready connection. | func (c *Connection) Restore(dbConn *sdb.Conn, s *Store) | // Restore prepares a partially ready connection.
func (c *Connection) Restore(dbConn *sdb.Conn, s *Store) | {
c.dbMu.Lock()
defer c.dbMu.Unlock()
c.db = dbConn
c.store = s
c.logger = log.New(os.Stderr, connectionLogPrefix(c.ID), log.LstdFlags)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L66-L70 | go | train | // SetLastUsedNow marks the connection as being used now. | func (c *Connection) SetLastUsedNow() | // SetLastUsedNow marks the connection as being used now.
func (c *Connection) SetLastUsedNow() | {
c.timeMu.Lock()
defer c.timeMu.Unlock()
c.LastUsedAt = time.Now()
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L78-L85 | go | train | // TransactionActive returns whether a transaction is active on the connection. | func (c *Connection) TransactionActive() bool | // TransactionActive returns whether a transaction is active on the connection.
func (c *Connection) TransactionActive() bool | {
c.dbMu.RLock()
defer c.dbMu.RUnlock()
if c.db == nil {
return false
}
return c.db.TransactionActive()
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L88-L95 | go | train | // Execute executes queries that return no rows, but do modify the database. | func (c *Connection) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) | // Execute executes queries that return no rows, but do modify the database.
func (c *Connection) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) | {
c.dbMu.RLock()
defer c.dbMu.RUnlock()
if c.db == nil {
return nil, ErrConnectionDoesNotExist
}
return c.store.execute(c, ex)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L99-L106 | go | train | // ExecuteOrAbort executes the requests, but aborts any active transaction
// on the underlying database in the case of any error. | func (c *Connection) ExecuteOrAbort(ex *ExecuteRequest) (resp *ExecuteResponse, retErr error) | // ExecuteOrAbort executes the requests, but aborts any active transaction
// on the underlying database in the case of any error.
func (c *Connection) ExecuteOrAbort(ex *ExecuteRequest) (resp *ExecuteResponse, retErr error) | {
c.dbMu.RLock()
defer c.dbMu.RUnlock()
if c.db == nil {
return nil, ErrConnectionDoesNotExist
}
return c.store.executeOrAbort(c, ex)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L109-L116 | go | train | // Query executes queries that return rows, and do not modify the database. | func (c *Connection) Query(qr *QueryRequest) (*QueryResponse, error) | // Query executes queries that return rows, and do not modify the database.
func (c *Connection) Query(qr *QueryRequest) (*QueryResponse, error) | {
c.dbMu.RLock()
defer c.dbMu.RUnlock()
if c.db == nil {
return nil, ErrConnectionDoesNotExist
}
return c.store.query(c, qr)
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L122-L130 | go | train | // AbortTransaction aborts -- rolls back -- any active transaction. Calling code
// should know exactly what it is doing if it decides to call this function. It
// can be used to clean up any dangling state that may result from certain
// error scenarios. | func (c *Connection) AbortTransaction() error | // AbortTransaction aborts -- rolls back -- any active transaction. Calling code
// should know exactly what it is doing if it decides to call this function. It
// can be used to clean up any dangling state that may result from certain
// error scenarios.
func (c *Connection) AbortTransaction() error | {
c.dbMu.RLock()
defer c.dbMu.RUnlock()
if c.db == nil {
return ErrConnectionDoesNotExist
}
_, err := c.store.execute(c, &ExecuteRequest{[]string{"ROLLBACK"}, false, false})
return err
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L133-L151 | go | train | // Close closes the connection via consensus. | func (c *Connection) Close() error | // Close closes the connection via consensus.
func (c *Connection) Close() error | {
c.dbMu.Lock()
defer c.dbMu.Unlock()
if c.store != nil {
if err := c.store.disconnect(c); err != nil {
return err
}
}
if c.db == nil {
return nil
}
if err := c.db.Close(); err != nil {
return err
}
c.db = nil
return nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L154-L178 | go | train | // Stats returns the status of the connection. | func (c *Connection) Stats() (interface{}, error) | // Stats returns the status of the connection.
func (c *Connection) Stats() (interface{}, error) | {
c.dbMu.RLock()
defer c.dbMu.RUnlock()
c.timeMu.Lock()
defer c.timeMu.Unlock()
c.txStateMu.Lock()
defer c.txStateMu.Unlock()
fkEnabled, err := c.db.FKConstraints()
if err != nil {
return nil, err
}
m := make(map[string]interface{})
m["last_used_at"] = c.LastUsedAt
m["created_at"] = c.CreatedAt
m["idle_timeout"] = c.IdleTimeout.String()
m["tx_timeout"] = c.TxTimeout.String()
m["id"] = c.ID
m["fk_constraints"] = enabledFromBool(fkEnabled)
if !c.TxStartedAt.IsZero() {
m["tx_started_at"] = c.TxStartedAt.String()
}
return m, nil
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L181-L185 | go | train | // IdleTimedOut returns if the connection has not been active in the idle time. | func (c *Connection) IdleTimedOut() bool | // IdleTimedOut returns if the connection has not been active in the idle time.
func (c *Connection) IdleTimedOut() bool | {
c.timeMu.Lock()
defer c.timeMu.Unlock()
return time.Since(c.LastUsedAt) > c.IdleTimeout && c.IdleTimeout != 0
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L189-L196 | go | train | // TxTimedOut returns if the transaction has been open, without activity in
// transaction-idle time. | func (c *Connection) TxTimedOut() bool | // TxTimedOut returns if the transaction has been open, without activity in
// transaction-idle time.
func (c *Connection) TxTimedOut() bool | {
c.timeMu.Lock()
defer c.timeMu.Unlock()
c.txStateMu.Lock()
defer c.txStateMu.Unlock()
lau := c.LastUsedAt
return !c.TxStartedAt.IsZero() && time.Since(lau) > c.TxTimeout && c.TxTimeout != 0
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L211-L216 | go | train | // NewTxStateChange returns an initialized TxStateChange | func NewTxStateChange(c *Connection) *TxStateChange | // NewTxStateChange returns an initialized TxStateChange
func NewTxStateChange(c *Connection) *TxStateChange | {
return &TxStateChange{
c: c,
tx: c.TransactionActive(),
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/connection.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L221-L235 | go | train | // CheckAndSet sets whether a transaction has begun or ended on the
// connection since the TxStateChange was created. Once CheckAndSet
// has been called, this function will panic if called a second time. | func (t *TxStateChange) CheckAndSet() | // CheckAndSet sets whether a transaction has begun or ended on the
// connection since the TxStateChange was created. Once CheckAndSet
// has been called, this function will panic if called a second time.
func (t *TxStateChange) CheckAndSet() | {
t.c.txStateMu.Lock()
defer t.c.txStateMu.Unlock()
defer func() { t.done = true }()
if t.done {
panic("CheckAndSet should only be called once")
}
if !t.tx && t.c.TransactionActive() && t.c.TxStartedAt.IsZero() {
t.c.TxStartedAt = time.Now()
} else if t.tx && !t.c.TransactionActive() && !t.c.TxStartedAt.IsZero() {
t.c.TxStartedAt = time.Time{}
}
} |
rqlite/rqlite | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | store/db_config.go | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/db_config.go#L10-L12 | go | train | // NewDBConfig returns a new DB config instance. | func NewDBConfig(dsn string, memory bool) *DBConfig | // NewDBConfig returns a new DB config instance.
func NewDBConfig(dsn string, memory bool) *DBConfig | {
return &DBConfig{DSN: dsn, Memory: memory}
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | debug.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/debug.go#L163-L174 | go | train | // SetDebugHook sets the debugging hook function.
//
// f is the hook function. mask specifies on which events the hook will be
// called: it is formed by a bitwise or of the constants MaskCall, MaskReturn,
// MaskLine, and MaskCount. The count argument is only meaningful when the
// mask includes MaskCount. For each event, the hook is called as explained
// below:
//
// Call hook is called when the interpreter calls a function. The hook is
// called just after Lua enters the new function, before the function gets
// its arguments.
//
// Return hook is called when the interpreter returns from a function. The
// hook is called just before Lua leaves the function. There is no standard
// way to access the values to be returned by the function.
//
// Line hook is called when the interpreter is about to start the execution
// of a new line of code, or when it jumps back in the code (even to the same
// line). (This event only happens while Lua is executing a Lua function.)
//
// Count hook is called after the interpreter executes every count
// instructions. (This event only happens while Lua is executing a Lua
// function.)
//
// A hook is disabled by setting mask to zero. | func SetDebugHook(l *State, f Hook, mask byte, count int) | // SetDebugHook sets the debugging hook function.
//
// f is the hook function. mask specifies on which events the hook will be
// called: it is formed by a bitwise or of the constants MaskCall, MaskReturn,
// MaskLine, and MaskCount. The count argument is only meaningful when the
// mask includes MaskCount. For each event, the hook is called as explained
// below:
//
// Call hook is called when the interpreter calls a function. The hook is
// called just after Lua enters the new function, before the function gets
// its arguments.
//
// Return hook is called when the interpreter returns from a function. The
// hook is called just before Lua leaves the function. There is no standard
// way to access the values to be returned by the function.
//
// Line hook is called when the interpreter is about to start the execution
// of a new line of code, or when it jumps back in the code (even to the same
// line). (This event only happens while Lua is executing a Lua function.)
//
// Count hook is called after the interpreter executes every count
// instructions. (This event only happens while Lua is executing a Lua
// function.)
//
// A hook is disabled by setting mask to zero.
func SetDebugHook(l *State, f Hook, mask byte, count int) | {
if f == nil || mask == 0 {
f, mask = nil, 0
}
if ci := l.callInfo; ci.isLua() {
l.oldPC = ci.savedPC
}
l.hooker, l.baseHookCount = f, count
l.resetHookCount()
l.hookMask = mask
l.internalHook = false
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | debug.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/debug.go#L193-L204 | go | train | // Stack gets information about the interpreter runtime stack.
//
// It returns a Frame identifying the activation record of the
// function executing at a given level. Level 0 is the current running
// function, whereas level n+1 is the function that has called level n (except
// for tail calls, which do not count on the stack). When there are no errors,
// Stack returns true; when called with a level greater than the stack depth,
// it returns false. | func Stack(l *State, level int) (f Frame, ok bool) | // Stack gets information about the interpreter runtime stack.
//
// It returns a Frame identifying the activation record of the
// function executing at a given level. Level 0 is the current running
// function, whereas level n+1 is the function that has called level n (except
// for tail calls, which do not count on the stack). When there are no errors,
// Stack returns true; when called with a level greater than the stack depth,
// it returns false.
func Stack(l *State, level int) (f Frame, ok bool) | {
if level < 0 {
return // invalid (negative) level
}
callInfo := l.callInfo
for ; level > 0 && callInfo != &l.baseCallInfo; level, callInfo = level-1, callInfo.previous {
}
if level == 0 && callInfo != &l.baseCallInfo { // level found?
f, ok = callInfo, true
}
return
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | debug.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/debug.go#L310-L388 | go | train | // Info gets information about a specific function or function invocation.
//
// To get information about a function invocation, the parameter where must
// be a valid activation record that was filled by a previous call to Stack
// or given as an argument to a hook (see Hook).
//
// To get information about a function you push it onto the stack and start
// the what string with the character '>'. (In that case, Info pops the
// function from the top of the stack.) For instance, to know in which line
// a function f was defined, you can write the following code:
// l.Global("f") // Get global 'f'.
// d, _ := lua.Info(l, ">S", nil)
// fmt.Printf("%d\n", d.LineDefined)
//
// Each character in the string what selects some fields of the Debug struct
// to be filled or a value to be pushed on the stack:
// 'n': fills in the field Name and NameKind
// 'S': fills in the fields Source, ShortSource, LineDefined, LastLineDefined, and What
// 'l': fills in the field CurrentLine
// 't': fills in the field IsTailCall
// 'u': fills in the fields UpValueCount, ParameterCount, and IsVarArg
// 'f': pushes onto the stack the function that is running at the given level
// 'L': pushes onto the stack a table whose indices are the numbers of the lines that are valid on the function
// (A valid line is a line with some associated code, that is, a line where you
// can put a break point. Non-valid lines include empty lines and comments.)
//
// This function returns false on error (for instance, an invalid option in what). | func Info(l *State, what string, where Frame) (d Debug, ok bool) | // Info gets information about a specific function or function invocation.
//
// To get information about a function invocation, the parameter where must
// be a valid activation record that was filled by a previous call to Stack
// or given as an argument to a hook (see Hook).
//
// To get information about a function you push it onto the stack and start
// the what string with the character '>'. (In that case, Info pops the
// function from the top of the stack.) For instance, to know in which line
// a function f was defined, you can write the following code:
// l.Global("f") // Get global 'f'.
// d, _ := lua.Info(l, ">S", nil)
// fmt.Printf("%d\n", d.LineDefined)
//
// Each character in the string what selects some fields of the Debug struct
// to be filled or a value to be pushed on the stack:
// 'n': fills in the field Name and NameKind
// 'S': fills in the fields Source, ShortSource, LineDefined, LastLineDefined, and What
// 'l': fills in the field CurrentLine
// 't': fills in the field IsTailCall
// 'u': fills in the fields UpValueCount, ParameterCount, and IsVarArg
// 'f': pushes onto the stack the function that is running at the given level
// 'L': pushes onto the stack a table whose indices are the numbers of the lines that are valid on the function
// (A valid line is a line with some associated code, that is, a line where you
// can put a break point. Non-valid lines include empty lines and comments.)
//
// This function returns false on error (for instance, an invalid option in what).
func Info(l *State, what string, where Frame) (d Debug, ok bool) | {
var f closure
var fun value
if what[0] == '>' {
where = nil
fun = l.stack[l.top-1]
switch fun := fun.(type) {
case closure:
f = fun
case *goFunction:
default:
panic("function expected")
}
what = what[1:] // skip the '>'
l.top-- // pop function
} else {
fun = l.stack[where.function]
switch fun := fun.(type) {
case closure:
f = fun
case *goFunction:
default:
l.assert(false)
}
}
ok, hasL, hasF := true, false, false
d.callInfo = where
ci := d.callInfo
for _, r := range what {
switch r {
case 'S':
d = functionInfo(d, f)
case 'l':
d.CurrentLine = -1
if where != nil && ci.isLua() {
d.CurrentLine = l.currentLine(where)
}
case 'u':
if f == nil {
d.UpValueCount = 0
} else {
d.UpValueCount = f.upValueCount()
}
if lf, ok := f.(*luaClosure); !ok {
d.IsVarArg = true
d.ParameterCount = 0
} else {
d.IsVarArg = lf.prototype.isVarArg
d.ParameterCount = lf.prototype.parameterCount
}
case 't':
d.IsTailCall = where != nil && ci.isCallStatus(callStatusTail)
case 'n':
// calling function is a known Lua function?
if where != nil && !ci.isCallStatus(callStatusTail) && where.previous.isLua() {
d.Name, d.NameKind = l.functionName(where.previous)
} else {
d.NameKind = ""
}
if d.NameKind == "" {
d.NameKind = "" // not found
d.Name = ""
}
case 'L':
hasL = true
case 'f':
hasF = true
default:
ok = false
}
}
if hasF {
l.apiPush(f)
}
if hasL {
l.collectValidLines(f)
}
return d, ok
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | string.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/string.go#L235-L246 | go | train | // StringOpen opens the string library. Usually passed to Require. | func StringOpen(l *State) int | // StringOpen opens the string library. Usually passed to Require.
func StringOpen(l *State) int | {
NewLibrary(l, stringLibrary)
l.CreateTable(0, 1)
l.PushString("")
l.PushValue(-2)
l.SetMetaTable(-2)
l.Pop(1)
l.PushValue(-2)
l.SetField(-2, "__index")
l.Pop(1)
return 1
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L323-L328 | go | train | // Context is called by a continuation function to retrieve the status of the
// thread and context information. When called in the origin function, it
// will always return (0, false, nil). When called inside a continuation function,
// it will return (ctx, shouldYield, err), where ctx is the value that was
// passed to the callee together with the continuation function.
//
// http://www.lua.org/manual/5.2/manual.html#lua_getctx | func (l *State) Context() (int, bool, error) | // Context is called by a continuation function to retrieve the status of the
// thread and context information. When called in the origin function, it
// will always return (0, false, nil). When called inside a continuation function,
// it will return (ctx, shouldYield, err), where ctx is the value that was
// passed to the callee together with the continuation function.
//
// http://www.lua.org/manual/5.2/manual.html#lua_getctx
func (l *State) Context() (int, bool, error) | {
if l.callInfo.isCallStatus(callStatusYielded) {
return l.callInfo.context, l.callInfo.shouldYield, l.callInfo.error
}
return 0, false, nil
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L334-L352 | go | train | // CallWithContinuation is exactly like Call, but allows the called function to
// yield.
//
// http://www.lua.org/manual/5.2/manual.html#lua_callk | func (l *State) CallWithContinuation(argCount, resultCount, context int, continuation Function) | // CallWithContinuation is exactly like Call, but allows the called function to
// yield.
//
// http://www.lua.org/manual/5.2/manual.html#lua_callk
func (l *State) CallWithContinuation(argCount, resultCount, context int, continuation Function) | {
if apiCheck && continuation != nil && l.callInfo.isLua() {
panic("cannot use continuations inside hooks")
}
l.checkElementCount(argCount + 1)
if apiCheck && l.shouldYield {
panic("cannot do calls on non-normal thread")
}
l.checkResults(argCount, resultCount)
f := l.top - (argCount + 1)
if continuation != nil && l.nonYieldableCallCount == 0 { // need to prepare continuation?
l.callInfo.continuation = continuation
l.callInfo.context = context
l.call(f, resultCount, true) // just do the call
} else { // no continuation or not yieldable
l.call(f, resultCount, false) // just do the call
}
l.adjustResults(resultCount)
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L381-L383 | go | train | // ProtectedCall calls a function in protected mode. Both argCount and
// resultCount have the same meaning as in Call. If there are no errors
// during the call, ProtectedCall behaves exactly like Call.
//
// However, if there is any error, ProtectedCall catches it, pushes a single
// value on the stack (the error message), and returns an error. Like Call,
// ProtectedCall always removes the function and its arguments from the stack.
//
// If errorFunction is 0, then the error message returned on the stack is
// exactly the original error message. Otherwise, errorFunction is the stack
// index of an error handler (in the Lua C, message handler). This cannot be
// a pseudo-index in the current implementation. In case of runtime errors,
// this function will be called with the error message and its return value
// will be the message returned on the stack by ProtectedCall.
//
// Typically, the error handler is used to add more debug information to the
// error message, such as a stack traceback. Such information cannot be
// gathered after the return of ProtectedCall, since by then, the stack has
// unwound.
//
// The possible errors are the following:
//
// RuntimeError a runtime error
// MemoryError allocating memory, the error handler is not called
// ErrorError running the error handler
//
// http://www.lua.org/manual/5.2/manual.html#lua_pcall | func (l *State) ProtectedCall(argCount, resultCount, errorFunction int) error | // ProtectedCall calls a function in protected mode. Both argCount and
// resultCount have the same meaning as in Call. If there are no errors
// during the call, ProtectedCall behaves exactly like Call.
//
// However, if there is any error, ProtectedCall catches it, pushes a single
// value on the stack (the error message), and returns an error. Like Call,
// ProtectedCall always removes the function and its arguments from the stack.
//
// If errorFunction is 0, then the error message returned on the stack is
// exactly the original error message. Otherwise, errorFunction is the stack
// index of an error handler (in the Lua C, message handler). This cannot be
// a pseudo-index in the current implementation. In case of runtime errors,
// this function will be called with the error message and its return value
// will be the message returned on the stack by ProtectedCall.
//
// Typically, the error handler is used to add more debug information to the
// error message, such as a stack traceback. Such information cannot be
// gathered after the return of ProtectedCall, since by then, the stack has
// unwound.
//
// The possible errors are the following:
//
// RuntimeError a runtime error
// MemoryError allocating memory, the error handler is not called
// ErrorError running the error handler
//
// http://www.lua.org/manual/5.2/manual.html#lua_pcall
func (l *State) ProtectedCall(argCount, resultCount, errorFunction int) error | {
return l.ProtectedCallWithContinuation(argCount, resultCount, errorFunction, 0, nil)
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L389-L418 | go | train | // ProtectedCallWithContinuation behaves exactly like ProtectedCall, but
// allows the called function to yield.
//
// http://www.lua.org/manual/5.2/manual.html#lua_pcallk | func (l *State) ProtectedCallWithContinuation(argCount, resultCount, errorFunction, context int, continuation Function) (err error) | // ProtectedCallWithContinuation behaves exactly like ProtectedCall, but
// allows the called function to yield.
//
// http://www.lua.org/manual/5.2/manual.html#lua_pcallk
func (l *State) ProtectedCallWithContinuation(argCount, resultCount, errorFunction, context int, continuation Function) (err error) | {
if apiCheck && continuation != nil && l.callInfo.isLua() {
panic("cannot use continuations inside hooks")
}
l.checkElementCount(argCount + 1)
if apiCheck && l.shouldYield {
panic("cannot do calls on non-normal thread")
}
l.checkResults(argCount, resultCount)
if errorFunction != 0 {
apiCheckStackIndex(errorFunction, l.indexToValue(errorFunction))
errorFunction = l.AbsIndex(errorFunction)
}
f := l.top - (argCount + 1)
if continuation == nil || l.nonYieldableCallCount > 0 {
err = l.protectedCall(func() { l.call(f, resultCount, false) }, f, errorFunction)
} else {
c := l.callInfo
c.continuation, c.context, c.extra, c.oldAllowHook, c.oldErrorFunction = continuation, context, f, l.allowHook, l.errorFunction
l.errorFunction = errorFunction
l.callInfo.setCallStatus(callStatusYieldableProtected)
l.call(f, resultCount, true)
l.callInfo.clearCallStatus(callStatusYieldableProtected)
l.errorFunction = c.oldErrorFunction
}
l.adjustResults(resultCount)
return
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L425-L438 | go | train | // Load loads a Lua chunk, without running it. If there are no errors, it
// pushes the compiled chunk as a Lua function on top of the stack.
// Otherwise, it pushes an error message.
//
// http://www.lua.org/manual/5.2/manual.html#lua_load | func (l *State) Load(r io.Reader, chunkName string, mode string) error | // Load loads a Lua chunk, without running it. If there are no errors, it
// pushes the compiled chunk as a Lua function on top of the stack.
// Otherwise, it pushes an error message.
//
// http://www.lua.org/manual/5.2/manual.html#lua_load
func (l *State) Load(r io.Reader, chunkName string, mode string) error | {
if chunkName == "" {
chunkName = "?"
}
if err := protectedParser(l, r, chunkName, mode); err != nil {
return err
}
if f := l.stack[l.top-1].(*luaClosure); f.upValueCount() == 1 {
f.setUpValue(0, l.global.registry.atInt(RegistryIndexGlobals))
}
return nil
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L445-L451 | go | train | // Dump dumps a function as a binary chunk. It receives a Lua function on
// the top of the stack and produces a binary chunk that, if loaded again,
// results in a function equivalent to the one dumped.
//
// http://www.lua.org/manual/5.3/manual.html#lua_dump | func (l *State) Dump(w io.Writer) error | // Dump dumps a function as a binary chunk. It receives a Lua function on
// the top of the stack and produces a binary chunk that, if loaded again,
// results in a function equivalent to the one dumped.
//
// http://www.lua.org/manual/5.3/manual.html#lua_dump
func (l *State) Dump(w io.Writer) error | {
l.checkElementCount(1)
if f, ok := l.stack[l.top-1].(*luaClosure); ok {
return l.dump(f.prototype, w)
}
panic("closure expected")
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L456-L466 | go | train | // NewState creates a new thread running in a new, independent state.
//
// http://www.lua.org/manual/5.2/manual.html#lua_newstate | func NewState() *State | // NewState creates a new thread running in a new, independent state.
//
// http://www.lua.org/manual/5.2/manual.html#lua_newstate
func NewState() *State | {
v := float64(VersionNumber)
l := &State{allowHook: true, error: nil, nonYieldableCallCount: 1}
g := &globalState{mainThread: l, registry: newTable(), version: &v, memoryErrorMessage: "not enough memory"}
l.global = g
l.initializeStack()
g.registry.putAtInt(RegistryIndexMainThread, l)
g.registry.putAtInt(RegistryIndexGlobals, newTable())
copy(g.tagMethodNames[:], eventNames)
return l
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L481-L487 | go | train | // SetField does the equivalent of table[key]=v where table is the value at
// index and v is the value on top of the stack.
//
// This function pops the value from the stack. As in Lua, this function may
// trigger a metamethod for the __newindex event.
//
// http://www.lua.org/manual/5.2/manual.html#lua_setfield | func (l *State) SetField(index int, key string) | // SetField does the equivalent of table[key]=v where table is the value at
// index and v is the value on top of the stack.
//
// This function pops the value from the stack. As in Lua, this function may
// trigger a metamethod for the __newindex event.
//
// http://www.lua.org/manual/5.2/manual.html#lua_setfield
func (l *State) SetField(index int, key string) | {
l.checkElementCount(1)
t := l.indexToValue(index)
l.push(key)
l.setTableAt(t, key, l.stack[l.top-2])
l.top -= 2
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L541-L546 | go | train | // AbsIndex converts the acceptable index index to an absolute index (that
// is, one that does not depend on the stack top).
//
// http://www.lua.org/manual/5.2/manual.html#lua_absindex | func (l *State) AbsIndex(index int) int | // AbsIndex converts the acceptable index index to an absolute index (that
// is, one that does not depend on the stack top).
//
// http://www.lua.org/manual/5.2/manual.html#lua_absindex
func (l *State) AbsIndex(index int) int | {
if index > 0 || isPseudoIndex(index) {
return index
}
return l.top - l.callInfo.function + index
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L556-L572 | go | train | // SetTop accepts any index, or 0, and sets the stack top to index. If the
// new top is larger than the old one, then the new elements are filled with
// nil. If index is 0, then all stack elements are removed.
//
// If index is negative, the stack will be decremented by that much. If
// the decrement is larger than the stack, SetTop will panic().
//
// http://www.lua.org/manual/5.2/manual.html#lua_settop | func (l *State) SetTop(index int) | // SetTop accepts any index, or 0, and sets the stack top to index. If the
// new top is larger than the old one, then the new elements are filled with
// nil. If index is 0, then all stack elements are removed.
//
// If index is negative, the stack will be decremented by that much. If
// the decrement is larger than the stack, SetTop will panic().
//
// http://www.lua.org/manual/5.2/manual.html#lua_settop
func (l *State) SetTop(index int) | {
f := l.callInfo.function
if index >= 0 {
if apiCheck && index > l.stackLast-(f+1) {
panic("new top too large")
}
i := l.top
for l.top = f + 1 + index; i < l.top; i++ {
l.stack[i] = nil
}
} else {
if apiCheck && -(index+1) > l.top-(f+1) {
panic("invalid new top")
}
l.top += index + 1 // 'subtract' index (index is negative)
}
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L579-L584 | go | train | // Remove the element at the given valid index, shifting down the elements
// above index to fill the gap. This function cannot be called with a
// pseudo-index, because a pseudo-index is not an actual stack position.
//
// http://www.lua.org/manual/5.2/manual.html#lua_remove | func (l *State) Remove(index int) | // Remove the element at the given valid index, shifting down the elements
// above index to fill the gap. This function cannot be called with a
// pseudo-index, because a pseudo-index is not an actual stack position.
//
// http://www.lua.org/manual/5.2/manual.html#lua_remove
func (l *State) Remove(index int) | {
apiCheckStackIndex(index, l.indexToValue(index))
i := l.callInfo.function + l.AbsIndex(index)
copy(l.stack[i:l.top-1], l.stack[i+1:l.top])
l.top--
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L605-L609 | go | train | // Replace moves the top element into the given valid index without shifting
// any element (therefore replacing the value at the given index), and then
// pops the top element.
//
// http://www.lua.org/manual/5.2/manual.html#lua_replace | func (l *State) Replace(index int) | // Replace moves the top element into the given valid index without shifting
// any element (therefore replacing the value at the given index), and then
// pops the top element.
//
// http://www.lua.org/manual/5.2/manual.html#lua_replace
func (l *State) Replace(index int) | {
l.checkElementCount(1)
l.move(index, l.stack[l.top-1])
l.top--
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L615-L625 | go | train | // CheckStack ensures that there are at least size free stack slots in the
// stack. This call will not panic(), unlike the other Check*() functions.
//
// http://www.lua.org/manual/5.2/manual.html#lua_checkstack | func (l *State) CheckStack(size int) bool | // CheckStack ensures that there are at least size free stack slots in the
// stack. This call will not panic(), unlike the other Check*() functions.
//
// http://www.lua.org/manual/5.2/manual.html#lua_checkstack
func (l *State) CheckStack(size int) bool | {
callInfo := l.callInfo
ok := l.stackLast-l.top > size
if !ok && l.top+extraStack <= maxStack-size {
ok = l.protect(func() { l.growStack(size) }) == nil
}
if ok && callInfo.top < l.top+size {
callInfo.setTop(l.top + size)
}
return ok
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L628-L631 | go | train | // AtPanic sets a new panic function and returns the old one. | func AtPanic(l *State, panicFunction Function) Function | // AtPanic sets a new panic function and returns the old one.
func AtPanic(l *State, panicFunction Function) Function | {
panicFunction, l.global.panicFunction = l.global.panicFunction, panicFunction
return panicFunction
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L665-L667 | go | train | // TypeOf returns the type of the value at index, or TypeNone for a
// non-valid (but acceptable) index.
//
// http://www.lua.org/manual/5.2/manual.html#lua_type | func (l *State) TypeOf(index int) Type | // TypeOf returns the type of the value at index, or TypeNone for a
// non-valid (but acceptable) index.
//
// http://www.lua.org/manual/5.2/manual.html#lua_type
func (l *State) TypeOf(index int) Type | {
return l.valueToType(l.indexToValue(index))
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L672-L678 | go | train | // IsGoFunction verifies that the value at index is a Go function.
//
// http://www.lua.org/manual/5.2/manual.html#lua_iscfunction | func (l *State) IsGoFunction(index int) bool | // IsGoFunction verifies that the value at index is a Go function.
//
// http://www.lua.org/manual/5.2/manual.html#lua_iscfunction
func (l *State) IsGoFunction(index int) bool | {
if _, ok := l.indexToValue(index).(*goFunction); ok {
return true
}
_, ok := l.indexToValue(index).(*goClosure)
return ok
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L683-L686 | go | train | // IsNumber verifies that the value at index is a number.
//
// http://www.lua.org/manual/5.2/manual.html#lua_isnumber | func (l *State) IsNumber(index int) bool | // IsNumber verifies that the value at index is a number.
//
// http://www.lua.org/manual/5.2/manual.html#lua_isnumber
func (l *State) IsNumber(index int) bool | {
_, ok := l.toNumber(l.indexToValue(index))
return ok
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L692-L698 | go | train | // IsString verifies that the value at index is a string, or a number (which
// is always convertible to a string).
//
// http://www.lua.org/manual/5.2/manual.html#lua_isstring | func (l *State) IsString(index int) bool | // IsString verifies that the value at index is a string, or a number (which
// is always convertible to a string).
//
// http://www.lua.org/manual/5.2/manual.html#lua_isstring
func (l *State) IsString(index int) bool | {
if _, ok := l.indexToValue(index).(string); ok {
return true
}
_, ok := l.indexToValue(index).(float64)
return ok
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L703-L706 | go | train | // IsUserData verifies that the value at index is a userdata.
//
// http://www.lua.org/manual/5.2/manual.html#lua_isuserdata | func (l *State) IsUserData(index int) bool | // IsUserData verifies that the value at index is a userdata.
//
// http://www.lua.org/manual/5.2/manual.html#lua_isuserdata
func (l *State) IsUserData(index int) bool | {
_, ok := l.indexToValue(index).(*userData)
return ok
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L715-L729 | go | train | // Arith performs an arithmetic operation over the two values (or one, in
// case of negation) at the top of the stack, with the value at the top being
// the second operand, ops these values and pushes the result of the operation.
// The function follows the semantics of the corresponding Lua operator
// (that is, it may call metamethods).
//
// http://www.lua.org/manual/5.2/manual.html#lua_arith | func (l *State) Arith(op Operator) | // Arith performs an arithmetic operation over the two values (or one, in
// case of negation) at the top of the stack, with the value at the top being
// the second operand, ops these values and pushes the result of the operation.
// The function follows the semantics of the corresponding Lua operator
// (that is, it may call metamethods).
//
// http://www.lua.org/manual/5.2/manual.html#lua_arith
func (l *State) Arith(op Operator) | {
if op != OpUnaryMinus {
l.checkElementCount(2)
} else {
l.checkElementCount(1)
l.push(l.stack[l.top-1])
}
o1, o2 := l.stack[l.top-2], l.stack[l.top-1]
if n1, n2, ok := pairAsNumbers(o1, o2); ok {
l.stack[l.top-2] = arith(op, n1, n2)
} else {
l.stack[l.top-2] = l.arith(o1, o2, tm(op-OpAdd)+tmAdd)
}
l.top--
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L735-L740 | go | train | // RawEqual verifies that the values at index1 and index2 are primitively
// equal (that is, without calling their metamethods).
//
// http://www.lua.org/manual/5.2/manual.html#lua_rawequal | func (l *State) RawEqual(index1, index2 int) bool | // RawEqual verifies that the values at index1 and index2 are primitively
// equal (that is, without calling their metamethods).
//
// http://www.lua.org/manual/5.2/manual.html#lua_rawequal
func (l *State) RawEqual(index1, index2 int) bool | {
if o1, o2 := l.indexToValue(index1), l.indexToValue(index2); o1 != nil && o2 != nil {
return o1 == o2
}
return false
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L745-L759 | go | train | // Compare compares two values.
//
// http://www.lua.org/manual/5.2/manual.html#lua_compare | func (l *State) Compare(index1, index2 int, op ComparisonOperator) bool | // Compare compares two values.
//
// http://www.lua.org/manual/5.2/manual.html#lua_compare
func (l *State) Compare(index1, index2 int, op ComparisonOperator) bool | {
if o1, o2 := l.indexToValue(index1), l.indexToValue(index2); o1 != nil && o2 != nil {
switch op {
case OpEq:
return l.equalObjects(o1, o2)
case OpLT:
return l.lessThan(o1, o2)
case OpLE:
return l.lessOrEqual(o1, o2)
default:
panic("invalid option")
}
}
return false
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L769-L774 | go | train | // ToInteger converts the Lua value at index into a signed integer. The Lua
// value must be a number, or a string convertible to a number.
//
// If the number is not an integer, it is truncated in some non-specified way.
//
// If the operation failed, the second return value will be false.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tointegerx | func (l *State) ToInteger(index int) (int, bool) | // ToInteger converts the Lua value at index into a signed integer. The Lua
// value must be a number, or a string convertible to a number.
//
// If the number is not an integer, it is truncated in some non-specified way.
//
// If the operation failed, the second return value will be false.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tointegerx
func (l *State) ToInteger(index int) (int, bool) | {
if n, ok := l.toNumber(l.indexToValue(index)); ok {
return int(n), true
}
return 0, false
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L787-L793 | go | train | // ToUnsigned converts the Lua value at index to a Go uint. The Lua value
// must be a number or a string convertible to a number.
//
// If the number is not an unsigned integer, it is truncated in some
// non-specified way. If the number is outside the range of uint, it is
// normalized to the remainder of its division by one more than the maximum
// representable value.
//
// If the operation failed, the second return value will be false.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tounsignedx | func (l *State) ToUnsigned(index int) (uint, bool) | // ToUnsigned converts the Lua value at index to a Go uint. The Lua value
// must be a number or a string convertible to a number.
//
// If the number is not an unsigned integer, it is truncated in some
// non-specified way. If the number is outside the range of uint, it is
// normalized to the remainder of its division by one more than the maximum
// representable value.
//
// If the operation failed, the second return value will be false.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tounsignedx
func (l *State) ToUnsigned(index int) (uint, bool) | {
if n, ok := l.toNumber(l.indexToValue(index)); ok {
const supUnsigned = float64(^uint32(0)) + 1
return uint(n - math.Floor(n/supUnsigned)*supUnsigned), true
}
return 0, false
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L800-L805 | go | train | // ToString converts the Lua value at index to a Go string. The Lua value
// must also be a string or a number; otherwise the function returns
// false for its second return value.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tolstring | func (l *State) ToString(index int) (s string, ok bool) | // ToString converts the Lua value at index to a Go string. The Lua value
// must also be a string or a number; otherwise the function returns
// false for its second return value.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tolstring
func (l *State) ToString(index int) (s string, ok bool) | {
if s, ok = toString(l.indexToValue(index)); ok { // Bug compatibility: replace a number with its string representation.
l.setIndexToValue(index, s)
}
return
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L813-L823 | go | train | // RawLength returns the length of the value at index. For strings, this is
// the length. For tables, this is the result of the # operator with no
// metamethods. For userdata, this is the size of the block of memory
// allocated for the userdata (not implemented yet). For other values, it is 0.
//
// http://www.lua.org/manual/5.2/manual.html#lua_rawlen | func (l *State) RawLength(index int) int | // RawLength returns the length of the value at index. For strings, this is
// the length. For tables, this is the result of the # operator with no
// metamethods. For userdata, this is the size of the block of memory
// allocated for the userdata (not implemented yet). For other values, it is 0.
//
// http://www.lua.org/manual/5.2/manual.html#lua_rawlen
func (l *State) RawLength(index int) int | {
switch v := l.indexToValue(index).(type) {
case string:
return len(v)
// case *userData:
// return reflect.Sizeof(v.data)
case *table:
return v.length()
}
return 0
} |
Shopify/go-lua | 48449c60c0a91cdc83cf554aa0931380393b9b02 | lua.go | https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L829-L837 | go | train | // ToGoFunction converts a value at index into a Go function. That value
// must be a Go function, otherwise it returns nil.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tocfunction | func (l *State) ToGoFunction(index int) Function | // ToGoFunction converts a value at index into a Go function. That value
// must be a Go function, otherwise it returns nil.
//
// http://www.lua.org/manual/5.2/manual.html#lua_tocfunction
func (l *State) ToGoFunction(index int) Function | {
switch v := l.indexToValue(index).(type) {
case *goFunction:
return v.Function
case *goClosure:
return v.function
}
return nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.