hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 1, "code_window": [ " const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;\n", " const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);\n", " const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);\n", " const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);\n", " const loading = queryTransactions.some(qt => !qt.done);\n", "\n", " return (\n", " <div className={exploreClass} ref={this.getRef}>\n", " <div className=\"navbar\">\n", " {position === 'left' ? (\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const queryEmpty = queryTransactions.some(qt => qt.resultType === 'Logs' && qt.done && qt.result.length === 0);\n" ], "file_path": "public/app/features/explore/Explore.tsx", "type": "add", "edit_start_line_idx": 839 }
package pq import ( "bufio" "crypto/md5" "database/sql" "database/sql/driver" "encoding/binary" "errors" "fmt" "io" "net" "os" "os/user" "path" "path/filepath" "strconv" "strings" "time" "unicode" "github.com/lib/pq/oid" ) // Common error types var ( ErrNotSupported = errors.New("pq: Unsupported command") ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction") ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server") ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less") ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly") errUnexpectedReady = errors.New("unexpected ReadyForQuery") errNoRowsAffected = errors.New("no RowsAffected available after the empty statement") errNoLastInsertID = errors.New("no LastInsertId available after the empty statement") ) // Driver is the Postgres database driver. type Driver struct{} // Open opens a new connection to the database. name is a connection string. // Most users should only use it through database/sql package from the standard // library. func (d *Driver) Open(name string) (driver.Conn, error) { return Open(name) } func init() { sql.Register("postgres", &Driver{}) } type parameterStatus struct { // server version in the same format as server_version_num, or 0 if // unavailable serverVersion int // the current location based on the TimeZone value of the session, if // available currentLocation *time.Location } type transactionStatus byte const ( txnStatusIdle transactionStatus = 'I' txnStatusIdleInTransaction transactionStatus = 'T' txnStatusInFailedTransaction transactionStatus = 'E' ) func (s transactionStatus) String() string { switch s { case txnStatusIdle: return "idle" case txnStatusIdleInTransaction: return "idle in transaction" case txnStatusInFailedTransaction: return "in a failed transaction" default: errorf("unknown transactionStatus %d", s) } panic("not reached") } // Dialer is the dialer interface. It can be used to obtain more control over // how pq creates network connections. type Dialer interface { Dial(network, address string) (net.Conn, error) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) } type defaultDialer struct{} func (d defaultDialer) Dial(ntw, addr string) (net.Conn, error) { return net.Dial(ntw, addr) } func (d defaultDialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout(ntw, addr, timeout) } type conn struct { c net.Conn buf *bufio.Reader namei int scratch [512]byte txnStatus transactionStatus txnFinish func() // Save connection arguments to use during CancelRequest. dialer Dialer opts values // Cancellation key data for use with CancelRequest messages. processID int secretKey int parameterStatus parameterStatus saveMessageType byte saveMessageBuffer []byte // If true, this connection is bad and all public-facing functions should // return ErrBadConn. bad bool // If set, this connection should never use the binary format when // receiving query results from prepared statements. Only provided for // debugging. disablePreparedBinaryResult bool // Whether to always send []byte parameters over as binary. Enables single // round-trip mode for non-prepared Query calls. binaryParameters bool // If true this connection is in the middle of a COPY inCopy bool } // Handle driver-side settings in parsed connection string. func (cn *conn) handleDriverSettings(o values) (err error) { boolSetting := func(key string, val *bool) error { if value, ok := o[key]; ok { if value == "yes" { *val = true } else if value == "no" { *val = false } else { return fmt.Errorf("unrecognized value %q for %s", value, key) } } return nil } err = boolSetting("disable_prepared_binary_result", &cn.disablePreparedBinaryResult) if err != nil { return err } return boolSetting("binary_parameters", &cn.binaryParameters) } func (cn *conn) handlePgpass(o values) { // if a password was supplied, do not process .pgpass if _, ok := o["password"]; ok { return } filename := os.Getenv("PGPASSFILE") if filename == "" { // XXX this code doesn't work on Windows where the default filename is // XXX %APPDATA%\postgresql\pgpass.conf // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470 userHome := os.Getenv("HOME") if userHome == "" { user, err := user.Current() if err != nil { return } userHome = user.HomeDir } filename = filepath.Join(userHome, ".pgpass") } fileinfo, err := os.Stat(filename) if err != nil { return } mode := fileinfo.Mode() if mode&(0x77) != 0 { // XXX should warn about incorrect .pgpass permissions as psql does return } file, err := os.Open(filename) if err != nil { return } defer file.Close() scanner := bufio.NewScanner(io.Reader(file)) hostname := o["host"] ntw, _ := network(o) port := o["port"] db := o["dbname"] username := o["user"] // From: https://github.com/tg/pgpass/blob/master/reader.go getFields := func(s string) []string { fs := make([]string, 0, 5) f := make([]rune, 0, len(s)) var esc bool for _, c := range s { switch { case esc: f = append(f, c) esc = false case c == '\\': esc = true case c == ':': fs = append(fs, string(f)) f = f[:0] default: f = append(f, c) } } return append(fs, string(f)) } for scanner.Scan() { line := scanner.Text() if len(line) == 0 || line[0] == '#' { continue } split := getFields(line) if len(split) != 5 { continue } if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) { o["password"] = split[4] return } } } func (cn *conn) writeBuf(b byte) *writeBuf { cn.scratch[0] = b return &writeBuf{ buf: cn.scratch[:5], pos: 1, } } // Open opens a new connection to the database. name is a connection string. // Most users should only use it through database/sql package from the standard // library. func Open(name string) (_ driver.Conn, err error) { return DialOpen(defaultDialer{}, name) } // DialOpen opens a new connection to the database using a dialer. func DialOpen(d Dialer, name string) (_ driver.Conn, err error) { // Handle any panics during connection initialization. Note that we // specifically do *not* want to use errRecover(), as that would turn any // connection errors into ErrBadConns, hiding the real error message from // the user. defer errRecoverNoErrBadConn(&err) o := make(values) // A number of defaults are applied here, in this order: // // * Very low precedence defaults applied in every situation // * Environment variables // * Explicitly passed connection information o["host"] = "localhost" o["port"] = "5432" // N.B.: Extra float digits should be set to 3, but that breaks // Postgres 8.4 and older, where the max is 2. o["extra_float_digits"] = "2" for k, v := range parseEnviron(os.Environ()) { o[k] = v } if strings.HasPrefix(name, "postgres://") || strings.HasPrefix(name, "postgresql://") { name, err = ParseURL(name) if err != nil { return nil, err } } if err := parseOpts(name, o); err != nil { return nil, err } // Use the "fallback" application name if necessary if fallback, ok := o["fallback_application_name"]; ok { if _, ok := o["application_name"]; !ok { o["application_name"] = fallback } } // We can't work with any client_encoding other than UTF-8 currently. // However, we have historically allowed the user to set it to UTF-8 // explicitly, and there's no reason to break such programs, so allow that. // Note that the "options" setting could also set client_encoding, but // parsing its value is not worth it. Instead, we always explicitly send // client_encoding as a separate run-time parameter, which should override // anything set in options. if enc, ok := o["client_encoding"]; ok && !isUTF8(enc) { return nil, errors.New("client_encoding must be absent or 'UTF8'") } o["client_encoding"] = "UTF8" // DateStyle needs a similar treatment. if datestyle, ok := o["datestyle"]; ok { if datestyle != "ISO, MDY" { panic(fmt.Sprintf("setting datestyle must be absent or %v; got %v", "ISO, MDY", datestyle)) } } else { o["datestyle"] = "ISO, MDY" } // If a user is not provided by any other means, the last // resort is to use the current operating system provided user // name. if _, ok := o["user"]; !ok { u, err := userCurrent() if err != nil { return nil, err } o["user"] = u } cn := &conn{ opts: o, dialer: d, } err = cn.handleDriverSettings(o) if err != nil { return nil, err } cn.handlePgpass(o) cn.c, err = dial(d, o) if err != nil { return nil, err } err = cn.ssl(o) if err != nil { return nil, err } // cn.startup panics on error. Make sure we don't leak cn.c. panicking := true defer func() { if panicking { cn.c.Close() } }() cn.buf = bufio.NewReader(cn.c) cn.startup(o) // reset the deadline, in case one was set (see dial) if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { err = cn.c.SetDeadline(time.Time{}) } panicking = false return cn, err } func dial(d Dialer, o values) (net.Conn, error) { ntw, addr := network(o) // SSL is not necessary or supported over UNIX domain sockets if ntw == "unix" { o["sslmode"] = "disable" } // Zero or not specified means wait indefinitely. if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { seconds, err := strconv.ParseInt(timeout, 10, 0) if err != nil { return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err) } duration := time.Duration(seconds) * time.Second // connect_timeout should apply to the entire connection establishment // procedure, so we both use a timeout for the TCP connection // establishment and set a deadline for doing the initial handshake. // The deadline is then reset after startup() is done. deadline := time.Now().Add(duration) conn, err := d.DialTimeout(ntw, addr, duration) if err != nil { return nil, err } err = conn.SetDeadline(deadline) return conn, err } return d.Dial(ntw, addr) } func network(o values) (string, string) { host := o["host"] if strings.HasPrefix(host, "/") { sockPath := path.Join(host, ".s.PGSQL."+o["port"]) return "unix", sockPath } return "tcp", net.JoinHostPort(host, o["port"]) } type values map[string]string // scanner implements a tokenizer for libpq-style option strings. type scanner struct { s []rune i int } // newScanner returns a new scanner initialized with the option string s. func newScanner(s string) *scanner { return &scanner{[]rune(s), 0} } // Next returns the next rune. // It returns 0, false if the end of the text has been reached. func (s *scanner) Next() (rune, bool) { if s.i >= len(s.s) { return 0, false } r := s.s[s.i] s.i++ return r, true } // SkipSpaces returns the next non-whitespace rune. // It returns 0, false if the end of the text has been reached. func (s *scanner) SkipSpaces() (rune, bool) { r, ok := s.Next() for unicode.IsSpace(r) && ok { r, ok = s.Next() } return r, ok } // parseOpts parses the options from name and adds them to the values. // // The parsing code is based on conninfo_parse from libpq's fe-connect.c func parseOpts(name string, o values) error { s := newScanner(name) for { var ( keyRunes, valRunes []rune r rune ok bool ) if r, ok = s.SkipSpaces(); !ok { break } // Scan the key for !unicode.IsSpace(r) && r != '=' { keyRunes = append(keyRunes, r) if r, ok = s.Next(); !ok { break } } // Skip any whitespace if we're not at the = yet if r != '=' { r, ok = s.SkipSpaces() } // The current character should be = if r != '=' || !ok { return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes)) } // Skip any whitespace after the = if r, ok = s.SkipSpaces(); !ok { // If we reach the end here, the last value is just an empty string as per libpq. o[string(keyRunes)] = "" break } if r != '\'' { for !unicode.IsSpace(r) { if r == '\\' { if r, ok = s.Next(); !ok { return fmt.Errorf(`missing character after backslash`) } } valRunes = append(valRunes, r) if r, ok = s.Next(); !ok { break } } } else { quote: for { if r, ok = s.Next(); !ok { return fmt.Errorf(`unterminated quoted string literal in connection string`) } switch r { case '\'': break quote case '\\': r, _ = s.Next() fallthrough default: valRunes = append(valRunes, r) } } } o[string(keyRunes)] = string(valRunes) } return nil } func (cn *conn) isInTransaction() bool { return cn.txnStatus == txnStatusIdleInTransaction || cn.txnStatus == txnStatusInFailedTransaction } func (cn *conn) checkIsInTransaction(intxn bool) { if cn.isInTransaction() != intxn { cn.bad = true errorf("unexpected transaction status %v", cn.txnStatus) } } func (cn *conn) Begin() (_ driver.Tx, err error) { return cn.begin("") } func (cn *conn) begin(mode string) (_ driver.Tx, err error) { if cn.bad { return nil, driver.ErrBadConn } defer cn.errRecover(&err) cn.checkIsInTransaction(false) _, commandTag, err := cn.simpleExec("BEGIN" + mode) if err != nil { return nil, err } if commandTag != "BEGIN" { cn.bad = true return nil, fmt.Errorf("unexpected command tag %s", commandTag) } if cn.txnStatus != txnStatusIdleInTransaction { cn.bad = true return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus) } return cn, nil } func (cn *conn) closeTxn() { if finish := cn.txnFinish; finish != nil { finish() } } func (cn *conn) Commit() (err error) { defer cn.closeTxn() if cn.bad { return driver.ErrBadConn } defer cn.errRecover(&err) cn.checkIsInTransaction(true) // We don't want the client to think that everything is okay if it tries // to commit a failed transaction. However, no matter what we return, // database/sql will release this connection back into the free connection // pool so we have to abort the current transaction here. Note that you // would get the same behaviour if you issued a COMMIT in a failed // transaction, so it's also the least surprising thing to do here. if cn.txnStatus == txnStatusInFailedTransaction { if err := cn.Rollback(); err != nil { return err } return ErrInFailedTransaction } _, commandTag, err := cn.simpleExec("COMMIT") if err != nil { if cn.isInTransaction() { cn.bad = true } return err } if commandTag != "COMMIT" { cn.bad = true return fmt.Errorf("unexpected command tag %s", commandTag) } cn.checkIsInTransaction(false) return nil } func (cn *conn) Rollback() (err error) { defer cn.closeTxn() if cn.bad { return driver.ErrBadConn } defer cn.errRecover(&err) cn.checkIsInTransaction(true) _, commandTag, err := cn.simpleExec("ROLLBACK") if err != nil { if cn.isInTransaction() { cn.bad = true } return err } if commandTag != "ROLLBACK" { return fmt.Errorf("unexpected command tag %s", commandTag) } cn.checkIsInTransaction(false) return nil } func (cn *conn) gname() string { cn.namei++ return strconv.FormatInt(int64(cn.namei), 10) } func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) { b := cn.writeBuf('Q') b.string(q) cn.send(b) for { t, r := cn.recv1() switch t { case 'C': res, commandTag = cn.parseComplete(r.string()) case 'Z': cn.processReadyForQuery(r) if res == nil && err == nil { err = errUnexpectedReady } // done return case 'E': err = parseError(r) case 'I': res = emptyRows case 'T', 'D': // ignore any results default: cn.bad = true errorf("unknown response for simple query: %q", t) } } } func (cn *conn) simpleQuery(q string) (res *rows, err error) { defer cn.errRecover(&err) b := cn.writeBuf('Q') b.string(q) cn.send(b) for { t, r := cn.recv1() switch t { case 'C', 'I': // We allow queries which don't return any results through Query as // well as Exec. We still have to give database/sql a rows object // the user can close, though, to avoid connections from being // leaked. A "rows" with done=true works fine for that purpose. if err != nil { cn.bad = true errorf("unexpected message %q in simple query execution", t) } if res == nil { res = &rows{ cn: cn, } } // Set the result and tag to the last command complete if there wasn't a // query already run. Although queries usually return from here and cede // control to Next, a query with zero results does not. if t == 'C' && res.colNames == nil { res.result, res.tag = cn.parseComplete(r.string()) } res.done = true case 'Z': cn.processReadyForQuery(r) // done return case 'E': res = nil err = parseError(r) case 'D': if res == nil { cn.bad = true errorf("unexpected DataRow in simple query execution") } // the query didn't fail; kick off to Next cn.saveMessage(t, r) return case 'T': // res might be non-nil here if we received a previous // CommandComplete, but that's fine; just overwrite it res = &rows{cn: cn} res.colNames, res.colFmts, res.colTyps = parsePortalRowDescribe(r) // To work around a bug in QueryRow in Go 1.2 and earlier, wait // until the first DataRow has been received. default: cn.bad = true errorf("unknown response for simple query: %q", t) } } } type noRows struct{} var emptyRows noRows var _ driver.Result = noRows{} func (noRows) LastInsertId() (int64, error) { return 0, errNoLastInsertID } func (noRows) RowsAffected() (int64, error) { return 0, errNoRowsAffected } // Decides which column formats to use for a prepared statement. The input is // an array of type oids, one element per result column. func decideColumnFormats(colTyps []fieldDesc, forceText bool) (colFmts []format, colFmtData []byte) { if len(colTyps) == 0 { return nil, colFmtDataAllText } colFmts = make([]format, len(colTyps)) if forceText { return colFmts, colFmtDataAllText } allBinary := true allText := true for i, t := range colTyps { switch t.OID { // This is the list of types to use binary mode for when receiving them // through a prepared statement. If a type appears in this list, it // must also be implemented in binaryDecode in encode.go. case oid.T_bytea: fallthrough case oid.T_int8: fallthrough case oid.T_int4: fallthrough case oid.T_int2: fallthrough case oid.T_uuid: colFmts[i] = formatBinary allText = false default: allBinary = false } } if allBinary { return colFmts, colFmtDataAllBinary } else if allText { return colFmts, colFmtDataAllText } else { colFmtData = make([]byte, 2+len(colFmts)*2) binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts))) for i, v := range colFmts { binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v)) } return colFmts, colFmtData } } func (cn *conn) prepareTo(q, stmtName string) *stmt { st := &stmt{cn: cn, name: stmtName} b := cn.writeBuf('P') b.string(st.name) b.string(q) b.int16(0) b.next('D') b.byte('S') b.string(st.name) b.next('S') cn.send(b) cn.readParseResponse() st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse() st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult) cn.readReadyForQuery() return st } func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) { if cn.bad { return nil, driver.ErrBadConn } defer cn.errRecover(&err) if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") { s, err := cn.prepareCopyIn(q) if err == nil { cn.inCopy = true } return s, err } return cn.prepareTo(q, cn.gname()), nil } func (cn *conn) Close() (err error) { // Skip cn.bad return here because we always want to close a connection. defer cn.errRecover(&err) // Ensure that cn.c.Close is always run. Since error handling is done with // panics and cn.errRecover, the Close must be in a defer. defer func() { cerr := cn.c.Close() if err == nil { err = cerr } }() // Don't go through send(); ListenerConn relies on us not scribbling on the // scratch buffer of this connection. return cn.sendSimpleMessage('X') } // Implement the "Queryer" interface func (cn *conn) Query(query string, args []driver.Value) (driver.Rows, error) { return cn.query(query, args) } func (cn *conn) query(query string, args []driver.Value) (_ *rows, err error) { if cn.bad { return nil, driver.ErrBadConn } if cn.inCopy { return nil, errCopyInProgress } defer cn.errRecover(&err) // Check to see if we can use the "simpleQuery" interface, which is // *much* faster than going through prepare/exec if len(args) == 0 { return cn.simpleQuery(query) } if cn.binaryParameters { cn.sendBinaryModeQuery(query, args) cn.readParseResponse() cn.readBindResponse() rows := &rows{cn: cn} rows.colNames, rows.colFmts, rows.colTyps = cn.readPortalDescribeResponse() cn.postExecuteWorkaround() return rows, nil } st := cn.prepareTo(query, "") st.exec(args) return &rows{ cn: cn, colNames: st.colNames, colTyps: st.colTyps, colFmts: st.colFmts, }, nil } // Implement the optional "Execer" interface for one-shot queries func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) { if cn.bad { return nil, driver.ErrBadConn } defer cn.errRecover(&err) // Check to see if we can use the "simpleExec" interface, which is // *much* faster than going through prepare/exec if len(args) == 0 { // ignore commandTag, our caller doesn't care r, _, err := cn.simpleExec(query) return r, err } if cn.binaryParameters { cn.sendBinaryModeQuery(query, args) cn.readParseResponse() cn.readBindResponse() cn.readPortalDescribeResponse() cn.postExecuteWorkaround() res, _, err = cn.readExecuteResponse("Execute") return res, err } // Use the unnamed statement to defer planning until bind // time, or else value-based selectivity estimates cannot be // used. st := cn.prepareTo(query, "") r, err := st.Exec(args) if err != nil { panic(err) } return r, err } func (cn *conn) send(m *writeBuf) { _, err := cn.c.Write(m.wrap()) if err != nil { panic(err) } } func (cn *conn) sendStartupPacket(m *writeBuf) error { _, err := cn.c.Write((m.wrap())[1:]) return err } // Send a message of type typ to the server on the other end of cn. The // message should have no payload. This method does not use the scratch // buffer. func (cn *conn) sendSimpleMessage(typ byte) (err error) { _, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'}) return err } // saveMessage memorizes a message and its buffer in the conn struct. // recvMessage will then return these values on the next call to it. This // method is useful in cases where you have to see what the next message is // going to be (e.g. to see whether it's an error or not) but you can't handle // the message yourself. func (cn *conn) saveMessage(typ byte, buf *readBuf) { if cn.saveMessageType != 0 { cn.bad = true errorf("unexpected saveMessageType %d", cn.saveMessageType) } cn.saveMessageType = typ cn.saveMessageBuffer = *buf } // recvMessage receives any message from the backend, or returns an error if // a problem occurred while reading the message. func (cn *conn) recvMessage(r *readBuf) (byte, error) { // workaround for a QueryRow bug, see exec if cn.saveMessageType != 0 { t := cn.saveMessageType *r = cn.saveMessageBuffer cn.saveMessageType = 0 cn.saveMessageBuffer = nil return t, nil } x := cn.scratch[:5] _, err := io.ReadFull(cn.buf, x) if err != nil { return 0, err } // read the type and length of the message that follows t := x[0] n := int(binary.BigEndian.Uint32(x[1:])) - 4 var y []byte if n <= len(cn.scratch) { y = cn.scratch[:n] } else { y = make([]byte, n) } _, err = io.ReadFull(cn.buf, y) if err != nil { return 0, err } *r = y return t, nil } // recv receives a message from the backend, but if an error happened while // reading the message or the received message was an ErrorResponse, it panics. // NoticeResponses are ignored. This function should generally be used only // during the startup sequence. func (cn *conn) recv() (t byte, r *readBuf) { for { var err error r = &readBuf{} t, err = cn.recvMessage(r) if err != nil { panic(err) } switch t { case 'E': panic(parseError(r)) case 'N': // ignore default: return } } } // recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by // the caller to avoid an allocation. func (cn *conn) recv1Buf(r *readBuf) byte { for { t, err := cn.recvMessage(r) if err != nil { panic(err) } switch t { case 'A', 'N': // ignore case 'S': cn.processParameterStatus(r) default: return t } } } // recv1 receives a message from the backend, panicking if an error occurs // while attempting to read it. All asynchronous messages are ignored, with // the exception of ErrorResponse. func (cn *conn) recv1() (t byte, r *readBuf) { r = &readBuf{} t = cn.recv1Buf(r) return t, r } func (cn *conn) ssl(o values) error { upgrade, err := ssl(o) if err != nil { return err } if upgrade == nil { // Nothing to do return nil } w := cn.writeBuf(0) w.int32(80877103) if err = cn.sendStartupPacket(w); err != nil { return err } b := cn.scratch[:1] _, err = io.ReadFull(cn.c, b) if err != nil { return err } if b[0] != 'S' { return ErrSSLNotSupported } cn.c, err = upgrade(cn.c) return err } // isDriverSetting returns true iff a setting is purely for configuring the // driver's options and should not be sent to the server in the connection // startup packet. func isDriverSetting(key string) bool { switch key { case "host", "port": return true case "password": return true case "sslmode", "sslcert", "sslkey", "sslrootcert": return true case "fallback_application_name": return true case "connect_timeout": return true case "disable_prepared_binary_result": return true case "binary_parameters": return true default: return false } } func (cn *conn) startup(o values) { w := cn.writeBuf(0) w.int32(196608) // Send the backend the name of the database we want to connect to, and the // user we want to connect as. Additionally, we send over any run-time // parameters potentially included in the connection string. If the server // doesn't recognize any of them, it will reply with an error. for k, v := range o { if isDriverSetting(k) { // skip options which can't be run-time parameters continue } // The protocol requires us to supply the database name as "database" // instead of "dbname". if k == "dbname" { k = "database" } w.string(k) w.string(v) } w.string("") if err := cn.sendStartupPacket(w); err != nil { panic(err) } for { t, r := cn.recv() switch t { case 'K': cn.processBackendKeyData(r) case 'S': cn.processParameterStatus(r) case 'R': cn.auth(r, o) case 'Z': cn.processReadyForQuery(r) return default: errorf("unknown response for startup: %q", t) } } } func (cn *conn) auth(r *readBuf, o values) { switch code := r.int32(); code { case 0: // OK case 3: w := cn.writeBuf('p') w.string(o["password"]) cn.send(w) t, r := cn.recv() if t != 'R' { errorf("unexpected password response: %q", t) } if r.int32() != 0 { errorf("unexpected authentication response: %q", t) } case 5: s := string(r.next(4)) w := cn.writeBuf('p') w.string("md5" + md5s(md5s(o["password"]+o["user"])+s)) cn.send(w) t, r := cn.recv() if t != 'R' { errorf("unexpected password response: %q", t) } if r.int32() != 0 { errorf("unexpected authentication response: %q", t) } default: errorf("unknown authentication response: %d", code) } } type format int const formatText format = 0 const formatBinary format = 1 // One result-column format code with the value 1 (i.e. all binary). var colFmtDataAllBinary = []byte{0, 1, 0, 1} // No result-column format codes (i.e. all text). var colFmtDataAllText = []byte{0, 0} type stmt struct { cn *conn name string colNames []string colFmts []format colFmtData []byte colTyps []fieldDesc paramTyps []oid.Oid closed bool } func (st *stmt) Close() (err error) { if st.closed { return nil } if st.cn.bad { return driver.ErrBadConn } defer st.cn.errRecover(&err) w := st.cn.writeBuf('C') w.byte('S') w.string(st.name) st.cn.send(w) st.cn.send(st.cn.writeBuf('S')) t, _ := st.cn.recv1() if t != '3' { st.cn.bad = true errorf("unexpected close response: %q", t) } st.closed = true t, r := st.cn.recv1() if t != 'Z' { st.cn.bad = true errorf("expected ready for query, but got: %q", t) } st.cn.processReadyForQuery(r) return nil } func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) { if st.cn.bad { return nil, driver.ErrBadConn } defer st.cn.errRecover(&err) st.exec(v) return &rows{ cn: st.cn, colNames: st.colNames, colTyps: st.colTyps, colFmts: st.colFmts, }, nil } func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) { if st.cn.bad { return nil, driver.ErrBadConn } defer st.cn.errRecover(&err) st.exec(v) res, _, err = st.cn.readExecuteResponse("simple query") return res, err } func (st *stmt) exec(v []driver.Value) { if len(v) >= 65536 { errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v)) } if len(v) != len(st.paramTyps) { errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps)) } cn := st.cn w := cn.writeBuf('B') w.byte(0) // unnamed portal w.string(st.name) if cn.binaryParameters { cn.sendBinaryParameters(w, v) } else { w.int16(0) w.int16(len(v)) for i, x := range v { if x == nil { w.int32(-1) } else { b := encode(&cn.parameterStatus, x, st.paramTyps[i]) w.int32(len(b)) w.bytes(b) } } } w.bytes(st.colFmtData) w.next('E') w.byte(0) w.int32(0) w.next('S') cn.send(w) cn.readBindResponse() cn.postExecuteWorkaround() } func (st *stmt) NumInput() int { return len(st.paramTyps) } // parseComplete parses the "command tag" from a CommandComplete message, and // returns the number of rows affected (if applicable) and a string // identifying only the command that was executed, e.g. "ALTER TABLE". If the // command tag could not be parsed, parseComplete panics. func (cn *conn) parseComplete(commandTag string) (driver.Result, string) { commandsWithAffectedRows := []string{ "SELECT ", // INSERT is handled below "UPDATE ", "DELETE ", "FETCH ", "MOVE ", "COPY ", } var affectedRows *string for _, tag := range commandsWithAffectedRows { if strings.HasPrefix(commandTag, tag) { t := commandTag[len(tag):] affectedRows = &t commandTag = tag[:len(tag)-1] break } } // INSERT also includes the oid of the inserted row in its command tag. // Oids in user tables are deprecated, and the oid is only returned when // exactly one row is inserted, so it's unlikely to be of value to any // real-world application and we can ignore it. if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") { parts := strings.Split(commandTag, " ") if len(parts) != 3 { cn.bad = true errorf("unexpected INSERT command tag %s", commandTag) } affectedRows = &parts[len(parts)-1] commandTag = "INSERT" } // There should be no affected rows attached to the tag, just return it if affectedRows == nil { return driver.RowsAffected(0), commandTag } n, err := strconv.ParseInt(*affectedRows, 10, 64) if err != nil { cn.bad = true errorf("could not parse commandTag: %s", err) } return driver.RowsAffected(n), commandTag } type rows struct { cn *conn finish func() colNames []string colTyps []fieldDesc colFmts []format done bool rb readBuf result driver.Result tag string } func (rs *rows) Close() error { if finish := rs.finish; finish != nil { defer finish() } // no need to look at cn.bad as Next() will for { err := rs.Next(nil) switch err { case nil: case io.EOF: // rs.Next can return io.EOF on both 'Z' (ready for query) and 'T' (row // description, used with HasNextResultSet). We need to fetch messages until // we hit a 'Z', which is done by waiting for done to be set. if rs.done { return nil } default: return err } } } func (rs *rows) Columns() []string { return rs.colNames } func (rs *rows) Result() driver.Result { if rs.result == nil { return emptyRows } return rs.result } func (rs *rows) Tag() string { return rs.tag } func (rs *rows) Next(dest []driver.Value) (err error) { if rs.done { return io.EOF } conn := rs.cn if conn.bad { return driver.ErrBadConn } defer conn.errRecover(&err) for { t := conn.recv1Buf(&rs.rb) switch t { case 'E': err = parseError(&rs.rb) case 'C', 'I': if t == 'C' { rs.result, rs.tag = conn.parseComplete(rs.rb.string()) } continue case 'Z': conn.processReadyForQuery(&rs.rb) rs.done = true if err != nil { return err } return io.EOF case 'D': n := rs.rb.int16() if err != nil { conn.bad = true errorf("unexpected DataRow after error %s", err) } if n < len(dest) { dest = dest[:n] } for i := range dest { l := rs.rb.int32() if l == -1 { dest[i] = nil continue } dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i].OID, rs.colFmts[i]) } return case 'T': rs.colNames, rs.colFmts, rs.colTyps = parsePortalRowDescribe(&rs.rb) return io.EOF default: errorf("unexpected message after execute: %q", t) } } } func (rs *rows) HasNextResultSet() bool { return !rs.done } func (rs *rows) NextResultSet() error { return nil } // QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be // used as part of an SQL statement. For example: // // tblname := "my_table" // data := "my_data" // quoted := pq.QuoteIdentifier(tblname) // err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data) // // Any double quotes in name will be escaped. The quoted identifier will be // case sensitive when used in a query. If the input string contains a zero // byte, the result will be truncated immediately before it. func QuoteIdentifier(name string) string { end := strings.IndexRune(name, 0) if end > -1 { name = name[:end] } return `"` + strings.Replace(name, `"`, `""`, -1) + `"` } func md5s(s string) string { h := md5.New() h.Write([]byte(s)) return fmt.Sprintf("%x", h.Sum(nil)) } func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) { // Do one pass over the parameters to see if we're going to send any of // them over in binary. If we are, create a paramFormats array at the // same time. var paramFormats []int for i, x := range args { _, ok := x.([]byte) if ok { if paramFormats == nil { paramFormats = make([]int, len(args)) } paramFormats[i] = 1 } } if paramFormats == nil { b.int16(0) } else { b.int16(len(paramFormats)) for _, x := range paramFormats { b.int16(x) } } b.int16(len(args)) for _, x := range args { if x == nil { b.int32(-1) } else { datum := binaryEncode(&cn.parameterStatus, x) b.int32(len(datum)) b.bytes(datum) } } } func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) { if len(args) >= 65536 { errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args)) } b := cn.writeBuf('P') b.byte(0) // unnamed statement b.string(query) b.int16(0) b.next('B') b.int16(0) // unnamed portal and statement cn.sendBinaryParameters(b, args) b.bytes(colFmtDataAllText) b.next('D') b.byte('P') b.byte(0) // unnamed portal b.next('E') b.byte(0) b.int32(0) b.next('S') cn.send(b) } func (cn *conn) processParameterStatus(r *readBuf) { var err error param := r.string() switch param { case "server_version": var major1 int var major2 int var minor int _, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor) if err == nil { cn.parameterStatus.serverVersion = major1*10000 + major2*100 + minor } case "TimeZone": cn.parameterStatus.currentLocation, err = time.LoadLocation(r.string()) if err != nil { cn.parameterStatus.currentLocation = nil } default: // ignore } } func (cn *conn) processReadyForQuery(r *readBuf) { cn.txnStatus = transactionStatus(r.byte()) } func (cn *conn) readReadyForQuery() { t, r := cn.recv1() switch t { case 'Z': cn.processReadyForQuery(r) return default: cn.bad = true errorf("unexpected message %q; expected ReadyForQuery", t) } } func (cn *conn) processBackendKeyData(r *readBuf) { cn.processID = r.int32() cn.secretKey = r.int32() } func (cn *conn) readParseResponse() { t, r := cn.recv1() switch t { case '1': return case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) default: cn.bad = true errorf("unexpected Parse response %q", t) } } func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []fieldDesc) { for { t, r := cn.recv1() switch t { case 't': nparams := r.int16() paramTyps = make([]oid.Oid, nparams) for i := range paramTyps { paramTyps[i] = r.oid() } case 'n': return paramTyps, nil, nil case 'T': colNames, colTyps = parseStatementRowDescribe(r) return paramTyps, colNames, colTyps case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) default: cn.bad = true errorf("unexpected Describe statement response %q", t) } } } func (cn *conn) readPortalDescribeResponse() (colNames []string, colFmts []format, colTyps []fieldDesc) { t, r := cn.recv1() switch t { case 'T': return parsePortalRowDescribe(r) case 'n': return nil, nil, nil case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) default: cn.bad = true errorf("unexpected Describe response %q", t) } panic("not reached") } func (cn *conn) readBindResponse() { t, r := cn.recv1() switch t { case '2': return case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) default: cn.bad = true errorf("unexpected Bind response %q", t) } } func (cn *conn) postExecuteWorkaround() { // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores // any errors from rows.Next, which masks errors that happened during the // execution of the query. To avoid the problem in common cases, we wait // here for one more message from the database. If it's not an error the // query will likely succeed (or perhaps has already, if it's a // CommandComplete), so we push the message into the conn struct; recv1 // will return it as the next message for rows.Next or rows.Close. // However, if it's an error, we wait until ReadyForQuery and then return // the error to our caller. for { t, r := cn.recv1() switch t { case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) case 'C', 'D', 'I': // the query didn't fail, but we can't process this message cn.saveMessage(t, r) return default: cn.bad = true errorf("unexpected message during extended query execution: %q", t) } } } // Only for Exec(), since we ignore the returned data func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, err error) { for { t, r := cn.recv1() switch t { case 'C': if err != nil { cn.bad = true errorf("unexpected CommandComplete after error %s", err) } res, commandTag = cn.parseComplete(r.string()) case 'Z': cn.processReadyForQuery(r) if res == nil && err == nil { err = errUnexpectedReady } return res, commandTag, err case 'E': err = parseError(r) case 'T', 'D', 'I': if err != nil { cn.bad = true errorf("unexpected %q after error %s", t, err) } if t == 'I' { res = emptyRows } // ignore any results default: cn.bad = true errorf("unknown %s response: %q", protocolState, t) } } } func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []fieldDesc) { n := r.int16() colNames = make([]string, n) colTyps = make([]fieldDesc, n) for i := range colNames { colNames[i] = r.string() r.next(6) colTyps[i].OID = r.oid() colTyps[i].Len = r.int16() colTyps[i].Mod = r.int32() // format code not known when describing a statement; always 0 r.next(2) } return } func parsePortalRowDescribe(r *readBuf) (colNames []string, colFmts []format, colTyps []fieldDesc) { n := r.int16() colNames = make([]string, n) colFmts = make([]format, n) colTyps = make([]fieldDesc, n) for i := range colNames { colNames[i] = r.string() r.next(6) colTyps[i].OID = r.oid() colTyps[i].Len = r.int16() colTyps[i].Mod = r.int32() colFmts[i] = format(r.int16()) } return } // parseEnviron tries to mimic some of libpq's environment handling // // To ease testing, it does not directly reference os.Environ, but is // designed to accept its output. // // Environment-set connection information is intended to have a higher // precedence than a library default but lower than any explicitly // passed information (such as in the URL or connection string). func parseEnviron(env []string) (out map[string]string) { out = make(map[string]string) for _, v := range env { parts := strings.SplitN(v, "=", 2) accrue := func(keyname string) { out[keyname] = parts[1] } unsupported := func() { panic(fmt.Sprintf("setting %v not supported", parts[0])) } // The order of these is the same as is seen in the // PostgreSQL 9.1 manual. Unsupported but well-defined // keys cause a panic; these should be unset prior to // execution. Options which pq expects to be set to a // certain value are allowed, but must be set to that // value if present (they can, of course, be absent). switch parts[0] { case "PGHOST": accrue("host") case "PGHOSTADDR": unsupported() case "PGPORT": accrue("port") case "PGDATABASE": accrue("dbname") case "PGUSER": accrue("user") case "PGPASSWORD": accrue("password") case "PGSERVICE", "PGSERVICEFILE", "PGREALM": unsupported() case "PGOPTIONS": accrue("options") case "PGAPPNAME": accrue("application_name") case "PGSSLMODE": accrue("sslmode") case "PGSSLCERT": accrue("sslcert") case "PGSSLKEY": accrue("sslkey") case "PGSSLROOTCERT": accrue("sslrootcert") case "PGREQUIRESSL", "PGSSLCRL": unsupported() case "PGREQUIREPEER": unsupported() case "PGKRBSRVNAME", "PGGSSLIB": unsupported() case "PGCONNECT_TIMEOUT": accrue("connect_timeout") case "PGCLIENTENCODING": accrue("client_encoding") case "PGDATESTYLE": accrue("datestyle") case "PGTZ": accrue("timezone") case "PGGEQO": accrue("geqo") case "PGSYSCONFDIR", "PGLOCALEDIR": unsupported() } } return out } // isUTF8 returns whether name is a fuzzy variation of the string "UTF-8". func isUTF8(name string) bool { // Recognize all sorts of silly things as "UTF-8", like Postgres does s := strings.Map(alnumLowerASCII, name) return s == "utf8" || s == "unicode" } func alnumLowerASCII(ch rune) rune { if 'A' <= ch && ch <= 'Z' { return ch + ('a' - 'A') } if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' { return ch } return -1 // discard }
vendor/github.com/lib/pq/conn.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.0009717172360979021, 0.000184815056854859, 0.00015943520702421665, 0.00017167463374789804, 0.00007847082451917231 ]
{ "id": 1, "code_window": [ " const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;\n", " const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);\n", " const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);\n", " const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);\n", " const loading = queryTransactions.some(qt => !qt.done);\n", "\n", " return (\n", " <div className={exploreClass} ref={this.getRef}>\n", " <div className=\"navbar\">\n", " {position === 'left' ? (\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const queryEmpty = queryTransactions.some(qt => qt.resultType === 'Logs' && qt.done && qt.result.length === 0);\n" ], "file_path": "public/app/features/explore/Explore.tsx", "type": "add", "edit_start_line_idx": 839 }
// Code generated by "stringer -type token"; DO NOT EDIT package mssql import "fmt" const ( _token_name_0 = "tokenReturnStatus" _token_name_1 = "tokenColMetadata" _token_name_2 = "tokenOrdertokenErrortokenInfo" _token_name_3 = "tokenLoginAck" _token_name_4 = "tokenRowtokenNbcRow" _token_name_5 = "tokenEnvChange" _token_name_6 = "tokenSSPI" _token_name_7 = "tokenDonetokenDoneProctokenDoneInProc" ) var ( _token_index_0 = [...]uint8{0, 17} _token_index_1 = [...]uint8{0, 16} _token_index_2 = [...]uint8{0, 10, 20, 29} _token_index_3 = [...]uint8{0, 13} _token_index_4 = [...]uint8{0, 8, 19} _token_index_5 = [...]uint8{0, 14} _token_index_6 = [...]uint8{0, 9} _token_index_7 = [...]uint8{0, 9, 22, 37} ) func (i token) String() string { switch { case i == 121: return _token_name_0 case i == 129: return _token_name_1 case 169 <= i && i <= 171: i -= 169 return _token_name_2[_token_index_2[i]:_token_index_2[i+1]] case i == 173: return _token_name_3 case 209 <= i && i <= 210: i -= 209 return _token_name_4[_token_index_4[i]:_token_index_4[i+1]] case i == 227: return _token_name_5 case i == 237: return _token_name_6 case 253 <= i && i <= 255: i -= 253 return _token_name_7[_token_index_7[i]:_token_index_7[i+1]] default: return fmt.Sprintf("token(%d)", i) } }
vendor/github.com/denisenkom/go-mssqldb/token_string.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.00017655076226219535, 0.0001719687134027481, 0.00016587610298302025, 0.00017194708925671875, 0.0000035922309962188592 ]
{ "id": 2, "code_window": [ " onStopScanning={this.onStopScanning}\n", " range={range}\n", " scanning={scanning}\n", " scanRange={scanRange}\n", " />\n", " </Panel>\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty={queryEmpty}\n" ], "file_path": "public/app/features/explore/Explore.tsx", "type": "add", "edit_start_line_idx": 971 }
import _ from 'lodash'; import React, { PureComponent } from 'react'; import Highlighter from 'react-highlight-words'; import * as rangeUtil from 'app/core/utils/rangeutil'; import { RawTimeRange } from 'app/types/series'; import { LogsDedupStrategy, LogsModel, dedupLogRows, filterLogLevels, LogLevel, LogsStreamLabels, LogsMetaKind, LogRow, } from 'app/core/logs_model'; import { findHighlightChunksInText } from 'app/core/utils/text'; import { Switch } from 'app/core/components/Switch/Switch'; import Graph from './Graph'; const PREVIEW_LIMIT = 100; const graphOptions = { series: { bars: { show: true, lineWidth: 5, // barWidth: 10, }, // stack: true, }, yaxis: { tickDecimals: 0, }, }; function renderMetaItem(value: any, kind: LogsMetaKind) { if (kind === LogsMetaKind.LabelsMap) { return ( <span className="logs-meta-item__value-labels"> <Labels labels={value} /> </span> ); } return value; } class Label extends PureComponent<{ label: string; value: string; onClickLabel?: (label: string, value: string) => void; }> { onClickLabel = () => { const { onClickLabel, label, value } = this.props; if (onClickLabel) { onClickLabel(label, value); } }; render() { const { label, value } = this.props; const tooltip = `${label}: ${value}`; return ( <span className="logs-label" title={tooltip} onClick={this.onClickLabel}> {value} </span> ); } } class Labels extends PureComponent<{ labels: LogsStreamLabels; onClickLabel?: (label: string, value: string) => void; }> { render() { const { labels, onClickLabel } = this.props; return Object.keys(labels).map(key => ( <Label key={key} label={key} value={labels[key]} onClickLabel={onClickLabel} /> )); } } interface RowProps { row: LogRow; showLabels: boolean | null; // Tristate: null means auto showLocalTime: boolean; showUtc: boolean; onClickLabel?: (label: string, value: string) => void; } function Row({ onClickLabel, row, showLabels, showLocalTime, showUtc }: RowProps) { const needsHighlighter = row.searchWords && row.searchWords.length > 0; return ( <div className="logs-row"> <div className={row.logLevel ? `logs-row-level logs-row-level-${row.logLevel}` : ''}> {row.duplicates > 0 && ( <div className="logs-row-level__duplicates" title={`${row.duplicates} duplicates`}> {Array.apply(null, { length: row.duplicates }).map((bogus, index) => ( <div className="logs-row-level__duplicate" key={`${index}`} /> ))} </div> )} </div> {showUtc && ( <div className="logs-row-time" title={`Local: ${row.timeLocal} (${row.timeFromNow})`}> {row.timestamp} </div> )} {showLocalTime && ( <div className="logs-row-time" title={`${row.timestamp} (${row.timeFromNow})`}> {row.timeLocal} </div> )} {showLabels && ( <div className="logs-row-labels"> <Labels labels={row.uniqueLabels} onClickLabel={onClickLabel} /> </div> )} <div className="logs-row-message"> {needsHighlighter ? ( <Highlighter textToHighlight={row.entry} searchWords={row.searchWords} findChunks={findHighlightChunksInText} highlightClassName="logs-row-match-highlight" /> ) : ( row.entry )} </div> </div> ); } interface LogsProps { className?: string; data: LogsModel; loading: boolean; position: string; range?: RawTimeRange; scanning?: boolean; scanRange?: RawTimeRange; onChangeTime?: (range: RawTimeRange) => void; onClickLabel?: (label: string, value: string) => void; onStartScanning?: () => void; onStopScanning?: () => void; } interface LogsState { dedup: LogsDedupStrategy; deferLogs: boolean; hiddenLogLevels: Set<LogLevel>; renderAll: boolean; showLabels: boolean | null; // Tristate: null means auto showLocalTime: boolean; showUtc: boolean; } export default class Logs extends PureComponent<LogsProps, LogsState> { deferLogsTimer: NodeJS.Timer; renderAllTimer: NodeJS.Timer; state = { dedup: LogsDedupStrategy.none, deferLogs: true, hiddenLogLevels: new Set(), renderAll: false, showLabels: null, showLocalTime: true, showUtc: false, }; componentDidMount() { // Staged rendering if (this.state.deferLogs) { const { data } = this.props; const rowCount = data && data.rows ? data.rows.length : 0; // Render all right away if not too far over the limit const renderAll = rowCount <= PREVIEW_LIMIT * 2; this.deferLogsTimer = setTimeout(() => this.setState({ deferLogs: false, renderAll }), rowCount); } } componentDidUpdate(prevProps, prevState) { // Staged rendering if (prevState.deferLogs && !this.state.deferLogs && !this.state.renderAll) { this.renderAllTimer = setTimeout(() => this.setState({ renderAll: true }), 2000); } } componentWillUnmount() { clearTimeout(this.deferLogsTimer); clearTimeout(this.renderAllTimer); } onChangeDedup = (dedup: LogsDedupStrategy) => { this.setState(prevState => { if (prevState.dedup === dedup) { return { dedup: LogsDedupStrategy.none }; } return { dedup }; }); }; onChangeLabels = (event: React.SyntheticEvent) => { const target = event.target as HTMLInputElement; this.setState({ showLabels: target.checked, }); }; onChangeLocalTime = (event: React.SyntheticEvent) => { const target = event.target as HTMLInputElement; this.setState({ showLocalTime: target.checked, }); }; onChangeUtc = (event: React.SyntheticEvent) => { const target = event.target as HTMLInputElement; this.setState({ showUtc: target.checked, }); }; onToggleLogLevel = (rawLevel: string, hiddenRawLevels: Set<string>) => { const hiddenLogLevels: Set<LogLevel> = new Set(Array.from(hiddenRawLevels).map(level => LogLevel[level])); this.setState({ hiddenLogLevels }); }; onClickScan = (event: React.SyntheticEvent) => { event.preventDefault(); this.props.onStartScanning(); }; onClickStopScan = (event: React.SyntheticEvent) => { event.preventDefault(); this.props.onStopScanning(); }; render() { const { className = '', data, loading = false, onClickLabel, position, range, scanning, scanRange } = this.props; const { dedup, deferLogs, hiddenLogLevels, renderAll, showLocalTime, showUtc } = this.state; let { showLabels } = this.state; const hasData = data && data.rows && data.rows.length > 0; // Filtering const filteredData = filterLogLevels(data, hiddenLogLevels); const dedupedData = dedupLogRows(filteredData, dedup); const dedupCount = dedupedData.rows.reduce((sum, row) => sum + row.duplicates, 0); const meta = [...data.meta]; if (dedup !== LogsDedupStrategy.none) { meta.push({ label: 'Dedup count', value: dedupCount, kind: LogsMetaKind.Number, }); } // Staged rendering const firstRows = dedupedData.rows.slice(0, PREVIEW_LIMIT); const lastRows = dedupedData.rows.slice(PREVIEW_LIMIT); // Check for labels if (showLabels === null) { if (hasData) { showLabels = data.rows.some(row => _.size(row.uniqueLabels) > 0); } else { showLabels = true; } } const scanText = scanRange ? `Scanning ${rangeUtil.describeTimeRange(scanRange)}` : 'Scanning...'; return ( <div className={`${className} logs`}> <div className="logs-graph"> <Graph data={data.series} height="100px" range={range} id={`explore-logs-graph-${position}`} onChangeTime={this.props.onChangeTime} onToggleSeries={this.onToggleLogLevel} userOptions={graphOptions} /> </div> <div className="logs-options"> <div className="logs-controls"> <Switch label="Timestamp" checked={showUtc} onChange={this.onChangeUtc} small /> <Switch label="Local time" checked={showLocalTime} onChange={this.onChangeLocalTime} small /> <Switch label="Labels" checked={showLabels} onChange={this.onChangeLabels} small /> <Switch label="Dedup: off" checked={dedup === LogsDedupStrategy.none} onChange={() => this.onChangeDedup(LogsDedupStrategy.none)} small /> <Switch label="Dedup: exact" checked={dedup === LogsDedupStrategy.exact} onChange={() => this.onChangeDedup(LogsDedupStrategy.exact)} small /> <Switch label="Dedup: numbers" checked={dedup === LogsDedupStrategy.numbers} onChange={() => this.onChangeDedup(LogsDedupStrategy.numbers)} small /> <Switch label="Dedup: signature" checked={dedup === LogsDedupStrategy.signature} onChange={() => this.onChangeDedup(LogsDedupStrategy.signature)} small /> {hasData && meta && ( <div className="logs-meta"> {meta.map(item => ( <div className="logs-meta-item" key={item.label}> <span className="logs-meta-item__label">{item.label}:</span> <span className="logs-meta-item__value">{renderMetaItem(item.value, item.kind)}</span> </div> ))} </div> )} </div> </div> <div className="logs-entries"> {hasData && !deferLogs && firstRows.map(row => ( <Row key={row.key + row.duplicates} row={row} showLabels={showLabels} showLocalTime={showLocalTime} showUtc={showUtc} onClickLabel={onClickLabel} /> ))} {hasData && !deferLogs && renderAll && lastRows.map(row => ( <Row key={row.key + row.duplicates} row={row} showLabels={showLabels} showLocalTime={showLocalTime} showUtc={showUtc} onClickLabel={onClickLabel} /> ))} {hasData && deferLogs && <span>Rendering {dedupedData.rows.length} rows...</span>} </div> {!loading && data.queryEmpty && !scanning && ( <div className="logs-nodata"> No logs found. <a className="link" onClick={this.onClickScan}> Scan for older logs </a> </div> )} {scanning && ( <div className="logs-nodata"> <span>{scanText}</span> <a className="link" onClick={this.onClickStopScan}> Stop scan </a> </div> )} </div> ); } }
public/app/features/explore/Logs.tsx
1
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.025825103744864464, 0.0010425555519759655, 0.00016406417125836015, 0.000171474544913508, 0.0040880292654037476 ]
{ "id": 2, "code_window": [ " onStopScanning={this.onStopScanning}\n", " range={range}\n", " scanning={scanning}\n", " scanRange={scanRange}\n", " />\n", " </Panel>\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty={queryEmpty}\n" ], "file_path": "public/app/features/explore/Explore.tsx", "type": "add", "edit_start_line_idx": 971 }
package hooks import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/registry" ) type IndexDataHook func(indexData *dtos.IndexViewData) type HooksService struct { indexDataHooks []IndexDataHook } func init() { registry.RegisterService(&HooksService{}) } func (srv *HooksService) Init() error { return nil } func (srv *HooksService) AddIndexDataHook(hook IndexDataHook) { srv.indexDataHooks = append(srv.indexDataHooks, hook) } func (srv *HooksService) RunIndexDataHooks(indexData *dtos.IndexViewData) { for _, hook := range srv.indexDataHooks { hook(indexData) } }
pkg/services/hooks/hooks.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.00016884245269466192, 0.00016755636897869408, 0.00016594397311564535, 0.00016771952505223453, 0.0000011032911970687564 ]
{ "id": 2, "code_window": [ " onStopScanning={this.onStopScanning}\n", " range={range}\n", " scanning={scanning}\n", " scanRange={scanRange}\n", " />\n", " </Panel>\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty={queryEmpty}\n" ], "file_path": "public/app/features/explore/Explore.tsx", "type": "add", "edit_start_line_idx": 971 }
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ed25519 implements the Ed25519 signature algorithm. See // https://ed25519.cr.yp.to/. // // These functions are also compatible with the “Ed25519” function defined in // RFC 8032. package ed25519 // This code is a port of the public domain, “ref10” implementation of ed25519 // from SUPERCOP. import ( "bytes" "crypto" cryptorand "crypto/rand" "crypto/sha512" "errors" "io" "strconv" "golang.org/x/crypto/ed25519/internal/edwards25519" ) const ( // PublicKeySize is the size, in bytes, of public keys as used in this package. PublicKeySize = 32 // PrivateKeySize is the size, in bytes, of private keys as used in this package. PrivateKeySize = 64 // SignatureSize is the size, in bytes, of signatures generated and verified by this package. SignatureSize = 64 ) // PublicKey is the type of Ed25519 public keys. type PublicKey []byte // PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. type PrivateKey []byte // Public returns the PublicKey corresponding to priv. func (priv PrivateKey) Public() crypto.PublicKey { publicKey := make([]byte, PublicKeySize) copy(publicKey, priv[32:]) return PublicKey(publicKey) } // Sign signs the given message with priv. // Ed25519 performs two passes over messages to be signed and therefore cannot // handle pre-hashed messages. Thus opts.HashFunc() must return zero to // indicate the message hasn't been hashed. This can be achieved by passing // crypto.Hash(0) as the value for opts. func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) { if opts.HashFunc() != crypto.Hash(0) { return nil, errors.New("ed25519: cannot sign hashed message") } return Sign(priv, message), nil } // GenerateKey generates a public/private key pair using entropy from rand. // If rand is nil, crypto/rand.Reader will be used. func GenerateKey(rand io.Reader) (publicKey PublicKey, privateKey PrivateKey, err error) { if rand == nil { rand = cryptorand.Reader } privateKey = make([]byte, PrivateKeySize) publicKey = make([]byte, PublicKeySize) _, err = io.ReadFull(rand, privateKey[:32]) if err != nil { return nil, nil, err } digest := sha512.Sum512(privateKey[:32]) digest[0] &= 248 digest[31] &= 127 digest[31] |= 64 var A edwards25519.ExtendedGroupElement var hBytes [32]byte copy(hBytes[:], digest[:]) edwards25519.GeScalarMultBase(&A, &hBytes) var publicKeyBytes [32]byte A.ToBytes(&publicKeyBytes) copy(privateKey[32:], publicKeyBytes[:]) copy(publicKey, publicKeyBytes[:]) return publicKey, privateKey, nil } // Sign signs the message with privateKey and returns a signature. It will // panic if len(privateKey) is not PrivateKeySize. func Sign(privateKey PrivateKey, message []byte) []byte { if l := len(privateKey); l != PrivateKeySize { panic("ed25519: bad private key length: " + strconv.Itoa(l)) } h := sha512.New() h.Write(privateKey[:32]) var digest1, messageDigest, hramDigest [64]byte var expandedSecretKey [32]byte h.Sum(digest1[:0]) copy(expandedSecretKey[:], digest1[:]) expandedSecretKey[0] &= 248 expandedSecretKey[31] &= 63 expandedSecretKey[31] |= 64 h.Reset() h.Write(digest1[32:]) h.Write(message) h.Sum(messageDigest[:0]) var messageDigestReduced [32]byte edwards25519.ScReduce(&messageDigestReduced, &messageDigest) var R edwards25519.ExtendedGroupElement edwards25519.GeScalarMultBase(&R, &messageDigestReduced) var encodedR [32]byte R.ToBytes(&encodedR) h.Reset() h.Write(encodedR[:]) h.Write(privateKey[32:]) h.Write(message) h.Sum(hramDigest[:0]) var hramDigestReduced [32]byte edwards25519.ScReduce(&hramDigestReduced, &hramDigest) var s [32]byte edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced) signature := make([]byte, SignatureSize) copy(signature[:], encodedR[:]) copy(signature[32:], s[:]) return signature } // Verify reports whether sig is a valid signature of message by publicKey. It // will panic if len(publicKey) is not PublicKeySize. func Verify(publicKey PublicKey, message, sig []byte) bool { if l := len(publicKey); l != PublicKeySize { panic("ed25519: bad public key length: " + strconv.Itoa(l)) } if len(sig) != SignatureSize || sig[63]&224 != 0 { return false } var A edwards25519.ExtendedGroupElement var publicKeyBytes [32]byte copy(publicKeyBytes[:], publicKey) if !A.FromBytes(&publicKeyBytes) { return false } edwards25519.FeNeg(&A.X, &A.X) edwards25519.FeNeg(&A.T, &A.T) h := sha512.New() h.Write(sig[:32]) h.Write(publicKey[:]) h.Write(message) var digest [64]byte h.Sum(digest[:0]) var hReduced [32]byte edwards25519.ScReduce(&hReduced, &digest) var R edwards25519.ProjectiveGroupElement var s [32]byte copy(s[:], sig[32:]) // https://tools.ietf.org/html/rfc8032#section-5.1.7 requires that s be in // the range [0, order) in order to prevent signature malleability. if !edwards25519.ScMinimal(&s) { return false } edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &s) var checkR [32]byte R.ToBytes(&checkR) return bytes.Equal(sig[:32], checkR[:]) }
vendor/golang.org/x/crypto/ed25519/ed25519.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.0001848790270742029, 0.00017278948507737368, 0.0001612211053725332, 0.00017516037041787058, 0.00000644642386760097 ]
{ "id": 2, "code_window": [ " onStopScanning={this.onStopScanning}\n", " range={range}\n", " scanning={scanning}\n", " scanRange={scanRange}\n", " />\n", " </Panel>\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty={queryEmpty}\n" ], "file_path": "public/app/features/explore/Explore.tsx", "type": "add", "edit_start_line_idx": 971 }
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin,race linux,race freebsd,race package unix import ( "runtime" "unsafe" ) const raceenabled = true func raceAcquire(addr unsafe.Pointer) { runtime.RaceAcquire(addr) } func raceReleaseMerge(addr unsafe.Pointer) { runtime.RaceReleaseMerge(addr) } func raceReadRange(addr unsafe.Pointer, len int) { runtime.RaceReadRange(addr, len) } func raceWriteRange(addr unsafe.Pointer, len int) { runtime.RaceWriteRange(addr, len) }
vendor/golang.org/x/sys/unix/race.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.0006516845314763486, 0.00029046606505289674, 0.00016472111747134477, 0.0001727292692521587, 0.00020859332289546728 ]
{ "id": 3, "code_window": [ " loading: boolean;\n", " position: string;\n", " range?: RawTimeRange;\n", " scanning?: boolean;\n", " scanRange?: RawTimeRange;\n", " onChangeTime?: (range: RawTimeRange) => void;\n", " onClickLabel?: (label: string, value: string) => void;\n", " onStartScanning?: () => void;\n", " onStopScanning?: () => void;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty: boolean;\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "add", "edit_start_line_idx": 142 }
import React from 'react'; import { hot } from 'react-hot-loader'; import Select from 'react-select'; import _ from 'lodash'; import { DataSource } from 'app/types/datasources'; import { ExploreState, ExploreUrlState, QueryTransaction, ResultType, QueryHintGetter, QueryHint, } from 'app/types/explore'; import { RawTimeRange, DataQuery } from 'app/types/series'; import store from 'app/core/store'; import { DEFAULT_RANGE, calculateResultsFromQueryTransactions, ensureQueries, getIntervals, generateKey, generateQueryKeys, hasNonEmptyQuery, makeTimeSeriesList, updateHistory, } from 'app/core/utils/explore'; import ResetStyles from 'app/core/components/Picker/ResetStyles'; import PickerOption from 'app/core/components/Picker/PickerOption'; import IndicatorsContainer from 'app/core/components/Picker/IndicatorsContainer'; import NoOptionsMessage from 'app/core/components/Picker/NoOptionsMessage'; import TableModel from 'app/core/table_model'; import { DatasourceSrv } from 'app/features/plugins/datasource_srv'; import Panel from './Panel'; import QueryRows from './QueryRows'; import Graph from './Graph'; import Logs from './Logs'; import Table from './Table'; import ErrorBoundary from './ErrorBoundary'; import TimePicker from './TimePicker'; interface ExploreProps { datasourceSrv: DatasourceSrv; onChangeSplit: (split: boolean, state?: ExploreState) => void; onSaveState: (key: string, state: ExploreState) => void; position: string; split: boolean; splitState?: ExploreState; stateKey: string; urlState: ExploreUrlState; } /** * Explore provides an area for quick query iteration for a given datasource. * Once a datasource is selected it populates the query section at the top. * When queries are run, their results are being displayed in the main section. * The datasource determines what kind of query editor it brings, and what kind * of results viewers it supports. * * QUERY HANDLING * * TLDR: to not re-render Explore during edits, query editing is not "controlled" * in a React sense: values need to be pushed down via `initialQueries`, while * edits travel up via `this.modifiedQueries`. * * By default the query rows start without prior state: `initialQueries` will * contain one empty DataQuery. While the user modifies the DataQuery, the * modifications are being tracked in `this.modifiedQueries`, which need to be * used whenever a query is sent to the datasource to reflect what the user sees * on the screen. Query rows can be initialized or reset using `initialQueries`, * by giving the respective row a new key. This wipes the old row and its state. * This property is also used to govern how many query rows there are (minimum 1). * * This flow makes sure that a query row can be arbitrarily complex without the * fear of being wiped or re-initialized via props. The query row is free to keep * its own state while the user edits or builds a query. Valid queries can be sent * up to Explore via the `onChangeQuery` prop. * * DATASOURCE REQUESTS * * A click on Run Query creates transactions for all DataQueries for all expanded * result viewers. New runs are discarding previous runs. Upon completion a transaction * saves the result. The result viewers construct their data from the currently existing * transactions. * * The result viewers determine some of the query options sent to the datasource, e.g., * `format`, to indicate eventual transformations by the datasources' result transformers. */ export class Explore extends React.PureComponent<ExploreProps, ExploreState> { el: any; /** * Current query expressions of the rows including their modifications, used for running queries. * Not kept in component state to prevent edit-render roundtrips. */ modifiedQueries: DataQuery[]; /** * Local ID cache to compare requested vs selected datasource */ requestedDatasourceId: string; scanTimer: NodeJS.Timer; /** * Timepicker to control scanning */ timepickerRef: React.RefObject<TimePicker>; constructor(props) { super(props); const splitState: ExploreState = props.splitState; let initialQueries: DataQuery[]; if (splitState) { // Split state overrides everything this.state = splitState; initialQueries = splitState.initialQueries; } else { const { datasource, queries, range } = props.urlState as ExploreUrlState; initialQueries = ensureQueries(queries); const initialRange = range || { ...DEFAULT_RANGE }; // Millies step for helper bar charts const initialGraphInterval = 15 * 1000; this.state = { datasource: null, datasourceError: null, datasourceLoading: null, datasourceMissing: false, datasourceName: datasource, exploreDatasources: [], graphInterval: initialGraphInterval, graphResult: [], initialQueries, history: [], logsResult: null, queryTransactions: [], range: initialRange, scanning: false, showingGraph: true, showingLogs: true, showingStartPage: false, showingTable: true, supportsGraph: null, supportsLogs: null, supportsTable: null, tableResult: new TableModel(), }; } this.modifiedQueries = initialQueries.slice(); this.timepickerRef = React.createRef(); } async componentDidMount() { const { datasourceSrv } = this.props; const { datasourceName } = this.state; if (!datasourceSrv) { throw new Error('No datasource service passed as props.'); } const datasources = datasourceSrv.getExploreSources(); const exploreDatasources = datasources.map(ds => ({ value: ds.name, label: ds.name, })); if (datasources.length > 0) { this.setState({ datasourceLoading: true, exploreDatasources }); // Priority: datasource in url, default datasource, first explore datasource let datasource; if (datasourceName) { datasource = await datasourceSrv.get(datasourceName); } else { datasource = await datasourceSrv.get(); } if (!datasource.meta.explore) { datasource = await datasourceSrv.get(datasources[0].name); } await this.setDatasource(datasource); } else { this.setState({ datasourceMissing: true }); } } componentWillUnmount() { clearTimeout(this.scanTimer); } async setDatasource(datasource: any, origin?: DataSource) { const { initialQueries, range } = this.state; const supportsGraph = datasource.meta.metrics; const supportsLogs = datasource.meta.logs; const supportsTable = datasource.meta.metrics; const datasourceId = datasource.meta.id; let datasourceError = null; // Keep ID to track selection this.requestedDatasourceId = datasourceId; try { const testResult = await datasource.testDatasource(); datasourceError = testResult.status === 'success' ? null : testResult.message; } catch (error) { datasourceError = (error && error.statusText) || 'Network error'; } if (datasourceId !== this.requestedDatasourceId) { // User already changed datasource again, discard results return; } const historyKey = `grafana.explore.history.${datasourceId}`; const history = store.getObject(historyKey, []); if (datasource.init) { datasource.init(); } // Check if queries can be imported from previously selected datasource let modifiedQueries = this.modifiedQueries; if (origin) { if (origin.meta.id === datasource.meta.id) { // Keep same queries if same type of datasource modifiedQueries = [...this.modifiedQueries]; } else if (datasource.importQueries) { // Datasource-specific importers modifiedQueries = await datasource.importQueries(this.modifiedQueries, origin.meta); } else { // Default is blank queries modifiedQueries = ensureQueries(); } } // Reset edit state with new queries const nextQueries = initialQueries.map((q, i) => ({ ...modifiedQueries[i], ...generateQueryKeys(i), })); this.modifiedQueries = modifiedQueries; // Custom components const StartPage = datasource.pluginExports.ExploreStartPage; // Calculate graph bucketing interval const graphInterval = getIntervals(range, datasource, this.el ? this.el.offsetWidth : 0).intervalMs; this.setState( { StartPage, datasource, datasourceError, graphInterval, history, supportsGraph, supportsLogs, supportsTable, datasourceLoading: false, datasourceName: datasource.name, initialQueries: nextQueries, showingStartPage: Boolean(StartPage), }, () => { if (datasourceError === null) { this.onSubmit(); } } ); } getRef = el => { this.el = el; }; onAddQueryRow = index => { // Local cache this.modifiedQueries[index + 1] = { ...generateQueryKeys(index + 1) }; this.setState(state => { const { initialQueries, queryTransactions } = state; const nextQueries = [ ...initialQueries.slice(0, index + 1), { ...this.modifiedQueries[index + 1] }, ...initialQueries.slice(index + 1), ]; // Ongoing transactions need to update their row indices const nextQueryTransactions = queryTransactions.map(qt => { if (qt.rowIndex > index) { return { ...qt, rowIndex: qt.rowIndex + 1, }; } return qt; }); return { initialQueries: nextQueries, queryTransactions: nextQueryTransactions }; }); }; onChangeDatasource = async option => { const origin = this.state.datasource; this.setState({ datasource: null, datasourceError: null, datasourceLoading: true, queryTransactions: [], }); const datasourceName = option.value; const datasource = await this.props.datasourceSrv.get(datasourceName); this.setDatasource(datasource as any, origin); }; onChangeQuery = (value: DataQuery, index: number, override?: boolean) => { // Null value means reset if (value === null) { value = { ...generateQueryKeys(index) }; } // Keep current value in local cache this.modifiedQueries[index] = value; if (override) { this.setState(state => { // Replace query row by injecting new key const { initialQueries, queryTransactions } = state; const query: DataQuery = { ...value, ...generateQueryKeys(index), }; const nextQueries = [...initialQueries]; nextQueries[index] = query; this.modifiedQueries = [...nextQueries]; // Discard ongoing transaction related to row query const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index); return { initialQueries: nextQueries, queryTransactions: nextQueryTransactions, }; }, this.onSubmit); } }; onChangeTime = (nextRange: RawTimeRange, scanning?: boolean) => { const range: RawTimeRange = { ...nextRange, }; if (this.state.scanning && !scanning) { this.onStopScanning(); } this.setState({ range, scanning }, () => this.onSubmit()); }; onClickClear = () => { this.modifiedQueries = ensureQueries(); this.setState( prevState => ({ initialQueries: [...this.modifiedQueries], queryTransactions: [], showingStartPage: Boolean(prevState.StartPage), }), this.saveState ); }; onClickCloseSplit = () => { const { onChangeSplit } = this.props; if (onChangeSplit) { onChangeSplit(false); } }; onClickGraphButton = () => { this.setState( state => { const showingGraph = !state.showingGraph; let nextQueryTransactions = state.queryTransactions; if (!showingGraph) { // Discard transactions related to Graph query nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Graph'); } return { queryTransactions: nextQueryTransactions, showingGraph }; }, () => { if (this.state.showingGraph) { this.onSubmit(); } } ); }; onClickLogsButton = () => { this.setState( state => { const showingLogs = !state.showingLogs; let nextQueryTransactions = state.queryTransactions; if (!showingLogs) { // Discard transactions related to Logs query nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Logs'); } return { queryTransactions: nextQueryTransactions, showingLogs }; }, () => { if (this.state.showingLogs) { this.onSubmit(); } } ); }; // Use this in help pages to set page to a single query onClickExample = (query: DataQuery) => { const nextQueries = [{ ...query, ...generateQueryKeys() }]; this.modifiedQueries = [...nextQueries]; this.setState({ initialQueries: nextQueries }, this.onSubmit); }; onClickSplit = () => { const { onChangeSplit } = this.props; if (onChangeSplit) { const state = this.cloneState(); onChangeSplit(true, state); } }; onClickTableButton = () => { this.setState( state => { const showingTable = !state.showingTable; if (showingTable) { return { showingTable, queryTransactions: state.queryTransactions }; } // Toggle off needs discarding of table queries const nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Table'); const results = calculateResultsFromQueryTransactions( nextQueryTransactions, state.datasource, state.graphInterval ); return { ...results, queryTransactions: nextQueryTransactions, showingTable }; }, () => { if (this.state.showingTable) { this.onSubmit(); } } ); }; onClickLabel = (key: string, value: string) => { this.onModifyQueries({ type: 'ADD_FILTER', key, value }); }; onModifyQueries = (action, index?: number) => { const { datasource } = this.state; if (datasource && datasource.modifyQuery) { const preventSubmit = action.preventSubmit; this.setState( state => { const { initialQueries, queryTransactions } = state; let nextQueries: DataQuery[]; let nextQueryTransactions; if (index === undefined) { // Modify all queries nextQueries = initialQueries.map((query, i) => ({ ...datasource.modifyQuery(this.modifiedQueries[i], action), ...generateQueryKeys(i), })); // Discard all ongoing transactions nextQueryTransactions = []; } else { // Modify query only at index nextQueries = initialQueries.map((query, i) => { // Synchronise all queries with local query cache to ensure consistency // TODO still needed? return i === index ? { ...datasource.modifyQuery(this.modifiedQueries[i], action), ...generateQueryKeys(i), } : query; }); nextQueryTransactions = queryTransactions // Consume the hint corresponding to the action .map(qt => { if (qt.hints != null && qt.rowIndex === index) { qt.hints = qt.hints.filter(hint => hint.fix.action !== action); } return qt; }) // Preserve previous row query transaction to keep results visible if next query is incomplete .filter(qt => preventSubmit || qt.rowIndex !== index); } this.modifiedQueries = [...nextQueries]; return { initialQueries: nextQueries, queryTransactions: nextQueryTransactions, }; }, // Accepting certain fixes do not result in a well-formed query which should not be submitted !preventSubmit ? () => this.onSubmit() : null ); } }; onRemoveQueryRow = index => { // Remove from local cache this.modifiedQueries = [...this.modifiedQueries.slice(0, index), ...this.modifiedQueries.slice(index + 1)]; this.setState( state => { const { initialQueries, queryTransactions } = state; if (initialQueries.length <= 1) { return null; } // Remove row from react state const nextQueries = [...initialQueries.slice(0, index), ...initialQueries.slice(index + 1)]; // Discard transactions related to row query const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index); const results = calculateResultsFromQueryTransactions( nextQueryTransactions, state.datasource, state.graphInterval ); return { ...results, initialQueries: nextQueries, queryTransactions: nextQueryTransactions, }; }, () => this.onSubmit() ); }; onStartScanning = () => { this.setState({ scanning: true }, this.scanPreviousRange); }; scanPreviousRange = () => { const scanRange = this.timepickerRef.current.move(-1, true); this.setState({ scanRange }); }; onStopScanning = () => { clearTimeout(this.scanTimer); this.setState(state => { const { queryTransactions } = state; const nextQueryTransactions = queryTransactions.filter(qt => qt.scanning && !qt.done); return { queryTransactions: nextQueryTransactions, scanning: false, scanRange: undefined }; }); }; onSubmit = () => { const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state; // Keep table queries first since they need to return quickly if (showingTable && supportsTable) { this.runQueries( 'Table', { format: 'table', instant: true, valueWithRefId: true, }, data => data[0] ); } if (showingGraph && supportsGraph) { this.runQueries( 'Graph', { format: 'time_series', instant: false, }, makeTimeSeriesList ); } if (showingLogs && supportsLogs) { this.runQueries('Logs', { format: 'logs' }); } this.saveState(); }; buildQueryOptions(query: DataQuery, queryOptions: { format: string; hinting?: boolean; instant?: boolean }) { const { datasource, range } = this.state; const { interval, intervalMs } = getIntervals(range, datasource, this.el.offsetWidth); const configuredQueries = [ { ...query, ...queryOptions, }, ]; // Clone range for query request const queryRange: RawTimeRange = { ...range }; // Datasource is using `panelId + query.refId` for cancellation logic. // Using `format` here because it relates to the view panel that the request is for. const panelId = queryOptions.format; return { interval, intervalMs, panelId, targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key. range: queryRange, }; } startQueryTransaction(query: DataQuery, rowIndex: number, resultType: ResultType, options: any): QueryTransaction { const queryOptions = this.buildQueryOptions(query, options); const transaction: QueryTransaction = { query, resultType, rowIndex, id: generateKey(), // reusing for unique ID done: false, latency: 0, options: queryOptions, scanning: this.state.scanning, }; // Using updater style because we might be modifying queryTransactions in quick succession this.setState(state => { const { queryTransactions } = state; // Discarding existing transactions of same type const remainingTransactions = queryTransactions.filter( qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex) ); // Append new transaction const nextQueryTransactions = [...remainingTransactions, transaction]; const results = calculateResultsFromQueryTransactions( nextQueryTransactions, state.datasource, state.graphInterval ); return { ...results, queryTransactions: nextQueryTransactions, showingStartPage: false, }; }); return transaction; } completeQueryTransaction( transactionId: string, result: any, latency: number, queries: DataQuery[], datasourceId: string ) { const { datasource } = this.state; if (datasource.meta.id !== datasourceId) { // Navigated away, queries did not matter return; } this.setState(state => { const { history, queryTransactions, scanning } = state; // Transaction might have been discarded const transaction = queryTransactions.find(qt => qt.id === transactionId); if (!transaction) { return null; } // Get query hints let hints: QueryHint[]; if (datasource.getQueryHints as QueryHintGetter) { hints = datasource.getQueryHints(transaction.query, result); } // Mark transactions as complete const nextQueryTransactions = queryTransactions.map(qt => { if (qt.id === transactionId) { return { ...qt, hints, latency, result, done: true, }; } return qt; }); const results = calculateResultsFromQueryTransactions( nextQueryTransactions, state.datasource, state.graphInterval ); const nextHistory = updateHistory(history, datasourceId, queries); // Keep scanning for results if this was the last scanning transaction if (_.size(result) === 0 && scanning) { const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done); if (!other) { this.scanTimer = setTimeout(this.scanPreviousRange, 1000); } } return { ...results, history: nextHistory, queryTransactions: nextQueryTransactions, }; }); } failQueryTransaction(transactionId: string, response: any, datasourceId: string) { const { datasource } = this.state; if (datasource.meta.id !== datasourceId || response.cancelled) { // Navigated away, queries did not matter return; } console.error(response); let error: string | JSX.Element = response; if (response.data) { if (typeof response.data === 'string') { error = response.data; } else if (response.data.error) { error = response.data.error; if (response.data.response) { error = ( <> <span>{response.data.error}</span> <details>{response.data.response}</details> </> ); } } else { throw new Error('Could not handle error response'); } } this.setState(state => { // Transaction might have been discarded if (!state.queryTransactions.find(qt => qt.id === transactionId)) { return null; } // Mark transactions as complete const nextQueryTransactions = state.queryTransactions.map(qt => { if (qt.id === transactionId) { return { ...qt, error, done: true, }; } return qt; }); return { queryTransactions: nextQueryTransactions, }; }); } async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) { const queries = [...this.modifiedQueries]; if (!hasNonEmptyQuery(queries)) { return; } const { datasource } = this.state; const datasourceId = datasource.meta.id; // Run all queries concurrently queries.forEach(async (query, rowIndex) => { const transaction = this.startQueryTransaction(query, rowIndex, resultType, queryOptions); try { const now = Date.now(); const res = await datasource.query(transaction.options); const latency = Date.now() - now; const results = resultGetter ? resultGetter(res.data) : res.data; this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId); } catch (response) { this.failQueryTransaction(transaction.id, response, datasourceId); } }); } cloneState(): ExploreState { // Copy state, but copy queries including modifications return { ...this.state, queryTransactions: [], initialQueries: [...this.modifiedQueries], }; } saveState = () => { const { stateKey, onSaveState } = this.props; onSaveState(stateKey, this.cloneState()); }; render() { const { position, split } = this.props; const { StartPage, datasource, datasourceError, datasourceLoading, datasourceMissing, exploreDatasources, graphResult, history, initialQueries, logsResult, queryTransactions, range, scanning, scanRange, showingGraph, showingLogs, showingStartPage, showingTable, supportsGraph, supportsLogs, supportsTable, tableResult, } = this.state; const graphHeight = showingGraph && showingTable ? '200px' : '400px'; const exploreClass = split ? 'explore explore-split' : 'explore'; const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined; const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done); const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done); const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done); const loading = queryTransactions.some(qt => !qt.done); return ( <div className={exploreClass} ref={this.getRef}> <div className="navbar"> {position === 'left' ? ( <div> <a className="navbar-page-btn"> <i className="fa fa-rocket" /> Explore </a> </div> ) : ( <div className="navbar-buttons explore-first-button"> <button className="btn navbar-button" onClick={this.onClickCloseSplit}> Close Split </button> </div> )} {!datasourceMissing ? ( <div className="navbar-buttons"> <Select classNamePrefix={`gf-form-select-box`} isMulti={false} isLoading={datasourceLoading} isClearable={false} className="gf-form-input gf-form-input--form-dropdown datasource-picker" onChange={this.onChangeDatasource} options={exploreDatasources} styles={ResetStyles} placeholder="Select datasource" loadingMessage={() => 'Loading datasources...'} noOptionsMessage={() => 'No datasources found'} value={selectedDatasource} components={{ Option: PickerOption, IndicatorsContainer, NoOptionsMessage, }} /> </div> ) : null} <div className="navbar__spacer" /> {position === 'left' && !split ? ( <div className="navbar-buttons"> <button className="btn navbar-button" onClick={this.onClickSplit}> Split </button> </div> ) : null} <TimePicker ref={this.timepickerRef} range={range} onChangeTime={this.onChangeTime} /> <div className="navbar-buttons"> <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}> Clear All </button> </div> <div className="navbar-buttons relative"> <button className="btn navbar-button--primary" onClick={this.onSubmit}> Run Query{' '} {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />} </button> </div> </div> {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null} {datasourceMissing ? ( <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div> ) : null} {datasourceError ? ( <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div> ) : null} {datasource && !datasourceError ? ( <div className="explore-container"> <QueryRows datasource={datasource} history={history} initialQueries={initialQueries} onAddQueryRow={this.onAddQueryRow} onChangeQuery={this.onChangeQuery} onClickHintFix={this.onModifyQueries} onExecuteQuery={this.onSubmit} onRemoveQueryRow={this.onRemoveQueryRow} transactions={queryTransactions} /> <main className="m-t-2"> <ErrorBoundary> {showingStartPage && <StartPage onClickExample={this.onClickExample} />} {!showingStartPage && ( <> {supportsGraph && ( <Panel label="Graph" isOpen={showingGraph} loading={graphLoading} onToggle={this.onClickGraphButton} > <Graph data={graphResult} height={graphHeight} id={`explore-graph-${position}`} onChangeTime={this.onChangeTime} range={range} split={split} /> </Panel> )} {supportsTable && ( <Panel label="Table" loading={tableLoading} isOpen={showingTable} onToggle={this.onClickTableButton} > <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickLabel} /> </Panel> )} {supportsLogs && ( <Panel label="Logs" loading={logsLoading} isOpen={showingLogs} onToggle={this.onClickLogsButton}> <Logs data={logsResult} key={logsResult.id} loading={logsLoading} position={position} onChangeTime={this.onChangeTime} onClickLabel={this.onClickLabel} onStartScanning={this.onStartScanning} onStopScanning={this.onStopScanning} range={range} scanning={scanning} scanRange={scanRange} /> </Panel> )} </> )} </ErrorBoundary> </main> </div> ) : null} </div> ); } } export default hot(module)(Explore);
public/app/features/explore/Explore.tsx
1
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.9964550733566284, 0.07974933087825775, 0.00016429445531684905, 0.0001746270718285814, 0.2565160095691681 ]
{ "id": 3, "code_window": [ " loading: boolean;\n", " position: string;\n", " range?: RawTimeRange;\n", " scanning?: boolean;\n", " scanRange?: RawTimeRange;\n", " onChangeTime?: (range: RawTimeRange) => void;\n", " onClickLabel?: (label: string, value: string) => void;\n", " onStartScanning?: () => void;\n", " onStopScanning?: () => void;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty: boolean;\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "add", "edit_start_line_idx": 142 }
+++ title = "Dashboard List" keywords = ["grafana", "dashboard list", "documentation", "panel", "dashlist"] type = "docs" aliases = ["/reference/dashlist/"] [menu.docs] name = "Dashboard list" parent = "panels" weight = 4 +++ # Dashboard List Panel {{< docs-imagebox img="/img/docs/v45/dashboard-list-panels.png" max-width="850px">}} The dashboard list panel allows you to display dynamic links to other dashboards. The list can be configured to use starred dashboards, recently viewed dashboards, a search query and/or dashboard tags. > On each dashboard load, the dashlist panel will re-query the dashboard list, always providing the most up to date results. ## Dashboard List Options {{< docs-imagebox img="/img/docs/v45/dashboard-list-options.png" class="docs-image--no-shadow docs-image--right">}} 1. **Starred**: The starred dashboard selection displays starred dashboards in alphabetical order. 2. **Recently Viewed**: The recently viewed dashboard selection displays recently viewed dashboards in alphabetical order. 3. **Search**: The search dashboard selection displays dashboards by search query or tag(s). 4. **Show Headings**: When show headings is ticked the chosen list selection(Starred, Recently Viewed, Search) is shown as a heading. 5. **Max Items**: Max items set the maximum of items in a list. 6. **Query**: Here is where you enter your query you want to search by. Queries are case-insensitive, and partial values are accepted. 7. **Tags**: Here is where you enter your tag(s) you want to search by. Note that existing tags will not appear as you type, and *are* case sensitive. To see a list of existing tags, you can always return to the dashboard, open the Dashboard Picker at the top and click `tags` link in the search bar. <div class="clearfix"></div> > When multiple tags and strings appear, the dashboard list will display those matching ALL conditions.
docs/sources/features/panels/dashlist.md
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.00017811177531257272, 0.00017269919044338167, 0.00016643536218907684, 0.00017312480485998094, 0.0000041958451220125426 ]
{ "id": 3, "code_window": [ " loading: boolean;\n", " position: string;\n", " range?: RawTimeRange;\n", " scanning?: boolean;\n", " scanRange?: RawTimeRange;\n", " onChangeTime?: (range: RawTimeRange) => void;\n", " onClickLabel?: (label: string, value: string) => void;\n", " onStartScanning?: () => void;\n", " onStopScanning?: () => void;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty: boolean;\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "add", "edit_start_line_idx": 142 }
package util type DynMap map[string]interface{}
pkg/util/json.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.00017127174942288548, 0.00017127174942288548, 0.00017127174942288548, 0.00017127174942288548, 0 ]
{ "id": 3, "code_window": [ " loading: boolean;\n", " position: string;\n", " range?: RawTimeRange;\n", " scanning?: boolean;\n", " scanRange?: RawTimeRange;\n", " onChangeTime?: (range: RawTimeRange) => void;\n", " onClickLabel?: (label: string, value: string) => void;\n", " onStartScanning?: () => void;\n", " onStopScanning?: () => void;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty: boolean;\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "add", "edit_start_line_idx": 142 }
package core import ( "fmt" "strings" "time" ) type DbType string type Uri struct { DbType DbType Proto string Host string Port string DbName string User string Passwd string Charset string Laddr string Raddr string Timeout time.Duration Schema string } // a dialect is a driver's wrapper type Dialect interface { SetLogger(logger ILogger) Init(*DB, *Uri, string, string) error URI() *Uri DB() *DB DBType() DbType SqlType(*Column) string FormatBytes(b []byte) string DriverName() string DataSourceName() string QuoteStr() string IsReserved(string) bool Quote(string) string AndStr() string OrStr() string EqStr() string RollBackStr() string AutoIncrStr() string SupportInsertMany() bool SupportEngine() bool SupportCharset() bool SupportDropIfExists() bool IndexOnTable() bool ShowCreateNull() bool IndexCheckSql(tableName, idxName string) (string, []interface{}) TableCheckSql(tableName string) (string, []interface{}) IsColumnExist(tableName string, colName string) (bool, error) CreateTableSql(table *Table, tableName, storeEngine, charset string) string DropTableSql(tableName string) string CreateIndexSql(tableName string, index *Index) string DropIndexSql(tableName string, index *Index) string ModifyColumnSql(tableName string, col *Column) string ForUpdateSql(query string) string //CreateTableIfNotExists(table *Table, tableName, storeEngine, charset string) error //MustDropTable(tableName string) error GetColumns(tableName string) ([]string, map[string]*Column, error) GetTables() ([]*Table, error) GetIndexes(tableName string) (map[string]*Index, error) Filters() []Filter } func OpenDialect(dialect Dialect) (*DB, error) { return Open(dialect.DriverName(), dialect.DataSourceName()) } type Base struct { db *DB dialect Dialect driverName string dataSourceName string logger ILogger *Uri } func (b *Base) DB() *DB { return b.db } func (b *Base) SetLogger(logger ILogger) { b.logger = logger } func (b *Base) Init(db *DB, dialect Dialect, uri *Uri, drivername, dataSourceName string) error { b.db, b.dialect, b.Uri = db, dialect, uri b.driverName, b.dataSourceName = drivername, dataSourceName return nil } func (b *Base) URI() *Uri { return b.Uri } func (b *Base) DBType() DbType { return b.Uri.DbType } func (b *Base) FormatBytes(bs []byte) string { return fmt.Sprintf("0x%x", bs) } func (b *Base) DriverName() string { return b.driverName } func (b *Base) ShowCreateNull() bool { return true } func (b *Base) DataSourceName() string { return b.dataSourceName } func (b *Base) AndStr() string { return "AND" } func (b *Base) OrStr() string { return "OR" } func (b *Base) EqStr() string { return "=" } func (db *Base) RollBackStr() string { return "ROLL BACK" } func (db *Base) SupportDropIfExists() bool { return true } func (db *Base) DropTableSql(tableName string) string { return fmt.Sprintf("DROP TABLE IF EXISTS `%s`", tableName) } func (db *Base) HasRecords(query string, args ...interface{}) (bool, error) { db.LogSQL(query, args) rows, err := db.DB().Query(query, args...) if err != nil { return false, err } defer rows.Close() if rows.Next() { return true, nil } return false, nil } func (db *Base) IsColumnExist(tableName, colName string) (bool, error) { query := "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ?" query = strings.Replace(query, "`", db.dialect.QuoteStr(), -1) return db.HasRecords(query, db.DbName, tableName, colName) } /* func (db *Base) CreateTableIfNotExists(table *Table, tableName, storeEngine, charset string) error { sql, args := db.dialect.TableCheckSql(tableName) rows, err := db.DB().Query(sql, args...) if db.Logger != nil { db.Logger.Info("[sql]", sql, args) } if err != nil { return err } defer rows.Close() if rows.Next() { return nil } sql = db.dialect.CreateTableSql(table, tableName, storeEngine, charset) _, err = db.DB().Exec(sql) if db.Logger != nil { db.Logger.Info("[sql]", sql) } return err }*/ func (db *Base) CreateIndexSql(tableName string, index *Index) string { quote := db.dialect.Quote var unique string var idxName string if index.Type == UniqueType { unique = " UNIQUE" } idxName = index.XName(tableName) return fmt.Sprintf("CREATE%s INDEX %v ON %v (%v)", unique, quote(idxName), quote(tableName), quote(strings.Join(index.Cols, quote(",")))) } func (db *Base) DropIndexSql(tableName string, index *Index) string { quote := db.dialect.Quote var name string if index.IsRegular { name = index.XName(tableName) } else { name = index.Name } return fmt.Sprintf("DROP INDEX %v ON %s", quote(name), quote(tableName)) } func (db *Base) ModifyColumnSql(tableName string, col *Column) string { return fmt.Sprintf("alter table %s MODIFY COLUMN %s", tableName, col.StringNoPk(db.dialect)) } func (b *Base) CreateTableSql(table *Table, tableName, storeEngine, charset string) string { var sql string sql = "CREATE TABLE IF NOT EXISTS " if tableName == "" { tableName = table.Name } sql += b.dialect.Quote(tableName) sql += " (" if len(table.ColumnsSeq()) > 0 { pkList := table.PrimaryKeys for _, colName := range table.ColumnsSeq() { col := table.GetColumn(colName) if col.IsPrimaryKey && len(pkList) == 1 { sql += col.String(b.dialect) } else { sql += col.StringNoPk(b.dialect) } sql = strings.TrimSpace(sql) if b.DriverName() == MYSQL && len(col.Comment) > 0 { sql += " COMMENT '" + col.Comment + "'" } sql += ", " } if len(pkList) > 1 { sql += "PRIMARY KEY ( " sql += b.dialect.Quote(strings.Join(pkList, b.dialect.Quote(","))) sql += " ), " } sql = sql[:len(sql)-2] } sql += ")" if b.dialect.SupportEngine() && storeEngine != "" { sql += " ENGINE=" + storeEngine } if b.dialect.SupportCharset() { if len(charset) == 0 { charset = b.dialect.URI().Charset } if len(charset) > 0 { sql += " DEFAULT CHARSET " + charset } } return sql } func (b *Base) ForUpdateSql(query string) string { return query + " FOR UPDATE" } func (b *Base) LogSQL(sql string, args []interface{}) { if b.logger != nil && b.logger.IsShowSQL() { if len(args) > 0 { b.logger.Infof("[SQL] %v %v", sql, args) } else { b.logger.Infof("[SQL] %v", sql) } } } var ( dialects = map[string]func() Dialect{} ) // RegisterDialect register database dialect func RegisterDialect(dbName DbType, dialectFunc func() Dialect) { if dialectFunc == nil { panic("core: Register dialect is nil") } dialects[strings.ToLower(string(dbName))] = dialectFunc // !nashtsai! allow override dialect } // QueryDialect query if registed database dialect func QueryDialect(dbName DbType) Dialect { if d, ok := dialects[strings.ToLower(string(dbName))]; ok { return d() } return nil }
vendor/github.com/go-xorm/core/dialect.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.0001770835224306211, 0.00016995513578876853, 0.00016361408052034676, 0.00016933816368691623, 0.000004051347332278965 ]
{ "id": 4, "code_window": [ " this.props.onStopScanning();\n", " };\n", "\n", " render() {\n", " const { className = '', data, loading = false, onClickLabel, position, range, scanning, scanRange } = this.props;\n", " const { dedup, deferLogs, hiddenLogLevels, renderAll, showLocalTime, showUtc } = this.state;\n", " let { showLabels } = this.state;\n", " const hasData = data && data.rows && data.rows.length > 0;\n", "\n", " // Filtering\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const {\n", " className = '',\n", " data,\n", " loading = false,\n", " onClickLabel,\n", " position,\n", " range,\n", " scanning,\n", " scanRange,\n", " queryEmpty,\n", " } = this.props;\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "replace", "edit_start_line_idx": 241 }
import _ from 'lodash'; import React, { PureComponent } from 'react'; import Highlighter from 'react-highlight-words'; import * as rangeUtil from 'app/core/utils/rangeutil'; import { RawTimeRange } from 'app/types/series'; import { LogsDedupStrategy, LogsModel, dedupLogRows, filterLogLevels, LogLevel, LogsStreamLabels, LogsMetaKind, LogRow, } from 'app/core/logs_model'; import { findHighlightChunksInText } from 'app/core/utils/text'; import { Switch } from 'app/core/components/Switch/Switch'; import Graph from './Graph'; const PREVIEW_LIMIT = 100; const graphOptions = { series: { bars: { show: true, lineWidth: 5, // barWidth: 10, }, // stack: true, }, yaxis: { tickDecimals: 0, }, }; function renderMetaItem(value: any, kind: LogsMetaKind) { if (kind === LogsMetaKind.LabelsMap) { return ( <span className="logs-meta-item__value-labels"> <Labels labels={value} /> </span> ); } return value; } class Label extends PureComponent<{ label: string; value: string; onClickLabel?: (label: string, value: string) => void; }> { onClickLabel = () => { const { onClickLabel, label, value } = this.props; if (onClickLabel) { onClickLabel(label, value); } }; render() { const { label, value } = this.props; const tooltip = `${label}: ${value}`; return ( <span className="logs-label" title={tooltip} onClick={this.onClickLabel}> {value} </span> ); } } class Labels extends PureComponent<{ labels: LogsStreamLabels; onClickLabel?: (label: string, value: string) => void; }> { render() { const { labels, onClickLabel } = this.props; return Object.keys(labels).map(key => ( <Label key={key} label={key} value={labels[key]} onClickLabel={onClickLabel} /> )); } } interface RowProps { row: LogRow; showLabels: boolean | null; // Tristate: null means auto showLocalTime: boolean; showUtc: boolean; onClickLabel?: (label: string, value: string) => void; } function Row({ onClickLabel, row, showLabels, showLocalTime, showUtc }: RowProps) { const needsHighlighter = row.searchWords && row.searchWords.length > 0; return ( <div className="logs-row"> <div className={row.logLevel ? `logs-row-level logs-row-level-${row.logLevel}` : ''}> {row.duplicates > 0 && ( <div className="logs-row-level__duplicates" title={`${row.duplicates} duplicates`}> {Array.apply(null, { length: row.duplicates }).map((bogus, index) => ( <div className="logs-row-level__duplicate" key={`${index}`} /> ))} </div> )} </div> {showUtc && ( <div className="logs-row-time" title={`Local: ${row.timeLocal} (${row.timeFromNow})`}> {row.timestamp} </div> )} {showLocalTime && ( <div className="logs-row-time" title={`${row.timestamp} (${row.timeFromNow})`}> {row.timeLocal} </div> )} {showLabels && ( <div className="logs-row-labels"> <Labels labels={row.uniqueLabels} onClickLabel={onClickLabel} /> </div> )} <div className="logs-row-message"> {needsHighlighter ? ( <Highlighter textToHighlight={row.entry} searchWords={row.searchWords} findChunks={findHighlightChunksInText} highlightClassName="logs-row-match-highlight" /> ) : ( row.entry )} </div> </div> ); } interface LogsProps { className?: string; data: LogsModel; loading: boolean; position: string; range?: RawTimeRange; scanning?: boolean; scanRange?: RawTimeRange; onChangeTime?: (range: RawTimeRange) => void; onClickLabel?: (label: string, value: string) => void; onStartScanning?: () => void; onStopScanning?: () => void; } interface LogsState { dedup: LogsDedupStrategy; deferLogs: boolean; hiddenLogLevels: Set<LogLevel>; renderAll: boolean; showLabels: boolean | null; // Tristate: null means auto showLocalTime: boolean; showUtc: boolean; } export default class Logs extends PureComponent<LogsProps, LogsState> { deferLogsTimer: NodeJS.Timer; renderAllTimer: NodeJS.Timer; state = { dedup: LogsDedupStrategy.none, deferLogs: true, hiddenLogLevels: new Set(), renderAll: false, showLabels: null, showLocalTime: true, showUtc: false, }; componentDidMount() { // Staged rendering if (this.state.deferLogs) { const { data } = this.props; const rowCount = data && data.rows ? data.rows.length : 0; // Render all right away if not too far over the limit const renderAll = rowCount <= PREVIEW_LIMIT * 2; this.deferLogsTimer = setTimeout(() => this.setState({ deferLogs: false, renderAll }), rowCount); } } componentDidUpdate(prevProps, prevState) { // Staged rendering if (prevState.deferLogs && !this.state.deferLogs && !this.state.renderAll) { this.renderAllTimer = setTimeout(() => this.setState({ renderAll: true }), 2000); } } componentWillUnmount() { clearTimeout(this.deferLogsTimer); clearTimeout(this.renderAllTimer); } onChangeDedup = (dedup: LogsDedupStrategy) => { this.setState(prevState => { if (prevState.dedup === dedup) { return { dedup: LogsDedupStrategy.none }; } return { dedup }; }); }; onChangeLabels = (event: React.SyntheticEvent) => { const target = event.target as HTMLInputElement; this.setState({ showLabels: target.checked, }); }; onChangeLocalTime = (event: React.SyntheticEvent) => { const target = event.target as HTMLInputElement; this.setState({ showLocalTime: target.checked, }); }; onChangeUtc = (event: React.SyntheticEvent) => { const target = event.target as HTMLInputElement; this.setState({ showUtc: target.checked, }); }; onToggleLogLevel = (rawLevel: string, hiddenRawLevels: Set<string>) => { const hiddenLogLevels: Set<LogLevel> = new Set(Array.from(hiddenRawLevels).map(level => LogLevel[level])); this.setState({ hiddenLogLevels }); }; onClickScan = (event: React.SyntheticEvent) => { event.preventDefault(); this.props.onStartScanning(); }; onClickStopScan = (event: React.SyntheticEvent) => { event.preventDefault(); this.props.onStopScanning(); }; render() { const { className = '', data, loading = false, onClickLabel, position, range, scanning, scanRange } = this.props; const { dedup, deferLogs, hiddenLogLevels, renderAll, showLocalTime, showUtc } = this.state; let { showLabels } = this.state; const hasData = data && data.rows && data.rows.length > 0; // Filtering const filteredData = filterLogLevels(data, hiddenLogLevels); const dedupedData = dedupLogRows(filteredData, dedup); const dedupCount = dedupedData.rows.reduce((sum, row) => sum + row.duplicates, 0); const meta = [...data.meta]; if (dedup !== LogsDedupStrategy.none) { meta.push({ label: 'Dedup count', value: dedupCount, kind: LogsMetaKind.Number, }); } // Staged rendering const firstRows = dedupedData.rows.slice(0, PREVIEW_LIMIT); const lastRows = dedupedData.rows.slice(PREVIEW_LIMIT); // Check for labels if (showLabels === null) { if (hasData) { showLabels = data.rows.some(row => _.size(row.uniqueLabels) > 0); } else { showLabels = true; } } const scanText = scanRange ? `Scanning ${rangeUtil.describeTimeRange(scanRange)}` : 'Scanning...'; return ( <div className={`${className} logs`}> <div className="logs-graph"> <Graph data={data.series} height="100px" range={range} id={`explore-logs-graph-${position}`} onChangeTime={this.props.onChangeTime} onToggleSeries={this.onToggleLogLevel} userOptions={graphOptions} /> </div> <div className="logs-options"> <div className="logs-controls"> <Switch label="Timestamp" checked={showUtc} onChange={this.onChangeUtc} small /> <Switch label="Local time" checked={showLocalTime} onChange={this.onChangeLocalTime} small /> <Switch label="Labels" checked={showLabels} onChange={this.onChangeLabels} small /> <Switch label="Dedup: off" checked={dedup === LogsDedupStrategy.none} onChange={() => this.onChangeDedup(LogsDedupStrategy.none)} small /> <Switch label="Dedup: exact" checked={dedup === LogsDedupStrategy.exact} onChange={() => this.onChangeDedup(LogsDedupStrategy.exact)} small /> <Switch label="Dedup: numbers" checked={dedup === LogsDedupStrategy.numbers} onChange={() => this.onChangeDedup(LogsDedupStrategy.numbers)} small /> <Switch label="Dedup: signature" checked={dedup === LogsDedupStrategy.signature} onChange={() => this.onChangeDedup(LogsDedupStrategy.signature)} small /> {hasData && meta && ( <div className="logs-meta"> {meta.map(item => ( <div className="logs-meta-item" key={item.label}> <span className="logs-meta-item__label">{item.label}:</span> <span className="logs-meta-item__value">{renderMetaItem(item.value, item.kind)}</span> </div> ))} </div> )} </div> </div> <div className="logs-entries"> {hasData && !deferLogs && firstRows.map(row => ( <Row key={row.key + row.duplicates} row={row} showLabels={showLabels} showLocalTime={showLocalTime} showUtc={showUtc} onClickLabel={onClickLabel} /> ))} {hasData && !deferLogs && renderAll && lastRows.map(row => ( <Row key={row.key + row.duplicates} row={row} showLabels={showLabels} showLocalTime={showLocalTime} showUtc={showUtc} onClickLabel={onClickLabel} /> ))} {hasData && deferLogs && <span>Rendering {dedupedData.rows.length} rows...</span>} </div> {!loading && data.queryEmpty && !scanning && ( <div className="logs-nodata"> No logs found. <a className="link" onClick={this.onClickScan}> Scan for older logs </a> </div> )} {scanning && ( <div className="logs-nodata"> <span>{scanText}</span> <a className="link" onClick={this.onClickStopScan}> Stop scan </a> </div> )} </div> ); } }
public/app/features/explore/Logs.tsx
1
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.9991568326950073, 0.674400269985199, 0.00016621412942185998, 0.9965721368789673, 0.44334328174591064 ]
{ "id": 4, "code_window": [ " this.props.onStopScanning();\n", " };\n", "\n", " render() {\n", " const { className = '', data, loading = false, onClickLabel, position, range, scanning, scanRange } = this.props;\n", " const { dedup, deferLogs, hiddenLogLevels, renderAll, showLocalTime, showUtc } = this.state;\n", " let { showLabels } = this.state;\n", " const hasData = data && data.rows && data.rows.length > 0;\n", "\n", " // Filtering\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const {\n", " className = '',\n", " data,\n", " loading = false,\n", " onClickLabel,\n", " position,\n", " range,\n", " scanning,\n", " scanRange,\n", " queryEmpty,\n", " } = this.props;\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "replace", "edit_start_line_idx": 241 }
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto /* * Routines for encoding data into the wire format for protocol buffers. */ import ( "fmt" "log" "os" "reflect" "sort" "strconv" "strings" "sync" ) const debug bool = false // Constants that identify the encoding of a value on the wire. const ( WireVarint = 0 WireFixed64 = 1 WireBytes = 2 WireStartGroup = 3 WireEndGroup = 4 WireFixed32 = 5 ) // tagMap is an optimization over map[int]int for typical protocol buffer // use-cases. Encoded protocol buffers are often in tag order with small tag // numbers. type tagMap struct { fastTags []int slowTags map[int]int } // tagMapFastLimit is the upper bound on the tag number that will be stored in // the tagMap slice rather than its map. const tagMapFastLimit = 1024 func (p *tagMap) get(t int) (int, bool) { if t > 0 && t < tagMapFastLimit { if t >= len(p.fastTags) { return 0, false } fi := p.fastTags[t] return fi, fi >= 0 } fi, ok := p.slowTags[t] return fi, ok } func (p *tagMap) put(t int, fi int) { if t > 0 && t < tagMapFastLimit { for len(p.fastTags) < t+1 { p.fastTags = append(p.fastTags, -1) } p.fastTags[t] = fi return } if p.slowTags == nil { p.slowTags = make(map[int]int) } p.slowTags[t] = fi } // StructProperties represents properties for all the fields of a struct. // decoderTags and decoderOrigNames should only be used by the decoder. type StructProperties struct { Prop []*Properties // properties for each field reqCount int // required count decoderTags tagMap // map from proto tag to struct field number decoderOrigNames map[string]int // map from original name to struct field number order []int // list of struct field numbers in tag order // OneofTypes contains information about the oneof fields in this message. // It is keyed by the original name of a field. OneofTypes map[string]*OneofProperties } // OneofProperties represents information about a specific field in a oneof. type OneofProperties struct { Type reflect.Type // pointer to generated struct type for this oneof field Field int // struct field number of the containing oneof in the message Prop *Properties } // Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. // See encode.go, (*Buffer).enc_struct. func (sp *StructProperties) Len() int { return len(sp.order) } func (sp *StructProperties) Less(i, j int) bool { return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag } func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } // Properties represents the protocol-specific behavior of a single struct field. type Properties struct { Name string // name of the field, for error messages OrigName string // original name before protocol compiler (always set) JSONName string // name to use for JSON; determined by protoc Wire string WireType int Tag int Required bool Optional bool Repeated bool Packed bool // relevant for repeated primitives only Enum string // set for enum types only proto3 bool // whether this is known to be a proto3 field; set for []byte only oneof bool // whether this is a oneof field Default string // default value HasDefault bool // whether an explicit default was provided stype reflect.Type // set for struct types only sprop *StructProperties // set for struct types only mtype reflect.Type // set for map types only mkeyprop *Properties // set for map types only mvalprop *Properties // set for map types only } // String formats the properties in the protobuf struct field tag style. func (p *Properties) String() string { s := p.Wire s += "," s += strconv.Itoa(p.Tag) if p.Required { s += ",req" } if p.Optional { s += ",opt" } if p.Repeated { s += ",rep" } if p.Packed { s += ",packed" } s += ",name=" + p.OrigName if p.JSONName != p.OrigName { s += ",json=" + p.JSONName } if p.proto3 { s += ",proto3" } if p.oneof { s += ",oneof" } if len(p.Enum) > 0 { s += ",enum=" + p.Enum } if p.HasDefault { s += ",def=" + p.Default } return s } // Parse populates p by parsing a string in the protobuf struct field tag style. func (p *Properties) Parse(s string) { // "bytes,49,opt,name=foo,def=hello!" fields := strings.Split(s, ",") // breaks def=, but handled below. if len(fields) < 2 { fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) return } p.Wire = fields[0] switch p.Wire { case "varint": p.WireType = WireVarint case "fixed32": p.WireType = WireFixed32 case "fixed64": p.WireType = WireFixed64 case "zigzag32": p.WireType = WireVarint case "zigzag64": p.WireType = WireVarint case "bytes", "group": p.WireType = WireBytes // no numeric converter for non-numeric types default: fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) return } var err error p.Tag, err = strconv.Atoi(fields[1]) if err != nil { return } outer: for i := 2; i < len(fields); i++ { f := fields[i] switch { case f == "req": p.Required = true case f == "opt": p.Optional = true case f == "rep": p.Repeated = true case f == "packed": p.Packed = true case strings.HasPrefix(f, "name="): p.OrigName = f[5:] case strings.HasPrefix(f, "json="): p.JSONName = f[5:] case strings.HasPrefix(f, "enum="): p.Enum = f[5:] case f == "proto3": p.proto3 = true case f == "oneof": p.oneof = true case strings.HasPrefix(f, "def="): p.HasDefault = true p.Default = f[4:] // rest of string if i+1 < len(fields) { // Commas aren't escaped, and def is always last. p.Default += "," + strings.Join(fields[i+1:], ",") break outer } } } } var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() // setFieldProps initializes the field properties for submessages and maps. func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { switch t1 := typ; t1.Kind() { case reflect.Ptr: if t1.Elem().Kind() == reflect.Struct { p.stype = t1.Elem() } case reflect.Slice: if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct { p.stype = t2.Elem() } case reflect.Map: p.mtype = t1 p.mkeyprop = &Properties{} p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) p.mvalprop = &Properties{} vtype := p.mtype.Elem() if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { // The value type is not a message (*T) or bytes ([]byte), // so we need encoders for the pointer to this type. vtype = reflect.PtrTo(vtype) } p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) } if p.stype != nil { if lockGetProp { p.sprop = GetProperties(p.stype) } else { p.sprop = getPropertiesLocked(p.stype) } } } var ( marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() ) // Init populates the properties from a protocol buffer struct tag. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { p.init(typ, name, tag, f, true) } func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { // "bytes,49,opt,def=hello!" p.Name = name p.OrigName = name if tag == "" { return } p.Parse(tag) p.setFieldProps(typ, f, lockGetProp) } var ( propertiesMu sync.RWMutex propertiesMap = make(map[reflect.Type]*StructProperties) ) // GetProperties returns the list of properties for the type represented by t. // t must represent a generated struct type of a protocol message. func GetProperties(t reflect.Type) *StructProperties { if t.Kind() != reflect.Struct { panic("proto: type must have kind struct") } // Most calls to GetProperties in a long-running program will be // retrieving details for types we have seen before. propertiesMu.RLock() sprop, ok := propertiesMap[t] propertiesMu.RUnlock() if ok { if collectStats { stats.Chit++ } return sprop } propertiesMu.Lock() sprop = getPropertiesLocked(t) propertiesMu.Unlock() return sprop } // getPropertiesLocked requires that propertiesMu is held. func getPropertiesLocked(t reflect.Type) *StructProperties { if prop, ok := propertiesMap[t]; ok { if collectStats { stats.Chit++ } return prop } if collectStats { stats.Cmiss++ } prop := new(StructProperties) // in case of recursive protos, fill this in now. propertiesMap[t] = prop // build properties prop.Prop = make([]*Properties, t.NumField()) prop.order = make([]int, t.NumField()) for i := 0; i < t.NumField(); i++ { f := t.Field(i) p := new(Properties) name := f.Name p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) oneof := f.Tag.Get("protobuf_oneof") // special case if oneof != "" { // Oneof fields don't use the traditional protobuf tag. p.OrigName = oneof } prop.Prop[i] = p prop.order[i] = i if debug { print(i, " ", f.Name, " ", t.String(), " ") if p.Tag > 0 { print(p.String()) } print("\n") } } // Re-order prop.order. sort.Sort(prop) type oneofMessage interface { XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) } if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { var oots []interface{} _, _, _, oots = om.XXX_OneofFuncs() // Interpret oneof metadata. prop.OneofTypes = make(map[string]*OneofProperties) for _, oot := range oots { oop := &OneofProperties{ Type: reflect.ValueOf(oot).Type(), // *T Prop: new(Properties), } sft := oop.Type.Elem().Field(0) oop.Prop.Name = sft.Name oop.Prop.Parse(sft.Tag.Get("protobuf")) // There will be exactly one interface field that // this new value is assignable to. for i := 0; i < t.NumField(); i++ { f := t.Field(i) if f.Type.Kind() != reflect.Interface { continue } if !oop.Type.AssignableTo(f.Type) { continue } oop.Field = i break } prop.OneofTypes[oop.Prop.OrigName] = oop } } // build required counts // build tags reqCount := 0 prop.decoderOrigNames = make(map[string]int) for i, p := range prop.Prop { if strings.HasPrefix(p.Name, "XXX_") { // Internal fields should not appear in tags/origNames maps. // They are handled specially when encoding and decoding. continue } if p.Required { reqCount++ } prop.decoderTags.put(p.Tag, i) prop.decoderOrigNames[p.OrigName] = i } prop.reqCount = reqCount return prop } // A global registry of enum types. // The generated code will register the generated maps by calling RegisterEnum. var enumValueMaps = make(map[string]map[string]int32) // RegisterEnum is called from the generated code to install the enum descriptor // maps into the global table to aid parsing text format protocol buffers. func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { if _, ok := enumValueMaps[typeName]; ok { panic("proto: duplicate enum registered: " + typeName) } enumValueMaps[typeName] = valueMap } // EnumValueMap returns the mapping from names to integers of the // enum type enumType, or a nil if not found. func EnumValueMap(enumType string) map[string]int32 { return enumValueMaps[enumType] } // A registry of all linked message types. // The string is a fully-qualified proto name ("pkg.Message"). var ( protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types revProtoTypes = make(map[reflect.Type]string) ) // RegisterType is called from generated code and maps from the fully qualified // proto name to the type (pointer to struct) of the protocol buffer. func RegisterType(x Message, name string) { if _, ok := protoTypedNils[name]; ok { // TODO: Some day, make this a panic. log.Printf("proto: duplicate proto type registered: %s", name) return } t := reflect.TypeOf(x) if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { // Generated code always calls RegisterType with nil x. // This check is just for extra safety. protoTypedNils[name] = x } else { protoTypedNils[name] = reflect.Zero(t).Interface().(Message) } revProtoTypes[t] = name } // RegisterMapType is called from generated code and maps from the fully qualified // proto name to the native map type of the proto map definition. func RegisterMapType(x interface{}, name string) { if reflect.TypeOf(x).Kind() != reflect.Map { panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) } if _, ok := protoMapTypes[name]; ok { log.Printf("proto: duplicate proto type registered: %s", name) return } t := reflect.TypeOf(x) protoMapTypes[name] = t revProtoTypes[t] = name } // MessageName returns the fully-qualified proto name for the given message type. func MessageName(x Message) string { type xname interface { XXX_MessageName() string } if m, ok := x.(xname); ok { return m.XXX_MessageName() } return revProtoTypes[reflect.TypeOf(x)] } // MessageType returns the message type (pointer to struct) for a named message. // The type is not guaranteed to implement proto.Message if the name refers to a // map entry. func MessageType(name string) reflect.Type { if t, ok := protoTypedNils[name]; ok { return reflect.TypeOf(t) } return protoMapTypes[name] } // A registry of all linked proto files. var ( protoFiles = make(map[string][]byte) // file name => fileDescriptor ) // RegisterFile is called from generated code and maps from the // full file name of a .proto file to its compressed FileDescriptorProto. func RegisterFile(filename string, fileDescriptor []byte) { protoFiles[filename] = fileDescriptor } // FileDescriptor returns the compressed FileDescriptorProto for a .proto file. func FileDescriptor(filename string) []byte { return protoFiles[filename] }
vendor/github.com/golang/protobuf/proto/properties.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.0002329285634914413, 0.000173243650351651, 0.00016278529074043036, 0.00017255180864594877, 0.000009496456186752766 ]
{ "id": 4, "code_window": [ " this.props.onStopScanning();\n", " };\n", "\n", " render() {\n", " const { className = '', data, loading = false, onClickLabel, position, range, scanning, scanRange } = this.props;\n", " const { dedup, deferLogs, hiddenLogLevels, renderAll, showLocalTime, showUtc } = this.state;\n", " let { showLabels } = this.state;\n", " const hasData = data && data.rows && data.rows.length > 0;\n", "\n", " // Filtering\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const {\n", " className = '',\n", " data,\n", " loading = false,\n", " onClickLabel,\n", " position,\n", " range,\n", " scanning,\n", " scanRange,\n", " queryEmpty,\n", " } = this.props;\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "replace", "edit_start_line_idx": 241 }
// Copyright 2016 The XORM Authors. All rights reserved. // Use of this source code is governed by a BSD // license that can be found in the LICENSE file. /* Package builder is a simple and powerful sql builder for Go. Make sure you have installed Go 1.1+ and then: go get github.com/go-xorm/builder WARNNING: Currently, only query conditions are supported. Below is the supported conditions. 1. Eq is a redefine of a map, you can give one or more conditions to Eq import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(Eq{"a":1}) // a=? [1] sql, args, _ := ToSQL(Eq{"b":"c"}.And(Eq{"c": 0})) // b=? AND c=? ["c", 0] sql, args, _ := ToSQL(Eq{"b":"c", "c":0}) // b=? AND c=? ["c", 0] sql, args, _ := ToSQL(Eq{"b":"c"}.Or(Eq{"b":"d"})) // b=? OR b=? ["c", "d"] sql, args, _ := ToSQL(Eq{"b": []string{"c", "d"}}) // b IN (?,?) ["c", "d"] sql, args, _ := ToSQL(Eq{"b": 1, "c":[]int{2, 3}}) // b=? AND c IN (?,?) [1, 2, 3] 2. Neq is the same to Eq import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(Neq{"a":1}) // a<>? [1] sql, args, _ := ToSQL(Neq{"b":"c"}.And(Neq{"c": 0})) // b<>? AND c<>? ["c", 0] sql, args, _ := ToSQL(Neq{"b":"c", "c":0}) // b<>? AND c<>? ["c", 0] sql, args, _ := ToSQL(Neq{"b":"c"}.Or(Neq{"b":"d"})) // b<>? OR b<>? ["c", "d"] sql, args, _ := ToSQL(Neq{"b": []string{"c", "d"}}) // b NOT IN (?,?) ["c", "d"] sql, args, _ := ToSQL(Neq{"b": 1, "c":[]int{2, 3}}) // b<>? AND c NOT IN (?,?) [1, 2, 3] 3. Gt, Gte, Lt, Lte import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(Gt{"a", 1}.And(Gte{"b", 2})) // a>? AND b>=? [1, 2] sql, args, _ := ToSQL(Lt{"a", 1}.Or(Lte{"b", 2})) // a<? OR b<=? [1, 2] 4. Like import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(Like{"a", "c"}) // a LIKE ? [%c%] 5. Expr you can customerize your sql with Expr import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(Expr("a = ? ", 1)) // a = ? [1] sql, args, _ := ToSQL(Eq{"a": Expr("select id from table where c = ?", 1)}) // a=(select id from table where c = ?) [1] 6. In and NotIn import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(In("a", 1, 2, 3)) // a IN (?,?,?) [1,2,3] sql, args, _ := ToSQL(In("a", []int{1, 2, 3})) // a IN (?,?,?) [1,2,3] sql, args, _ := ToSQL(In("a", Expr("select id from b where c = ?", 1)))) // a IN (select id from b where c = ?) [1] 7. IsNull and NotNull import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(IsNull{"a"}) // a IS NULL [] sql, args, _ := ToSQL(NotNull{"b"}) // b IS NOT NULL [] 8. And(conds ...Cond), And can connect one or more condtions via AND import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(And(Eq{"a":1}, Like{"b", "c"}, Neq{"d", 2})) // a=? AND b LIKE ? AND d<>? [1, %c%, 2] 9. Or(conds ...Cond), Or can connect one or more conditions via Or import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(Or(Eq{"a":1}, Like{"b", "c"}, Neq{"d", 2})) // a=? OR b LIKE ? OR d<>? [1, %c%, 2] sql, args, _ := ToSQL(Or(Eq{"a":1}, And(Like{"b", "c"}, Neq{"d", 2}))) // a=? OR (b LIKE ? AND d<>?) [1, %c%, 2] 10. Between import . "github.com/go-xorm/builder" sql, args, _ := ToSQL(Between("a", 1, 2)) // a BETWEEN 1 AND 2 11. define yourself conditions Since Cond is a interface, you can define yourself conditions and compare with them */ package builder
vendor/github.com/go-xorm/builder/doc.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.00017801141075324267, 0.00017496444343123585, 0.00016794762632343918, 0.00017522636335343122, 0.000002537178488637437 ]
{ "id": 4, "code_window": [ " this.props.onStopScanning();\n", " };\n", "\n", " render() {\n", " const { className = '', data, loading = false, onClickLabel, position, range, scanning, scanRange } = this.props;\n", " const { dedup, deferLogs, hiddenLogLevels, renderAll, showLocalTime, showUtc } = this.state;\n", " let { showLabels } = this.state;\n", " const hasData = data && data.rows && data.rows.length > 0;\n", "\n", " // Filtering\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const {\n", " className = '',\n", " data,\n", " loading = false,\n", " onClickLabel,\n", " position,\n", " range,\n", " scanning,\n", " scanRange,\n", " queryEmpty,\n", " } = this.props;\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "replace", "edit_start_line_idx": 241 }
// Copyright 2015 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package expfmt import ( "fmt" "io" "math" "mime" "net/http" dto "github.com/prometheus/client_model/go" "github.com/matttproud/golang_protobuf_extensions/pbutil" "github.com/prometheus/common/model" ) // Decoder types decode an input stream into metric families. type Decoder interface { Decode(*dto.MetricFamily) error } // DecodeOptions contains options used by the Decoder and in sample extraction. type DecodeOptions struct { // Timestamp is added to each value from the stream that has no explicit timestamp set. Timestamp model.Time } // ResponseFormat extracts the correct format from a HTTP response header. // If no matching format can be found FormatUnknown is returned. func ResponseFormat(h http.Header) Format { ct := h.Get(hdrContentType) mediatype, params, err := mime.ParseMediaType(ct) if err != nil { return FmtUnknown } const textType = "text/plain" switch mediatype { case ProtoType: if p, ok := params["proto"]; ok && p != ProtoProtocol { return FmtUnknown } if e, ok := params["encoding"]; ok && e != "delimited" { return FmtUnknown } return FmtProtoDelim case textType: if v, ok := params["version"]; ok && v != TextVersion { return FmtUnknown } return FmtText } return FmtUnknown } // NewDecoder returns a new decoder based on the given input format. // If the input format does not imply otherwise, a text format decoder is returned. func NewDecoder(r io.Reader, format Format) Decoder { switch format { case FmtProtoDelim: return &protoDecoder{r: r} } return &textDecoder{r: r} } // protoDecoder implements the Decoder interface for protocol buffers. type protoDecoder struct { r io.Reader } // Decode implements the Decoder interface. func (d *protoDecoder) Decode(v *dto.MetricFamily) error { _, err := pbutil.ReadDelimited(d.r, v) if err != nil { return err } if !model.IsValidMetricName(model.LabelValue(v.GetName())) { return fmt.Errorf("invalid metric name %q", v.GetName()) } for _, m := range v.GetMetric() { if m == nil { continue } for _, l := range m.GetLabel() { if l == nil { continue } if !model.LabelValue(l.GetValue()).IsValid() { return fmt.Errorf("invalid label value %q", l.GetValue()) } if !model.LabelName(l.GetName()).IsValid() { return fmt.Errorf("invalid label name %q", l.GetName()) } } } return nil } // textDecoder implements the Decoder interface for the text protocol. type textDecoder struct { r io.Reader p TextParser fams []*dto.MetricFamily } // Decode implements the Decoder interface. func (d *textDecoder) Decode(v *dto.MetricFamily) error { // TODO(fabxc): Wrap this as a line reader to make streaming safer. if len(d.fams) == 0 { // No cached metric families, read everything and parse metrics. fams, err := d.p.TextToMetricFamilies(d.r) if err != nil { return err } if len(fams) == 0 { return io.EOF } d.fams = make([]*dto.MetricFamily, 0, len(fams)) for _, f := range fams { d.fams = append(d.fams, f) } } *v = *d.fams[0] d.fams = d.fams[1:] return nil } // SampleDecoder wraps a Decoder to extract samples from the metric families // decoded by the wrapped Decoder. type SampleDecoder struct { Dec Decoder Opts *DecodeOptions f dto.MetricFamily } // Decode calls the Decode method of the wrapped Decoder and then extracts the // samples from the decoded MetricFamily into the provided model.Vector. func (sd *SampleDecoder) Decode(s *model.Vector) error { err := sd.Dec.Decode(&sd.f) if err != nil { return err } *s, err = extractSamples(&sd.f, sd.Opts) return err } // ExtractSamples builds a slice of samples from the provided metric // families. If an error occurrs during sample extraction, it continues to // extract from the remaining metric families. The returned error is the last // error that has occurred. func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) (model.Vector, error) { var ( all model.Vector lastErr error ) for _, f := range fams { some, err := extractSamples(f, o) if err != nil { lastErr = err continue } all = append(all, some...) } return all, lastErr } func extractSamples(f *dto.MetricFamily, o *DecodeOptions) (model.Vector, error) { switch f.GetType() { case dto.MetricType_COUNTER: return extractCounter(o, f), nil case dto.MetricType_GAUGE: return extractGauge(o, f), nil case dto.MetricType_SUMMARY: return extractSummary(o, f), nil case dto.MetricType_UNTYPED: return extractUntyped(o, f), nil case dto.MetricType_HISTOGRAM: return extractHistogram(o, f), nil } return nil, fmt.Errorf("expfmt.extractSamples: unknown metric family type %v", f.GetType()) } func extractCounter(o *DecodeOptions, f *dto.MetricFamily) model.Vector { samples := make(model.Vector, 0, len(f.Metric)) for _, m := range f.Metric { if m.Counter == nil { continue } lset := make(model.LabelSet, len(m.Label)+1) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.MetricNameLabel] = model.LabelValue(f.GetName()) smpl := &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(m.Counter.GetValue()), } if m.TimestampMs != nil { smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000) } else { smpl.Timestamp = o.Timestamp } samples = append(samples, smpl) } return samples } func extractGauge(o *DecodeOptions, f *dto.MetricFamily) model.Vector { samples := make(model.Vector, 0, len(f.Metric)) for _, m := range f.Metric { if m.Gauge == nil { continue } lset := make(model.LabelSet, len(m.Label)+1) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.MetricNameLabel] = model.LabelValue(f.GetName()) smpl := &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(m.Gauge.GetValue()), } if m.TimestampMs != nil { smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000) } else { smpl.Timestamp = o.Timestamp } samples = append(samples, smpl) } return samples } func extractUntyped(o *DecodeOptions, f *dto.MetricFamily) model.Vector { samples := make(model.Vector, 0, len(f.Metric)) for _, m := range f.Metric { if m.Untyped == nil { continue } lset := make(model.LabelSet, len(m.Label)+1) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.MetricNameLabel] = model.LabelValue(f.GetName()) smpl := &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(m.Untyped.GetValue()), } if m.TimestampMs != nil { smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000) } else { smpl.Timestamp = o.Timestamp } samples = append(samples, smpl) } return samples } func extractSummary(o *DecodeOptions, f *dto.MetricFamily) model.Vector { samples := make(model.Vector, 0, len(f.Metric)) for _, m := range f.Metric { if m.Summary == nil { continue } timestamp := o.Timestamp if m.TimestampMs != nil { timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000) } for _, q := range m.Summary.Quantile { lset := make(model.LabelSet, len(m.Label)+2) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } // BUG(matt): Update other names to "quantile". lset[model.LabelName(model.QuantileLabel)] = model.LabelValue(fmt.Sprint(q.GetQuantile())) lset[model.MetricNameLabel] = model.LabelValue(f.GetName()) samples = append(samples, &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(q.GetValue()), Timestamp: timestamp, }) } lset := make(model.LabelSet, len(m.Label)+1) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_sum") samples = append(samples, &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(m.Summary.GetSampleSum()), Timestamp: timestamp, }) lset = make(model.LabelSet, len(m.Label)+1) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_count") samples = append(samples, &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(m.Summary.GetSampleCount()), Timestamp: timestamp, }) } return samples } func extractHistogram(o *DecodeOptions, f *dto.MetricFamily) model.Vector { samples := make(model.Vector, 0, len(f.Metric)) for _, m := range f.Metric { if m.Histogram == nil { continue } timestamp := o.Timestamp if m.TimestampMs != nil { timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000) } infSeen := false for _, q := range m.Histogram.Bucket { lset := make(model.LabelSet, len(m.Label)+2) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.LabelName(model.BucketLabel)] = model.LabelValue(fmt.Sprint(q.GetUpperBound())) lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_bucket") if math.IsInf(q.GetUpperBound(), +1) { infSeen = true } samples = append(samples, &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(q.GetCumulativeCount()), Timestamp: timestamp, }) } lset := make(model.LabelSet, len(m.Label)+1) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_sum") samples = append(samples, &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(m.Histogram.GetSampleSum()), Timestamp: timestamp, }) lset = make(model.LabelSet, len(m.Label)+1) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_count") count := &model.Sample{ Metric: model.Metric(lset), Value: model.SampleValue(m.Histogram.GetSampleCount()), Timestamp: timestamp, } samples = append(samples, count) if !infSeen { // Append an infinity bucket sample. lset := make(model.LabelSet, len(m.Label)+2) for _, p := range m.Label { lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue()) } lset[model.LabelName(model.BucketLabel)] = model.LabelValue("+Inf") lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_bucket") samples = append(samples, &model.Sample{ Metric: model.Metric(lset), Value: count.Value, Timestamp: timestamp, }) } } return samples }
vendor/github.com/prometheus/common/expfmt/decode.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.0002019266103161499, 0.00017474443302489817, 0.00016288901679217815, 0.00017471934552304447, 0.000005383967618399765 ]
{ "id": 5, "code_window": [ " />\n", " ))}\n", " {hasData && deferLogs && <span>Rendering {dedupedData.rows.length} rows...</span>}\n", " </div>\n", " {!loading &&\n", " data.queryEmpty &&\n", " !scanning && (\n", " <div className=\"logs-nodata\">\n", " No logs found.\n", " <a className=\"link\" onClick={this.onClickScan}>\n", " Scan for older logs\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty &&\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "replace", "edit_start_line_idx": 360 }
import React from 'react'; import { hot } from 'react-hot-loader'; import Select from 'react-select'; import _ from 'lodash'; import { DataSource } from 'app/types/datasources'; import { ExploreState, ExploreUrlState, QueryTransaction, ResultType, QueryHintGetter, QueryHint, } from 'app/types/explore'; import { RawTimeRange, DataQuery } from 'app/types/series'; import store from 'app/core/store'; import { DEFAULT_RANGE, calculateResultsFromQueryTransactions, ensureQueries, getIntervals, generateKey, generateQueryKeys, hasNonEmptyQuery, makeTimeSeriesList, updateHistory, } from 'app/core/utils/explore'; import ResetStyles from 'app/core/components/Picker/ResetStyles'; import PickerOption from 'app/core/components/Picker/PickerOption'; import IndicatorsContainer from 'app/core/components/Picker/IndicatorsContainer'; import NoOptionsMessage from 'app/core/components/Picker/NoOptionsMessage'; import TableModel from 'app/core/table_model'; import { DatasourceSrv } from 'app/features/plugins/datasource_srv'; import Panel from './Panel'; import QueryRows from './QueryRows'; import Graph from './Graph'; import Logs from './Logs'; import Table from './Table'; import ErrorBoundary from './ErrorBoundary'; import TimePicker from './TimePicker'; interface ExploreProps { datasourceSrv: DatasourceSrv; onChangeSplit: (split: boolean, state?: ExploreState) => void; onSaveState: (key: string, state: ExploreState) => void; position: string; split: boolean; splitState?: ExploreState; stateKey: string; urlState: ExploreUrlState; } /** * Explore provides an area for quick query iteration for a given datasource. * Once a datasource is selected it populates the query section at the top. * When queries are run, their results are being displayed in the main section. * The datasource determines what kind of query editor it brings, and what kind * of results viewers it supports. * * QUERY HANDLING * * TLDR: to not re-render Explore during edits, query editing is not "controlled" * in a React sense: values need to be pushed down via `initialQueries`, while * edits travel up via `this.modifiedQueries`. * * By default the query rows start without prior state: `initialQueries` will * contain one empty DataQuery. While the user modifies the DataQuery, the * modifications are being tracked in `this.modifiedQueries`, which need to be * used whenever a query is sent to the datasource to reflect what the user sees * on the screen. Query rows can be initialized or reset using `initialQueries`, * by giving the respective row a new key. This wipes the old row and its state. * This property is also used to govern how many query rows there are (minimum 1). * * This flow makes sure that a query row can be arbitrarily complex without the * fear of being wiped or re-initialized via props. The query row is free to keep * its own state while the user edits or builds a query. Valid queries can be sent * up to Explore via the `onChangeQuery` prop. * * DATASOURCE REQUESTS * * A click on Run Query creates transactions for all DataQueries for all expanded * result viewers. New runs are discarding previous runs. Upon completion a transaction * saves the result. The result viewers construct their data from the currently existing * transactions. * * The result viewers determine some of the query options sent to the datasource, e.g., * `format`, to indicate eventual transformations by the datasources' result transformers. */ export class Explore extends React.PureComponent<ExploreProps, ExploreState> { el: any; /** * Current query expressions of the rows including their modifications, used for running queries. * Not kept in component state to prevent edit-render roundtrips. */ modifiedQueries: DataQuery[]; /** * Local ID cache to compare requested vs selected datasource */ requestedDatasourceId: string; scanTimer: NodeJS.Timer; /** * Timepicker to control scanning */ timepickerRef: React.RefObject<TimePicker>; constructor(props) { super(props); const splitState: ExploreState = props.splitState; let initialQueries: DataQuery[]; if (splitState) { // Split state overrides everything this.state = splitState; initialQueries = splitState.initialQueries; } else { const { datasource, queries, range } = props.urlState as ExploreUrlState; initialQueries = ensureQueries(queries); const initialRange = range || { ...DEFAULT_RANGE }; // Millies step for helper bar charts const initialGraphInterval = 15 * 1000; this.state = { datasource: null, datasourceError: null, datasourceLoading: null, datasourceMissing: false, datasourceName: datasource, exploreDatasources: [], graphInterval: initialGraphInterval, graphResult: [], initialQueries, history: [], logsResult: null, queryTransactions: [], range: initialRange, scanning: false, showingGraph: true, showingLogs: true, showingStartPage: false, showingTable: true, supportsGraph: null, supportsLogs: null, supportsTable: null, tableResult: new TableModel(), }; } this.modifiedQueries = initialQueries.slice(); this.timepickerRef = React.createRef(); } async componentDidMount() { const { datasourceSrv } = this.props; const { datasourceName } = this.state; if (!datasourceSrv) { throw new Error('No datasource service passed as props.'); } const datasources = datasourceSrv.getExploreSources(); const exploreDatasources = datasources.map(ds => ({ value: ds.name, label: ds.name, })); if (datasources.length > 0) { this.setState({ datasourceLoading: true, exploreDatasources }); // Priority: datasource in url, default datasource, first explore datasource let datasource; if (datasourceName) { datasource = await datasourceSrv.get(datasourceName); } else { datasource = await datasourceSrv.get(); } if (!datasource.meta.explore) { datasource = await datasourceSrv.get(datasources[0].name); } await this.setDatasource(datasource); } else { this.setState({ datasourceMissing: true }); } } componentWillUnmount() { clearTimeout(this.scanTimer); } async setDatasource(datasource: any, origin?: DataSource) { const { initialQueries, range } = this.state; const supportsGraph = datasource.meta.metrics; const supportsLogs = datasource.meta.logs; const supportsTable = datasource.meta.metrics; const datasourceId = datasource.meta.id; let datasourceError = null; // Keep ID to track selection this.requestedDatasourceId = datasourceId; try { const testResult = await datasource.testDatasource(); datasourceError = testResult.status === 'success' ? null : testResult.message; } catch (error) { datasourceError = (error && error.statusText) || 'Network error'; } if (datasourceId !== this.requestedDatasourceId) { // User already changed datasource again, discard results return; } const historyKey = `grafana.explore.history.${datasourceId}`; const history = store.getObject(historyKey, []); if (datasource.init) { datasource.init(); } // Check if queries can be imported from previously selected datasource let modifiedQueries = this.modifiedQueries; if (origin) { if (origin.meta.id === datasource.meta.id) { // Keep same queries if same type of datasource modifiedQueries = [...this.modifiedQueries]; } else if (datasource.importQueries) { // Datasource-specific importers modifiedQueries = await datasource.importQueries(this.modifiedQueries, origin.meta); } else { // Default is blank queries modifiedQueries = ensureQueries(); } } // Reset edit state with new queries const nextQueries = initialQueries.map((q, i) => ({ ...modifiedQueries[i], ...generateQueryKeys(i), })); this.modifiedQueries = modifiedQueries; // Custom components const StartPage = datasource.pluginExports.ExploreStartPage; // Calculate graph bucketing interval const graphInterval = getIntervals(range, datasource, this.el ? this.el.offsetWidth : 0).intervalMs; this.setState( { StartPage, datasource, datasourceError, graphInterval, history, supportsGraph, supportsLogs, supportsTable, datasourceLoading: false, datasourceName: datasource.name, initialQueries: nextQueries, showingStartPage: Boolean(StartPage), }, () => { if (datasourceError === null) { this.onSubmit(); } } ); } getRef = el => { this.el = el; }; onAddQueryRow = index => { // Local cache this.modifiedQueries[index + 1] = { ...generateQueryKeys(index + 1) }; this.setState(state => { const { initialQueries, queryTransactions } = state; const nextQueries = [ ...initialQueries.slice(0, index + 1), { ...this.modifiedQueries[index + 1] }, ...initialQueries.slice(index + 1), ]; // Ongoing transactions need to update their row indices const nextQueryTransactions = queryTransactions.map(qt => { if (qt.rowIndex > index) { return { ...qt, rowIndex: qt.rowIndex + 1, }; } return qt; }); return { initialQueries: nextQueries, queryTransactions: nextQueryTransactions }; }); }; onChangeDatasource = async option => { const origin = this.state.datasource; this.setState({ datasource: null, datasourceError: null, datasourceLoading: true, queryTransactions: [], }); const datasourceName = option.value; const datasource = await this.props.datasourceSrv.get(datasourceName); this.setDatasource(datasource as any, origin); }; onChangeQuery = (value: DataQuery, index: number, override?: boolean) => { // Null value means reset if (value === null) { value = { ...generateQueryKeys(index) }; } // Keep current value in local cache this.modifiedQueries[index] = value; if (override) { this.setState(state => { // Replace query row by injecting new key const { initialQueries, queryTransactions } = state; const query: DataQuery = { ...value, ...generateQueryKeys(index), }; const nextQueries = [...initialQueries]; nextQueries[index] = query; this.modifiedQueries = [...nextQueries]; // Discard ongoing transaction related to row query const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index); return { initialQueries: nextQueries, queryTransactions: nextQueryTransactions, }; }, this.onSubmit); } }; onChangeTime = (nextRange: RawTimeRange, scanning?: boolean) => { const range: RawTimeRange = { ...nextRange, }; if (this.state.scanning && !scanning) { this.onStopScanning(); } this.setState({ range, scanning }, () => this.onSubmit()); }; onClickClear = () => { this.modifiedQueries = ensureQueries(); this.setState( prevState => ({ initialQueries: [...this.modifiedQueries], queryTransactions: [], showingStartPage: Boolean(prevState.StartPage), }), this.saveState ); }; onClickCloseSplit = () => { const { onChangeSplit } = this.props; if (onChangeSplit) { onChangeSplit(false); } }; onClickGraphButton = () => { this.setState( state => { const showingGraph = !state.showingGraph; let nextQueryTransactions = state.queryTransactions; if (!showingGraph) { // Discard transactions related to Graph query nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Graph'); } return { queryTransactions: nextQueryTransactions, showingGraph }; }, () => { if (this.state.showingGraph) { this.onSubmit(); } } ); }; onClickLogsButton = () => { this.setState( state => { const showingLogs = !state.showingLogs; let nextQueryTransactions = state.queryTransactions; if (!showingLogs) { // Discard transactions related to Logs query nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Logs'); } return { queryTransactions: nextQueryTransactions, showingLogs }; }, () => { if (this.state.showingLogs) { this.onSubmit(); } } ); }; // Use this in help pages to set page to a single query onClickExample = (query: DataQuery) => { const nextQueries = [{ ...query, ...generateQueryKeys() }]; this.modifiedQueries = [...nextQueries]; this.setState({ initialQueries: nextQueries }, this.onSubmit); }; onClickSplit = () => { const { onChangeSplit } = this.props; if (onChangeSplit) { const state = this.cloneState(); onChangeSplit(true, state); } }; onClickTableButton = () => { this.setState( state => { const showingTable = !state.showingTable; if (showingTable) { return { showingTable, queryTransactions: state.queryTransactions }; } // Toggle off needs discarding of table queries const nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Table'); const results = calculateResultsFromQueryTransactions( nextQueryTransactions, state.datasource, state.graphInterval ); return { ...results, queryTransactions: nextQueryTransactions, showingTable }; }, () => { if (this.state.showingTable) { this.onSubmit(); } } ); }; onClickLabel = (key: string, value: string) => { this.onModifyQueries({ type: 'ADD_FILTER', key, value }); }; onModifyQueries = (action, index?: number) => { const { datasource } = this.state; if (datasource && datasource.modifyQuery) { const preventSubmit = action.preventSubmit; this.setState( state => { const { initialQueries, queryTransactions } = state; let nextQueries: DataQuery[]; let nextQueryTransactions; if (index === undefined) { // Modify all queries nextQueries = initialQueries.map((query, i) => ({ ...datasource.modifyQuery(this.modifiedQueries[i], action), ...generateQueryKeys(i), })); // Discard all ongoing transactions nextQueryTransactions = []; } else { // Modify query only at index nextQueries = initialQueries.map((query, i) => { // Synchronise all queries with local query cache to ensure consistency // TODO still needed? return i === index ? { ...datasource.modifyQuery(this.modifiedQueries[i], action), ...generateQueryKeys(i), } : query; }); nextQueryTransactions = queryTransactions // Consume the hint corresponding to the action .map(qt => { if (qt.hints != null && qt.rowIndex === index) { qt.hints = qt.hints.filter(hint => hint.fix.action !== action); } return qt; }) // Preserve previous row query transaction to keep results visible if next query is incomplete .filter(qt => preventSubmit || qt.rowIndex !== index); } this.modifiedQueries = [...nextQueries]; return { initialQueries: nextQueries, queryTransactions: nextQueryTransactions, }; }, // Accepting certain fixes do not result in a well-formed query which should not be submitted !preventSubmit ? () => this.onSubmit() : null ); } }; onRemoveQueryRow = index => { // Remove from local cache this.modifiedQueries = [...this.modifiedQueries.slice(0, index), ...this.modifiedQueries.slice(index + 1)]; this.setState( state => { const { initialQueries, queryTransactions } = state; if (initialQueries.length <= 1) { return null; } // Remove row from react state const nextQueries = [...initialQueries.slice(0, index), ...initialQueries.slice(index + 1)]; // Discard transactions related to row query const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index); const results = calculateResultsFromQueryTransactions( nextQueryTransactions, state.datasource, state.graphInterval ); return { ...results, initialQueries: nextQueries, queryTransactions: nextQueryTransactions, }; }, () => this.onSubmit() ); }; onStartScanning = () => { this.setState({ scanning: true }, this.scanPreviousRange); }; scanPreviousRange = () => { const scanRange = this.timepickerRef.current.move(-1, true); this.setState({ scanRange }); }; onStopScanning = () => { clearTimeout(this.scanTimer); this.setState(state => { const { queryTransactions } = state; const nextQueryTransactions = queryTransactions.filter(qt => qt.scanning && !qt.done); return { queryTransactions: nextQueryTransactions, scanning: false, scanRange: undefined }; }); }; onSubmit = () => { const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state; // Keep table queries first since they need to return quickly if (showingTable && supportsTable) { this.runQueries( 'Table', { format: 'table', instant: true, valueWithRefId: true, }, data => data[0] ); } if (showingGraph && supportsGraph) { this.runQueries( 'Graph', { format: 'time_series', instant: false, }, makeTimeSeriesList ); } if (showingLogs && supportsLogs) { this.runQueries('Logs', { format: 'logs' }); } this.saveState(); }; buildQueryOptions(query: DataQuery, queryOptions: { format: string; hinting?: boolean; instant?: boolean }) { const { datasource, range } = this.state; const { interval, intervalMs } = getIntervals(range, datasource, this.el.offsetWidth); const configuredQueries = [ { ...query, ...queryOptions, }, ]; // Clone range for query request const queryRange: RawTimeRange = { ...range }; // Datasource is using `panelId + query.refId` for cancellation logic. // Using `format` here because it relates to the view panel that the request is for. const panelId = queryOptions.format; return { interval, intervalMs, panelId, targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key. range: queryRange, }; } startQueryTransaction(query: DataQuery, rowIndex: number, resultType: ResultType, options: any): QueryTransaction { const queryOptions = this.buildQueryOptions(query, options); const transaction: QueryTransaction = { query, resultType, rowIndex, id: generateKey(), // reusing for unique ID done: false, latency: 0, options: queryOptions, scanning: this.state.scanning, }; // Using updater style because we might be modifying queryTransactions in quick succession this.setState(state => { const { queryTransactions } = state; // Discarding existing transactions of same type const remainingTransactions = queryTransactions.filter( qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex) ); // Append new transaction const nextQueryTransactions = [...remainingTransactions, transaction]; const results = calculateResultsFromQueryTransactions( nextQueryTransactions, state.datasource, state.graphInterval ); return { ...results, queryTransactions: nextQueryTransactions, showingStartPage: false, }; }); return transaction; } completeQueryTransaction( transactionId: string, result: any, latency: number, queries: DataQuery[], datasourceId: string ) { const { datasource } = this.state; if (datasource.meta.id !== datasourceId) { // Navigated away, queries did not matter return; } this.setState(state => { const { history, queryTransactions, scanning } = state; // Transaction might have been discarded const transaction = queryTransactions.find(qt => qt.id === transactionId); if (!transaction) { return null; } // Get query hints let hints: QueryHint[]; if (datasource.getQueryHints as QueryHintGetter) { hints = datasource.getQueryHints(transaction.query, result); } // Mark transactions as complete const nextQueryTransactions = queryTransactions.map(qt => { if (qt.id === transactionId) { return { ...qt, hints, latency, result, done: true, }; } return qt; }); const results = calculateResultsFromQueryTransactions( nextQueryTransactions, state.datasource, state.graphInterval ); const nextHistory = updateHistory(history, datasourceId, queries); // Keep scanning for results if this was the last scanning transaction if (_.size(result) === 0 && scanning) { const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done); if (!other) { this.scanTimer = setTimeout(this.scanPreviousRange, 1000); } } return { ...results, history: nextHistory, queryTransactions: nextQueryTransactions, }; }); } failQueryTransaction(transactionId: string, response: any, datasourceId: string) { const { datasource } = this.state; if (datasource.meta.id !== datasourceId || response.cancelled) { // Navigated away, queries did not matter return; } console.error(response); let error: string | JSX.Element = response; if (response.data) { if (typeof response.data === 'string') { error = response.data; } else if (response.data.error) { error = response.data.error; if (response.data.response) { error = ( <> <span>{response.data.error}</span> <details>{response.data.response}</details> </> ); } } else { throw new Error('Could not handle error response'); } } this.setState(state => { // Transaction might have been discarded if (!state.queryTransactions.find(qt => qt.id === transactionId)) { return null; } // Mark transactions as complete const nextQueryTransactions = state.queryTransactions.map(qt => { if (qt.id === transactionId) { return { ...qt, error, done: true, }; } return qt; }); return { queryTransactions: nextQueryTransactions, }; }); } async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) { const queries = [...this.modifiedQueries]; if (!hasNonEmptyQuery(queries)) { return; } const { datasource } = this.state; const datasourceId = datasource.meta.id; // Run all queries concurrently queries.forEach(async (query, rowIndex) => { const transaction = this.startQueryTransaction(query, rowIndex, resultType, queryOptions); try { const now = Date.now(); const res = await datasource.query(transaction.options); const latency = Date.now() - now; const results = resultGetter ? resultGetter(res.data) : res.data; this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId); } catch (response) { this.failQueryTransaction(transaction.id, response, datasourceId); } }); } cloneState(): ExploreState { // Copy state, but copy queries including modifications return { ...this.state, queryTransactions: [], initialQueries: [...this.modifiedQueries], }; } saveState = () => { const { stateKey, onSaveState } = this.props; onSaveState(stateKey, this.cloneState()); }; render() { const { position, split } = this.props; const { StartPage, datasource, datasourceError, datasourceLoading, datasourceMissing, exploreDatasources, graphResult, history, initialQueries, logsResult, queryTransactions, range, scanning, scanRange, showingGraph, showingLogs, showingStartPage, showingTable, supportsGraph, supportsLogs, supportsTable, tableResult, } = this.state; const graphHeight = showingGraph && showingTable ? '200px' : '400px'; const exploreClass = split ? 'explore explore-split' : 'explore'; const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined; const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done); const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done); const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done); const loading = queryTransactions.some(qt => !qt.done); return ( <div className={exploreClass} ref={this.getRef}> <div className="navbar"> {position === 'left' ? ( <div> <a className="navbar-page-btn"> <i className="fa fa-rocket" /> Explore </a> </div> ) : ( <div className="navbar-buttons explore-first-button"> <button className="btn navbar-button" onClick={this.onClickCloseSplit}> Close Split </button> </div> )} {!datasourceMissing ? ( <div className="navbar-buttons"> <Select classNamePrefix={`gf-form-select-box`} isMulti={false} isLoading={datasourceLoading} isClearable={false} className="gf-form-input gf-form-input--form-dropdown datasource-picker" onChange={this.onChangeDatasource} options={exploreDatasources} styles={ResetStyles} placeholder="Select datasource" loadingMessage={() => 'Loading datasources...'} noOptionsMessage={() => 'No datasources found'} value={selectedDatasource} components={{ Option: PickerOption, IndicatorsContainer, NoOptionsMessage, }} /> </div> ) : null} <div className="navbar__spacer" /> {position === 'left' && !split ? ( <div className="navbar-buttons"> <button className="btn navbar-button" onClick={this.onClickSplit}> Split </button> </div> ) : null} <TimePicker ref={this.timepickerRef} range={range} onChangeTime={this.onChangeTime} /> <div className="navbar-buttons"> <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}> Clear All </button> </div> <div className="navbar-buttons relative"> <button className="btn navbar-button--primary" onClick={this.onSubmit}> Run Query{' '} {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />} </button> </div> </div> {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null} {datasourceMissing ? ( <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div> ) : null} {datasourceError ? ( <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div> ) : null} {datasource && !datasourceError ? ( <div className="explore-container"> <QueryRows datasource={datasource} history={history} initialQueries={initialQueries} onAddQueryRow={this.onAddQueryRow} onChangeQuery={this.onChangeQuery} onClickHintFix={this.onModifyQueries} onExecuteQuery={this.onSubmit} onRemoveQueryRow={this.onRemoveQueryRow} transactions={queryTransactions} /> <main className="m-t-2"> <ErrorBoundary> {showingStartPage && <StartPage onClickExample={this.onClickExample} />} {!showingStartPage && ( <> {supportsGraph && ( <Panel label="Graph" isOpen={showingGraph} loading={graphLoading} onToggle={this.onClickGraphButton} > <Graph data={graphResult} height={graphHeight} id={`explore-graph-${position}`} onChangeTime={this.onChangeTime} range={range} split={split} /> </Panel> )} {supportsTable && ( <Panel label="Table" loading={tableLoading} isOpen={showingTable} onToggle={this.onClickTableButton} > <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickLabel} /> </Panel> )} {supportsLogs && ( <Panel label="Logs" loading={logsLoading} isOpen={showingLogs} onToggle={this.onClickLogsButton}> <Logs data={logsResult} key={logsResult.id} loading={logsLoading} position={position} onChangeTime={this.onChangeTime} onClickLabel={this.onClickLabel} onStartScanning={this.onStartScanning} onStopScanning={this.onStopScanning} range={range} scanning={scanning} scanRange={scanRange} /> </Panel> )} </> )} </ErrorBoundary> </main> </div> ) : null} </div> ); } } export default hot(module)(Explore);
public/app/features/explore/Explore.tsx
1
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.007600465323776007, 0.0004393276758491993, 0.0001605557627044618, 0.00016955005412455648, 0.0009979554452002048 ]
{ "id": 5, "code_window": [ " />\n", " ))}\n", " {hasData && deferLogs && <span>Rendering {dedupedData.rows.length} rows...</span>}\n", " </div>\n", " {!loading &&\n", " data.queryEmpty &&\n", " !scanning && (\n", " <div className=\"logs-nodata\">\n", " No logs found.\n", " <a className=\"link\" onClick={this.onClickScan}>\n", " Scan for older logs\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty &&\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "replace", "edit_start_line_idx": 360 }
<page-header model="ctrl.navModel"></page-header> <div class="page-container page-body" ng-cloak> <h3 class="page-sub-heading">New Team</h3> <form name="ctrl.saveForm" class="gf-form-group" ng-submit="ctrl.create()"> <div class="gf-form max-width-30"> <span class="gf-form-label width-10">Name</span> <input type="text" required ng-model="ctrl.name" class="gf-form-input max-width-22" give-focus="true"> </div> <div class="gf-form max-width-30"> <span class="gf-form-label width-10"> Email <info-popover mode="right-normal"> This is optional and is primarily used for allowing custom team avatars. </info-popover> </span> <input class="gf-form-input max-width-22" type="email" ng-model="ctrl.email" placeholder="[email protected]"> </div> <div class="gf-form-button-row"> <button type="submit" class="btn btn-success width-12"> <i class="fa fa-save"></i> Create </button> </div> </form> </div>
public/app/features/teams/partials/create_team.html
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.00017026140994857997, 0.00016847993538249284, 0.00016628086450509727, 0.00016889751714188606, 0.000001651659772505809 ]
{ "id": 5, "code_window": [ " />\n", " ))}\n", " {hasData && deferLogs && <span>Rendering {dedupedData.rows.length} rows...</span>}\n", " </div>\n", " {!loading &&\n", " data.queryEmpty &&\n", " !scanning && (\n", " <div className=\"logs-nodata\">\n", " No logs found.\n", " <a className=\"link\" onClick={this.onClickScan}>\n", " Scan for older logs\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty &&\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "replace", "edit_start_line_idx": 360 }
// +build go1.7 /* * * Copyright 2016 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "fmt" "io" "net" "net/http" netctx "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/grpc/transport" ) // dialContext connects to the address on the named network. func dialContext(ctx context.Context, network, address string) (net.Conn, error) { return (&net.Dialer{}).DialContext(ctx, network, address) } func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { req = req.WithContext(ctx) if err := req.Write(conn); err != nil { return fmt.Errorf("failed to write the HTTP request: %v", err) } return nil } // toRPCErr converts an error into an error from the status package. func toRPCErr(err error) error { if err == nil || err == io.EOF { return err } if _, ok := status.FromError(err); ok { return err } switch e := err.(type) { case transport.StreamError: return status.Error(e.Code, e.Desc) case transport.ConnectionError: return status.Error(codes.Unavailable, e.Desc) default: switch err { case context.DeadlineExceeded, netctx.DeadlineExceeded: return status.Error(codes.DeadlineExceeded, err.Error()) case context.Canceled, netctx.Canceled: return status.Error(codes.Canceled, err.Error()) } } return status.Error(codes.Unknown, err.Error()) }
vendor/google.golang.org/grpc/go17.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.0001757003483362496, 0.00016813358524814248, 0.00016259742551483214, 0.00016556188347749412, 0.000005325273377820849 ]
{ "id": 5, "code_window": [ " />\n", " ))}\n", " {hasData && deferLogs && <span>Rendering {dedupedData.rows.length} rows...</span>}\n", " </div>\n", " {!loading &&\n", " data.queryEmpty &&\n", " !scanning && (\n", " <div className=\"logs-nodata\">\n", " No logs found.\n", " <a className=\"link\" onClick={this.onClickScan}>\n", " Scan for older logs\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryEmpty &&\n" ], "file_path": "public/app/features/explore/Logs.tsx", "type": "replace", "edit_start_line_idx": 360 }
package sqlstore import ( "github.com/grafana/grafana/pkg/bus" m "github.com/grafana/grafana/pkg/models" ) func init() { bus.AddHandler("sql", StarDashboard) bus.AddHandler("sql", UnstarDashboard) bus.AddHandler("sql", GetUserStars) bus.AddHandler("sql", IsStarredByUser) } func IsStarredByUser(query *m.IsStarredByUserQuery) error { rawSql := "SELECT 1 from star where user_id=? and dashboard_id=?" results, err := x.Query(rawSql, query.UserId, query.DashboardId) if err != nil { return err } if len(results) == 0 { return nil } query.Result = true return nil } func StarDashboard(cmd *m.StarDashboardCommand) error { if cmd.DashboardId == 0 || cmd.UserId == 0 { return m.ErrCommandValidationFailed } return inTransaction(func(sess *DBSession) error { entity := m.Star{ UserId: cmd.UserId, DashboardId: cmd.DashboardId, } _, err := sess.Insert(&entity) return err }) } func UnstarDashboard(cmd *m.UnstarDashboardCommand) error { if cmd.DashboardId == 0 || cmd.UserId == 0 { return m.ErrCommandValidationFailed } return inTransaction(func(sess *DBSession) error { var rawSql = "DELETE FROM star WHERE user_id=? and dashboard_id=?" _, err := sess.Exec(rawSql, cmd.UserId, cmd.DashboardId) return err }) } func GetUserStars(query *m.GetUserStarsQuery) error { var stars = make([]m.Star, 0) err := x.Where("user_id=?", query.UserId).Find(&stars) query.Result = make(map[int64]bool) for _, star := range stars { query.Result[star.DashboardId] = true } return err }
pkg/services/sqlstore/star.go
0
https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967
[ 0.00020194894750602543, 0.00017220093286596239, 0.0001634833897696808, 0.00016863302153069526, 0.000011609948160185013 ]
{ "id": 0, "code_window": [ " const cellTarget = column.style.linkTargetBlank ? '_blank' : '';\n", "\n", " cellClasses.push('table-panel-cell-link');\n", "\n", " columnHtml += `\n", " <a href=\"${sanitizedCellLink}\" target=\"${cellTarget}\" data-link-tooltip data-original-title=\"${cellLinkTooltip}\" data-placement=\"right\"${cellStyle}>\n", " ${value}\n", " </a>\n", " `;\n", " } else {\n", " columnHtml += value;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " columnHtml += `<a href=\"${sanitizedCellLink}\" target=\"${cellTarget}\" data-link-tooltip data-original-title=\"${cellLinkTooltip}\" data-placement=\"right\"${cellStyle}>`;\n", " columnHtml += `${value}`;\n", " columnHtml += `</a>`;\n" ], "file_path": "public/app/plugins/panel/table/renderer.ts", "type": "replace", "edit_start_line_idx": 307 }
import _ from 'lodash'; import { dateTime, escapeStringForRegex, formattedValueToString, getColorFromHexRgbOrName, getValueFormat, GrafanaThemeType, ScopedVars, stringStartsAsRegEx, stringToJsRegex, unEscapeStringFromRegex, } from '@grafana/data'; import { TemplateSrv } from 'app/features/templating/template_srv'; import { ColumnRender, TableRenderModel, ColumnStyle } from './types'; import { ColumnOptionsCtrl } from './column_options'; import { sanitizeUrl } from 'app/core/utils/text'; export class TableRenderer { formatters: any[]; colorState: any; constructor( private panel: { styles: ColumnStyle[]; pageSize: number }, private table: TableRenderModel, private isUtc: boolean, private sanitize: (v: any) => any, private templateSrv: TemplateSrv, private theme?: GrafanaThemeType ) { this.initColumns(); } setTable(table: TableRenderModel) { this.table = table; this.initColumns(); } initColumns() { this.formatters = []; this.colorState = {}; for (let colIndex = 0; colIndex < this.table.columns.length; colIndex++) { const column = this.table.columns[colIndex]; column.title = column.text; for (let i = 0; i < this.panel.styles.length; i++) { const style = this.panel.styles[i]; const escapedPattern = stringStartsAsRegEx(style.pattern) ? style.pattern : escapeStringForRegex(unEscapeStringFromRegex(style.pattern)); const regex = stringToJsRegex(escapedPattern); if (column.text.match(regex)) { column.style = style; if (style.alias) { column.title = column.text.replace(regex, style.alias); } break; } } this.formatters[colIndex] = this.createColumnFormatter(column); } } getColorForValue(value: number, style: ColumnStyle) { if (!style.thresholds || !style.colors) { return null; } for (let i = style.thresholds.length; i > 0; i--) { if (value >= style.thresholds[i - 1]) { return getColorFromHexRgbOrName(style.colors[i], this.theme); } } return getColorFromHexRgbOrName(_.first(style.colors), this.theme); } defaultCellFormatter(v: any, style: ColumnStyle) { if (v === null || v === void 0 || v === undefined) { return ''; } if (_.isArray(v)) { v = v.join(', '); } if (style && style.sanitize) { return this.sanitize(v); } else { return _.escape(v); } } createColumnFormatter(column: ColumnRender) { if (!column.style) { return this.defaultCellFormatter; } if (column.style.type === 'hidden') { return (v: any): undefined => undefined; } if (column.style.type === 'date') { return (v: any) => { if (v === undefined || v === null) { return '-'; } if (_.isArray(v)) { v = v[0]; } // if is an epoch (numeric string and len > 12) if (_.isString(v) && !isNaN(v as any) && v.length > 12) { v = parseInt(v, 10); } let date = dateTime(v); if (this.isUtc) { date = date.utc(); } return date.format(column.style.dateFormat); }; } if (column.style.type === 'string') { return (v: any): any => { if (_.isArray(v)) { v = v.join(', '); } const mappingType = column.style.mappingType || 0; if (mappingType === 1 && column.style.valueMaps) { for (let i = 0; i < column.style.valueMaps.length; i++) { const map = column.style.valueMaps[i]; if (v === null) { if (map.value === 'null') { return map.text; } continue; } // Allow both numeric and string values to be mapped if ((!_.isString(v) && Number(map.value) === Number(v)) || map.value === v) { this.setColorState(v, column.style); return this.defaultCellFormatter(map.text, column.style); } } } if (mappingType === 2 && column.style.rangeMaps) { for (let i = 0; i < column.style.rangeMaps.length; i++) { const map = column.style.rangeMaps[i]; if (v === null) { if (map.from === 'null' && map.to === 'null') { return map.text; } continue; } if (Number(map.from) <= Number(v) && Number(map.to) >= Number(v)) { this.setColorState(v, column.style); return this.defaultCellFormatter(map.text, column.style); } } } if (v === null || v === void 0) { return '-'; } this.setColorState(v, column.style); return this.defaultCellFormatter(v, column.style); }; } if (column.style.type === 'number') { const valueFormatter = getValueFormat(column.unit || column.style.unit); return (v: any): any => { if (v === null || v === void 0) { return '-'; } if (isNaN(v) || _.isArray(v)) { return this.defaultCellFormatter(v, column.style); } this.setColorState(v, column.style); return formattedValueToString(valueFormatter(v, column.style.decimals, null)); }; } return (value: any) => { return this.defaultCellFormatter(value, column.style); }; } setColorState(value: any, style: ColumnStyle) { if (!style.colorMode) { return; } if (value === null || value === void 0 || _.isArray(value)) { return; } const numericValue = Number(value); if (isNaN(numericValue)) { return; } this.colorState[style.colorMode] = this.getColorForValue(numericValue, style); } renderRowVariables(rowIndex: number) { const scopedVars: ScopedVars = {}; let cellVariable; const row = this.table.rows[rowIndex]; for (let i = 0; i < row.length; i++) { cellVariable = `__cell_${i}`; scopedVars[cellVariable] = { value: row[i], text: row[i] ? row[i].toString() : '' }; } return scopedVars; } formatColumnValue(colIndex: number, value: any) { const fmt = this.formatters[colIndex]; if (fmt) { return fmt(value); } return value; } renderCell(columnIndex: number, rowIndex: number, value: any, addWidthHack = false) { value = this.formatColumnValue(columnIndex, value); const column = this.table.columns[columnIndex]; const cellStyles = []; let cellStyle = ''; const cellClasses = []; let cellClass = ''; if (this.colorState.cell) { cellStyles.push('background-color:' + this.colorState.cell); cellClasses.push('table-panel-color-cell'); this.colorState.cell = null; } else if (this.colorState.value) { cellStyles.push('color:' + this.colorState.value); this.colorState.value = null; } // because of the fixed table headers css only solution // there is an issue if header cell is wider the cell // this hack adds header content to cell (not visible) let columnHtml = ''; if (addWidthHack) { columnHtml = '<div class="table-panel-width-hack">' + this.table.columns[columnIndex].title + '</div>'; } if (value === undefined) { cellStyles.push('display:none'); column.hidden = true; } else { column.hidden = false; } if (column.hidden === true) { return ''; } if (column.style && column.style.preserveFormat) { cellClasses.push('table-panel-cell-pre'); } if (column.style && column.style.align) { const textAlign = _.find(ColumnOptionsCtrl.alignTypesEnum, ['text', column.style.align]); if (textAlign && textAlign['value']) { cellStyles.push(`text-align:${textAlign['value']}`); } } if (cellStyles.length) { cellStyle = ' style="' + cellStyles.join(';') + '"'; } if (column.style && column.style.link) { // Render cell as link const scopedVars = this.renderRowVariables(rowIndex); scopedVars['__cell'] = { value: value, text: value ? value.toString() : '' }; const cellLink = this.templateSrv.replace(column.style.linkUrl, scopedVars, encodeURIComponent); const sanitizedCellLink = sanitizeUrl(cellLink); const cellLinkTooltip = this.templateSrv.replace(column.style.linkTooltip, scopedVars); const cellTarget = column.style.linkTargetBlank ? '_blank' : ''; cellClasses.push('table-panel-cell-link'); columnHtml += ` <a href="${sanitizedCellLink}" target="${cellTarget}" data-link-tooltip data-original-title="${cellLinkTooltip}" data-placement="right"${cellStyle}> ${value} </a> `; } else { columnHtml += value; } if (column.filterable) { cellClasses.push('table-panel-cell-filterable'); columnHtml += ` <a class="table-panel-filter-link" data-link-tooltip data-original-title="Filter out value" data-placement="bottom" data-row="${rowIndex}" data-column="${columnIndex}" data-operator="!="> <i class="fa fa-search-minus"></i> </a> <a class="table-panel-filter-link" data-link-tooltip data-original-title="Filter for value" data-placement="bottom" data-row="${rowIndex}" data-column="${columnIndex}" data-operator="="> <i class="fa fa-search-plus"></i> </a>`; } if (cellClasses.length) { cellClass = ' class="' + cellClasses.join(' ') + '"'; } columnHtml = '<td' + cellClass + cellStyle + '>' + columnHtml + '</td>'; return columnHtml; } render(page: number) { const pageSize = this.panel.pageSize || 100; const startPos = page * pageSize; const endPos = Math.min(startPos + pageSize, this.table.rows.length); let html = ''; for (let y = startPos; y < endPos; y++) { const row = this.table.rows[y]; let cellHtml = ''; let rowStyle = ''; const rowClasses = []; let rowClass = ''; for (let i = 0; i < this.table.columns.length; i++) { cellHtml += this.renderCell(i, y, row[i], y === startPos); } if (this.colorState.row) { rowStyle = ' style="background-color:' + this.colorState.row + '"'; rowClasses.push('table-panel-color-row'); this.colorState.row = null; } if (rowClasses.length) { rowClass = ' class="' + rowClasses.join(' ') + '"'; } html += '<tr ' + rowClass + rowStyle + '>' + cellHtml + '</tr>'; } return html; } render_values() { const rows = []; const visibleColumns = this.table.columns.filter(column => !column.hidden); for (let y = 0; y < this.table.rows.length; y++) { const row = this.table.rows[y]; const newRow = []; for (let i = 0; i < this.table.columns.length; i++) { if (!this.table.columns[i].hidden) { newRow.push(this.formatColumnValue(i, row[i])); } } rows.push(newRow); } return { columns: visibleColumns, rows: rows, }; } }
public/app/plugins/panel/table/renderer.ts
1
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.9971672892570496, 0.10113155841827393, 0.00016344879986718297, 0.00036889914190396667, 0.2939736247062683 ]
{ "id": 0, "code_window": [ " const cellTarget = column.style.linkTargetBlank ? '_blank' : '';\n", "\n", " cellClasses.push('table-panel-cell-link');\n", "\n", " columnHtml += `\n", " <a href=\"${sanitizedCellLink}\" target=\"${cellTarget}\" data-link-tooltip data-original-title=\"${cellLinkTooltip}\" data-placement=\"right\"${cellStyle}>\n", " ${value}\n", " </a>\n", " `;\n", " } else {\n", " columnHtml += value;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " columnHtml += `<a href=\"${sanitizedCellLink}\" target=\"${cellTarget}\" data-link-tooltip data-original-title=\"${cellLinkTooltip}\" data-placement=\"right\"${cellStyle}>`;\n", " columnHtml += `${value}`;\n", " columnHtml += `</a>`;\n" ], "file_path": "public/app/plugins/panel/table/renderer.ts", "type": "replace", "edit_start_line_idx": 307 }
export type FormInputSize = 'sm' | 'md' | 'lg' | 'auto';
packages/grafana-ui/src/components/Forms/types.ts
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.00017090357141569257, 0.00017090357141569257, 0.00017090357141569257, 0.00017090357141569257, 0 ]
{ "id": 0, "code_window": [ " const cellTarget = column.style.linkTargetBlank ? '_blank' : '';\n", "\n", " cellClasses.push('table-panel-cell-link');\n", "\n", " columnHtml += `\n", " <a href=\"${sanitizedCellLink}\" target=\"${cellTarget}\" data-link-tooltip data-original-title=\"${cellLinkTooltip}\" data-placement=\"right\"${cellStyle}>\n", " ${value}\n", " </a>\n", " `;\n", " } else {\n", " columnHtml += value;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " columnHtml += `<a href=\"${sanitizedCellLink}\" target=\"${cellTarget}\" data-link-tooltip data-original-title=\"${cellLinkTooltip}\" data-placement=\"right\"${cellStyle}>`;\n", " columnHtml += `${value}`;\n", " columnHtml += `</a>`;\n" ], "file_path": "public/app/plugins/panel/table/renderer.ts", "type": "replace", "edit_start_line_idx": 307 }
// Copyright 2015 Unknwon // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package ini import ( "bufio" "bytes" "fmt" "io" "regexp" "strconv" "strings" "unicode" ) var pythonMultiline = regexp.MustCompile("^(\\s+)([^\n]+)") type parserOptions struct { IgnoreContinuation bool IgnoreInlineComment bool AllowPythonMultilineValues bool SpaceBeforeInlineComment bool UnescapeValueDoubleQuotes bool UnescapeValueCommentSymbols bool PreserveSurroundedQuote bool } type parser struct { buf *bufio.Reader options parserOptions isEOF bool count int comment *bytes.Buffer } func newParser(r io.Reader, opts parserOptions) *parser { return &parser{ buf: bufio.NewReader(r), options: opts, count: 1, comment: &bytes.Buffer{}, } } // BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format. // http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding func (p *parser) BOM() error { mask, err := p.buf.Peek(2) if err != nil && err != io.EOF { return err } else if len(mask) < 2 { return nil } switch { case mask[0] == 254 && mask[1] == 255: fallthrough case mask[0] == 255 && mask[1] == 254: p.buf.Read(mask) case mask[0] == 239 && mask[1] == 187: mask, err := p.buf.Peek(3) if err != nil && err != io.EOF { return err } else if len(mask) < 3 { return nil } if mask[2] == 191 { p.buf.Read(mask) } } return nil } func (p *parser) readUntil(delim byte) ([]byte, error) { data, err := p.buf.ReadBytes(delim) if err != nil { if err == io.EOF { p.isEOF = true } else { return nil, err } } return data, nil } func cleanComment(in []byte) ([]byte, bool) { i := bytes.IndexAny(in, "#;") if i == -1 { return nil, false } return in[i:], true } func readKeyName(delimiters string, in []byte) (string, int, error) { line := string(in) // Check if key name surrounded by quotes. var keyQuote string if line[0] == '"' { if len(line) > 6 && string(line[0:3]) == `"""` { keyQuote = `"""` } else { keyQuote = `"` } } else if line[0] == '`' { keyQuote = "`" } // Get out key name endIdx := -1 if len(keyQuote) > 0 { startIdx := len(keyQuote) // FIXME: fail case -> """"""name"""=value pos := strings.Index(line[startIdx:], keyQuote) if pos == -1 { return "", -1, fmt.Errorf("missing closing key quote: %s", line) } pos += startIdx // Find key-value delimiter i := strings.IndexAny(line[pos+startIdx:], delimiters) if i < 0 { return "", -1, ErrDelimiterNotFound{line} } endIdx = pos + i return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil } endIdx = strings.IndexAny(line, delimiters) if endIdx < 0 { return "", -1, ErrDelimiterNotFound{line} } return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil } func (p *parser) readMultilines(line, val, valQuote string) (string, error) { for { data, err := p.readUntil('\n') if err != nil { return "", err } next := string(data) pos := strings.LastIndex(next, valQuote) if pos > -1 { val += next[:pos] comment, has := cleanComment([]byte(next[pos:])) if has { p.comment.Write(bytes.TrimSpace(comment)) } break } val += next if p.isEOF { return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next) } } return val, nil } func (p *parser) readContinuationLines(val string) (string, error) { for { data, err := p.readUntil('\n') if err != nil { return "", err } next := strings.TrimSpace(string(data)) if len(next) == 0 { break } val += next if val[len(val)-1] != '\\' { break } val = val[:len(val)-1] } return val, nil } // hasSurroundedQuote check if and only if the first and last characters // are quotes \" or \'. // It returns false if any other parts also contain same kind of quotes. func hasSurroundedQuote(in string, quote byte) bool { return len(in) >= 2 && in[0] == quote && in[len(in)-1] == quote && strings.IndexByte(in[1:], quote) == len(in)-2 } func (p *parser) readValue(in []byte, bufferSize int) (string, error) { line := strings.TrimLeftFunc(string(in), unicode.IsSpace) if len(line) == 0 { if p.options.AllowPythonMultilineValues && len(in) > 0 && in[len(in)-1] == '\n' { return p.readPythonMultilines(line, bufferSize) } return "", nil } var valQuote string if len(line) > 3 && string(line[0:3]) == `"""` { valQuote = `"""` } else if line[0] == '`' { valQuote = "`" } else if p.options.UnescapeValueDoubleQuotes && line[0] == '"' { valQuote = `"` } if len(valQuote) > 0 { startIdx := len(valQuote) pos := strings.LastIndex(line[startIdx:], valQuote) // Check for multi-line value if pos == -1 { return p.readMultilines(line, line[startIdx:], valQuote) } if p.options.UnescapeValueDoubleQuotes && valQuote == `"` { return strings.Replace(line[startIdx:pos+startIdx], `\"`, `"`, -1), nil } return line[startIdx : pos+startIdx], nil } lastChar := line[len(line)-1] // Won't be able to reach here if value only contains whitespace line = strings.TrimSpace(line) trimmedLastChar := line[len(line)-1] // Check continuation lines when desired if !p.options.IgnoreContinuation && trimmedLastChar == '\\' { return p.readContinuationLines(line[:len(line)-1]) } // Check if ignore inline comment if !p.options.IgnoreInlineComment { var i int if p.options.SpaceBeforeInlineComment { i = strings.Index(line, " #") if i == -1 { i = strings.Index(line, " ;") } } else { i = strings.IndexAny(line, "#;") } if i > -1 { p.comment.WriteString(line[i:]) line = strings.TrimSpace(line[:i]) } } // Trim single and double quotes if (hasSurroundedQuote(line, '\'') || hasSurroundedQuote(line, '"')) && !p.options.PreserveSurroundedQuote { line = line[1 : len(line)-1] } else if len(valQuote) == 0 && p.options.UnescapeValueCommentSymbols { if strings.Contains(line, `\;`) { line = strings.Replace(line, `\;`, ";", -1) } if strings.Contains(line, `\#`) { line = strings.Replace(line, `\#`, "#", -1) } } else if p.options.AllowPythonMultilineValues && lastChar == '\n' { return p.readPythonMultilines(line, bufferSize) } return line, nil } func (p *parser) readPythonMultilines(line string, bufferSize int) (string, error) { parserBufferPeekResult, _ := p.buf.Peek(bufferSize) peekBuffer := bytes.NewBuffer(parserBufferPeekResult) for { peekData, peekErr := peekBuffer.ReadBytes('\n') if peekErr != nil { if peekErr == io.EOF { return line, nil } return "", peekErr } peekMatches := pythonMultiline.FindStringSubmatch(string(peekData)) if len(peekMatches) != 3 { return line, nil } // NOTE: Return if not a python-ini multi-line value. currentIdentSize := len(peekMatches[1]) if currentIdentSize <= 0 { return line, nil } // NOTE: Just advance the parser reader (buffer) in-sync with the peek buffer. _, err := p.readUntil('\n') if err != nil { return "", err } line += fmt.Sprintf("\n%s", peekMatches[2]) } } // parse parses data through an io.Reader. func (f *File) parse(reader io.Reader) (err error) { p := newParser(reader, parserOptions{ IgnoreContinuation: f.options.IgnoreContinuation, IgnoreInlineComment: f.options.IgnoreInlineComment, AllowPythonMultilineValues: f.options.AllowPythonMultilineValues, SpaceBeforeInlineComment: f.options.SpaceBeforeInlineComment, UnescapeValueDoubleQuotes: f.options.UnescapeValueDoubleQuotes, UnescapeValueCommentSymbols: f.options.UnescapeValueCommentSymbols, PreserveSurroundedQuote: f.options.PreserveSurroundedQuote, }) if err = p.BOM(); err != nil { return fmt.Errorf("BOM: %v", err) } // Ignore error because default section name is never empty string. name := DefaultSection if f.options.Insensitive { name = strings.ToLower(DefaultSection) } section, _ := f.NewSection(name) // This "last" is not strictly equivalent to "previous one" if current key is not the first nested key var isLastValueEmpty bool var lastRegularKey *Key var line []byte var inUnparseableSection bool // NOTE: Iterate and increase `currentPeekSize` until // the size of the parser buffer is found. // TODO(unknwon): When Golang 1.10 is the lowest version supported, replace with `parserBufferSize := p.buf.Size()`. parserBufferSize := 0 // NOTE: Peek 1kb at a time. currentPeekSize := 1024 if f.options.AllowPythonMultilineValues { for { peekBytes, _ := p.buf.Peek(currentPeekSize) peekBytesLength := len(peekBytes) if parserBufferSize >= peekBytesLength { break } currentPeekSize *= 2 parserBufferSize = peekBytesLength } } for !p.isEOF { line, err = p.readUntil('\n') if err != nil { return err } if f.options.AllowNestedValues && isLastValueEmpty && len(line) > 0 { if line[0] == ' ' || line[0] == '\t' { lastRegularKey.addNestedValue(string(bytes.TrimSpace(line))) continue } } line = bytes.TrimLeftFunc(line, unicode.IsSpace) if len(line) == 0 { continue } // Comments if line[0] == '#' || line[0] == ';' { // Note: we do not care ending line break, // it is needed for adding second line, // so just clean it once at the end when set to value. p.comment.Write(line) continue } // Section if line[0] == '[' { // Read to the next ']' (TODO: support quoted strings) closeIdx := bytes.LastIndexByte(line, ']') if closeIdx == -1 { return fmt.Errorf("unclosed section: %s", line) } name := string(line[1:closeIdx]) section, err = f.NewSection(name) if err != nil { return err } comment, has := cleanComment(line[closeIdx+1:]) if has { p.comment.Write(comment) } section.Comment = strings.TrimSpace(p.comment.String()) // Reset aotu-counter and comments p.comment.Reset() p.count = 1 inUnparseableSection = false for i := range f.options.UnparseableSections { if f.options.UnparseableSections[i] == name || (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) { inUnparseableSection = true continue } } continue } if inUnparseableSection { section.isRawSection = true section.rawBody += string(line) continue } kname, offset, err := readKeyName(f.options.KeyValueDelimiters, line) if err != nil { // Treat as boolean key when desired, and whole line is key name. if IsErrDelimiterNotFound(err) { switch { case f.options.AllowBooleanKeys: kname, err := p.readValue(line, parserBufferSize) if err != nil { return err } key, err := section.NewBooleanKey(kname) if err != nil { return err } key.Comment = strings.TrimSpace(p.comment.String()) p.comment.Reset() continue case f.options.SkipUnrecognizableLines: continue } } return err } // Auto increment. isAutoIncr := false if kname == "-" { isAutoIncr = true kname = "#" + strconv.Itoa(p.count) p.count++ } value, err := p.readValue(line[offset:], parserBufferSize) if err != nil { return err } isLastValueEmpty = len(value) == 0 key, err := section.NewKey(kname, value) if err != nil { return err } key.isAutoIncrement = isAutoIncr key.Comment = strings.TrimSpace(p.comment.String()) p.comment.Reset() lastRegularKey = key } return nil }
vendor/gopkg.in/ini.v1/parser.go
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.00017996999667957425, 0.00017392748850397766, 0.00015665577666368335, 0.00017504517745692283, 0.0000037742124732176308 ]
{ "id": 0, "code_window": [ " const cellTarget = column.style.linkTargetBlank ? '_blank' : '';\n", "\n", " cellClasses.push('table-panel-cell-link');\n", "\n", " columnHtml += `\n", " <a href=\"${sanitizedCellLink}\" target=\"${cellTarget}\" data-link-tooltip data-original-title=\"${cellLinkTooltip}\" data-placement=\"right\"${cellStyle}>\n", " ${value}\n", " </a>\n", " `;\n", " } else {\n", " columnHtml += value;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " columnHtml += `<a href=\"${sanitizedCellLink}\" target=\"${cellTarget}\" data-link-tooltip data-original-title=\"${cellLinkTooltip}\" data-placement=\"right\"${cellStyle}>`;\n", " columnHtml += `${value}`;\n", " columnHtml += `</a>`;\n" ], "file_path": "public/app/plugins/panel/table/renderer.ts", "type": "replace", "edit_start_line_idx": 307 }
+++ title = "What's New in Grafana v6.6" description = "Feature and improvement highlights for Grafana v6.6" keywords = ["grafana", "new", "documentation", "6.6"] type = "docs" [menu.docs] name = "Version 6.6" identifier = "v6.6" parent = "whatsnew" weight = -16 +++ # What's New in Grafana v6.6 For all details, read the full [CHANGELOG.md](https://github.com/grafana/grafana/blob/master/CHANGELOG.md) ## Highlights Grafana 6.6 comes with a lot of new features and enhancements: - [**Panels:** New stat panel]({{< relref "#new-stat-panel" >}}) - [**Panels:** Auto min/max for Bar Gauge/Gauge/Stat]({{< relref "#auto-min-max" >}}) - [**Panels:** News panel]({{< relref "#news-panel" >}}) - [**Panels:** Custom data units]({{< relref "#custom-data-units" >}}) - [**Panels:** Bar Gauge unfilled option]({{< relref "#bar-gauge-unfilled-option" >}}) - [**TimePicker:** New design & features]({{< relref "#new-time-picker" >}}) - [**Alerting enhancements**]({{< relref "#alerting-enhancements" >}}) - [**Explore:** Added log message line wrapping options for logs]({{< relref "#explore-logs-panel-log-message-line-wrapping-options" >}}) - [**Explore:** Column with unique log labels ]({{< relref "#explore-logs-panel-column-with-unique-log-labels" >}}) - [**Explore:** Context tooltip]({{< relref "#explore-context-tooltip" >}}) - **Explore:** Added ability to specify step with Prometheus queries - **Graphite:** Added Metrictank dashboard to Graphite datasource - **Loki:** Support for template variable queries - **Postgres/MySQL/MSSQL:** Added support for region annotations - [**Security:** Added disabled option for cookie samesite attribute]({{< relref "#cookie-management-modifications" >}}) - **TablePanel, GraphPanel:** Exclude hidden columns from CSV - [**Enterprise:** White labeling]({{< relref "#enterprise-white-labeling" >}}) - [**Enterprise:** APT and YUM repositories]({{< relref "#enterprise-apt-and-yum-repositories" >}}) - [**Stackdriver:** Meta labels]({{< relref "#stackdriver-meta-labels" >}}) - [**CloudWatch:** Calculate period based on time range]({{< relref "#cloudwatch-calculate-period-based-on-time-range" >}}) - [**CloudWatch:** Display partial result in graph when max DP/call limit is reached]({{< relref "#cloudwatch-display-partial-result-in-graph-when-max-data-points-per-call-limit-is-reached" >}}) ## New stat panel {{< docs-imagebox img="/img/docs/v66/stat_panel_dark2.png" max-width="1024px" caption="Stat panel" >}} This release adds a new panel named `Stat`. This panel is designed to replace the current `Singlestat` as the primary way to show big single number panels along with a sparkline. This panel is of course building on our new panel infrastructure and option design. So you can use the new threshold UI and data links. It also supports the same repeating feature as the Gauge and Bar Gauge panels, meaning it will repeat a separate visualization for every series or row in the query result. Key features: - Automatic font size handling - Automatic layout handling based on panel size - Colors based on thresholds that adapt to light or dark theme - Data links support - Repeats horizontally or vertically for every series, row, or column Here is how it looks in light theme: {{< docs-imagebox img="/img/docs/v66/stat_panel_light.png" max-width="1024px" caption="Stat panel" >}} ## Auto min-max For the panels Gauge, Bar Gauge, and Stat, you can now leave the min and max settings empty. Grafana will, in that case, calculate the min and max based on all the data. ## News panel This panel shows RSS feeds as news items in the default home dashboard for v6.6. Add it to your custom home dashboards to keep up-to-date with Grafana news, or switch the default RSS feed to one of your choice. {{< docs-imagebox img="/img/docs/v66/news_panel.png" max-width="600px" caption="News panel" >}} ## Custom data units A top feature request for years is now finally here. All panels now support custom units. Type any text in the unit picker and select the `Custom: <your unit>` option. By default, the text will be used as a suffix unit. If you want a custom prefix, then type `prefix: <your unit> ` to make the custom unit appear before the value. If you want a custom SI unit (with auto SI suffixes) specify `si:Ups`. A value like 1000 will be rendered as `1 kUps`. {{< docs-imagebox img="/img/docs/v66/custom_unit_burger1.png" max-width="600px" caption="Custom unit" >}} You can also paste a native emoji in the unit picker and pick it as a custom unit: {{< docs-imagebox img="/img/docs/v66/custom_unit_burger2.png" max-width="600px" caption="Custom unit emoji" >}} ## Bar Gauge unfilled option The Bar Gauge visualization has a new display option: `Unfilled`. This new option is enabled by default, so it will change how this visualization is displayed on old dashboards. If you prefer the old default -- in which an unfilled area is not shown and the value follows directly after -- you have to update the visualization settings. {{< docs-imagebox img="/img/docs/v66/bar_gauge_unfilled.png" max-width="900px" caption="Bar gauge unfilled" >}} ## New time picker The time picker has gotten a major design update. Key changes: - Quickly access the absolute from and to input fields without an extra click. - Calendar automatically shows when from or to inputs have focus. - A single calendar view can be used to select and show the from and to date. - You can now select recent absolute ranges. {{< docs-imagebox img="/img/docs/v66/time_picker_update.png" max-width="700px" caption="New time picker" >}} ## Alerting enhancements - We have introduced a new configuration for enforcing a minimal interval between evaluations to reduce load on the backend. - The email notifier can now optionally send a single email to all recipients. - OpsGenie, PagerDuty, Threema, and Google Chat notifiers have been updated to send additional information. ## Cookie management modifications In order to align with a [change in Chrome 80](https://www.chromestatus.com/feature/5088147346030592), a breaking change has been introduced to Grafana's [`cookie_samesite` setting]({{< relref "../installation/configuration.md#cookie-samesite" >}}). Grafana now properly renders cookies with the `SameSite=None` attribute when this setting is `none`. The previous behavior of `none` was to omit the `SameSite` attribute from cookies. Grafana will use the previous behavior when `cookie_samesite` is set to `disabled`. Read more about this in the [upgrade notes]({{< relref "../installation/upgrading/#important-changes-regarding-samesite-cookie-attribute" >}}). ## Explore/Logs Panel: Log message line wrapping options We introduced the wrap-lines option for logs because as for some of our users feel it's more efficient to see one line per log message. The wrapped-line option is set as a default; the unwrapped setting results in horizontal scrolling. {{< docs-imagebox img="/img/docs/v66/explore_wrap_lines.gif" max-width="600px" caption="Log message line wrapping" >}} ## Explore/Logs Panel: Column with unique log labels After feedback from our community, we have decided to reintroduce a labels column. However, for better readability and usefulness, we have transformed it into a Unique labels column which includes only non-common labels. All common labels are displayed above. {{< docs-imagebox img="/img/docs/v66/explore_labels_column.png" max-width="600px" caption="Unique log labels column" >}} ## Explore: Context tooltip Isolating a series from a big set of lines in a graph is important for drill-downs. That's why we have implemented the context tooltip in Explore, which allows you to copy data and labels from it to further refine the query. {{< docs-imagebox img="/img/docs/v66/explore_context_tooltip.png" max-width="600px" caption="Explore context tooltip" >}} ## Enterprise: White labeling This release adds new white labeling options to the grafana.ini file (can also be set via ENV variables). ```bash [white_labeling] # Set to complete url to override login logo login_logo = https://my.logo.url/images/logo.png # Set to complete css background expression to override login background login_background = url(http://www.bhmpics.com/wallpapers/starfield-1920x1080.jpg) # Set to complete url to override menu logo menu_logo = https://my.logo.url/images/logo_icon.png # Set to complete url to override fav icon (icon shown in browser tab) fav_icon = https://my.logo.url/images/logo_icon_32px.png # Set to complete url to override apple/ios icon apple_touch_icon = https://my.logo.url/images/logo_icon_32px.png # Below is an example for how to replace the default footer & help links with 2 custom links footer_links = support guides footer_links_support_text = Support footer_links_support_url = http://your.support.site footer_links_guides_text = Guides footer_links_guides_url = http://your.guides.site ``` Customize the login page, side menu bar, and footer links. {{< docs-imagebox img="/img/docs/v66/whitelabeling_1.png" max-width="700px" caption="White labeling example" >}} ## Enterprise APT and YUM repositories Now you can install the enterprise edition from the APT and YUM repository. The following table shows the APT repository for each Grafana version (for instructions read the [installation notes]({{< relref "../installation/debian/#install-from-apt-repository" >}})) : | Grafana Version | Package | Repository | |-----------------|---------|------------| | Grafana OSS | grafana | `https://packages.grafana.com/oss/deb stable main` | | Grafana OSS (Beta) | grafana | `https://packages.grafana.com/oss/deb beta main` | | Grafana Enterprise | grafana-enterprise | `https://packages.grafana.com/enterprise/deb stable main` | | Grafana Enterprise (Beta) | grafana-enterprise | `https://packages.grafana.com/enterprise/deb beta main` | The following table shows the YUM repositories for each Grafana version (for instructions read the [installation notes]({{< relref "../installation/rpm/#install-from-yum-repository" >}})) : | Grafana Version | Package | Repository | |----------------------------|--------------------|----------------------------------------------------| | Grafana OSS | grafana | `https://packages.grafana.com/oss/rpm` | | Grafana OSS (Beta) | grafana | `https://packages.grafana.com/oss/rpm-beta` | | Grafana Enterprise | grafana-enterprise | `https://packages.grafana.com/enterprise/rpm` | | Grafana Enterprise (Beta) | grafana-enterprise | `https://packages.grafana.com/enterprise/rpm-beta` | We recommend all users to install the Enterprise Edition of Grafana, which can be seamlessly upgraded with a Grafana Enterprise [subscription](https://grafana.com/products/enterprise/?utm_source=grafana-install-page). ## Stackdriver: Meta labels From now on it will be possible to utilize meta data label in group bys, filters and in the alias field. Unfortunaltey there's no API to retrieve all the labels, but the group by field dropdown comes with a pre-defined list of common system labels. User labels cannot be pre-defined, but it's possible to enter them manually in the group by field. If a meta data label, user label or system label, is included in the group by segment, it will be possible to create filters based on it and to expand its value on the alias field. {{< docs-imagebox img="/img/docs/v66/metadatalabels.gif" max-width="800px" caption="Stackdriver meta labels" >}} ## CloudWatch: Calculate period based on time range When the period field was left blank in Grafana 6.5, it would default to 60 seconds. In case users issued queries with a large time span, there was a high risk that they would reach the 100,800 data points per request limit in the Get Metric Data (GMD) api. When the period field is left blank in Grafana 6.6, the period will be calculated automatically based on the time range. The formula that is used is `time range in seconds / 2000`, and then we snap to next higher value in an array of pre-defined periods `[60, 300, 900, 3600, 21600, 86400]`. This will reduce the risk for receiving a `Too many datapoints requested` error in the panel. ## CloudWatch: Display partial result in graph when max data points per call limit is reached In case all queries in a GMD call are metric stat (not using math expressions), Grafana will paginate the response until all data points are received. But pagination is not supported in case a math expression is being used, so in that case it's not possible to receive more than 100,800 data points. Previously when that limit was reached, we only displayed an error message. In Grafana 6.6, we also display the 100,800 data points that were received in the graph. ## Upgrading See [upgrade notes]({{< relref "../installation/upgrading/#upgrading-to-v6-6" >}}). ## Changelog Check out [CHANGELOG.md](https://github.com/grafana/grafana/blob/master/CHANGELOG.md) for a complete list of new features, changes, and bug fixes. ## Notice about upcoming changes in backendSrv for plugin authors In our mission to migrate away from AngularJS to React we have removed all AngularJS dependencies in the core data retrieval service `backendSrv`. This change is already in master and will be introduced in the next `major` Grafana release. Removing the AngularJS dependencies in `backendSrv` has the unfortunate side effect of AngularJS digest no longer being triggered for any request made with `backendSrv`. Because of this, external plugins using `backendSrv` directly may suffer from strange behaviour in the UI. To remedy this issue as a plugin author you need to trigger the digest after a direct call to `backendSrv`. Example: ```js backendSrv.get(‘http://your.url/api’).then(result => { this.result = result; this.$scope.$digest(); }); ```
docs/sources/guides/whats-new-in-v6-6.md
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.0002117199619533494, 0.00017217444838024676, 0.0001608117891009897, 0.0001721624721540138, 0.000009592087735654786 ]
{ "id": 1, "code_window": [ "\n", " if (column.filterable) {\n", " cellClasses.push('table-panel-cell-filterable');\n", " columnHtml += `\n", " <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"!=\">\n", " <i class=\"fa fa-search-minus\"></i>\n", " </a>\n", " <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"=\">\n", " <i class=\"fa fa-search-plus\"></i>\n", " </a>`;\n", " }\n", "\n", " if (cellClasses.length) {\n", " cellClass = ' class=\"' + cellClasses.join(' ') + '\"';\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " columnHtml += `<a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"!=\">`;\n", " columnHtml += `<i class=\"fa fa-search-minus\"></i>`;\n", " columnHtml += `</a>`;\n", " columnHtml += `<a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"=\">`;\n", " columnHtml += `<i class=\"fa fa-search-plus\"></i>`;\n", " columnHtml += `</a>`;\n" ], "file_path": "public/app/plugins/panel/table/renderer.ts", "type": "replace", "edit_start_line_idx": 318 }
import _ from 'lodash'; import { dateTime, escapeStringForRegex, formattedValueToString, getColorFromHexRgbOrName, getValueFormat, GrafanaThemeType, ScopedVars, stringStartsAsRegEx, stringToJsRegex, unEscapeStringFromRegex, } from '@grafana/data'; import { TemplateSrv } from 'app/features/templating/template_srv'; import { ColumnRender, TableRenderModel, ColumnStyle } from './types'; import { ColumnOptionsCtrl } from './column_options'; import { sanitizeUrl } from 'app/core/utils/text'; export class TableRenderer { formatters: any[]; colorState: any; constructor( private panel: { styles: ColumnStyle[]; pageSize: number }, private table: TableRenderModel, private isUtc: boolean, private sanitize: (v: any) => any, private templateSrv: TemplateSrv, private theme?: GrafanaThemeType ) { this.initColumns(); } setTable(table: TableRenderModel) { this.table = table; this.initColumns(); } initColumns() { this.formatters = []; this.colorState = {}; for (let colIndex = 0; colIndex < this.table.columns.length; colIndex++) { const column = this.table.columns[colIndex]; column.title = column.text; for (let i = 0; i < this.panel.styles.length; i++) { const style = this.panel.styles[i]; const escapedPattern = stringStartsAsRegEx(style.pattern) ? style.pattern : escapeStringForRegex(unEscapeStringFromRegex(style.pattern)); const regex = stringToJsRegex(escapedPattern); if (column.text.match(regex)) { column.style = style; if (style.alias) { column.title = column.text.replace(regex, style.alias); } break; } } this.formatters[colIndex] = this.createColumnFormatter(column); } } getColorForValue(value: number, style: ColumnStyle) { if (!style.thresholds || !style.colors) { return null; } for (let i = style.thresholds.length; i > 0; i--) { if (value >= style.thresholds[i - 1]) { return getColorFromHexRgbOrName(style.colors[i], this.theme); } } return getColorFromHexRgbOrName(_.first(style.colors), this.theme); } defaultCellFormatter(v: any, style: ColumnStyle) { if (v === null || v === void 0 || v === undefined) { return ''; } if (_.isArray(v)) { v = v.join(', '); } if (style && style.sanitize) { return this.sanitize(v); } else { return _.escape(v); } } createColumnFormatter(column: ColumnRender) { if (!column.style) { return this.defaultCellFormatter; } if (column.style.type === 'hidden') { return (v: any): undefined => undefined; } if (column.style.type === 'date') { return (v: any) => { if (v === undefined || v === null) { return '-'; } if (_.isArray(v)) { v = v[0]; } // if is an epoch (numeric string and len > 12) if (_.isString(v) && !isNaN(v as any) && v.length > 12) { v = parseInt(v, 10); } let date = dateTime(v); if (this.isUtc) { date = date.utc(); } return date.format(column.style.dateFormat); }; } if (column.style.type === 'string') { return (v: any): any => { if (_.isArray(v)) { v = v.join(', '); } const mappingType = column.style.mappingType || 0; if (mappingType === 1 && column.style.valueMaps) { for (let i = 0; i < column.style.valueMaps.length; i++) { const map = column.style.valueMaps[i]; if (v === null) { if (map.value === 'null') { return map.text; } continue; } // Allow both numeric and string values to be mapped if ((!_.isString(v) && Number(map.value) === Number(v)) || map.value === v) { this.setColorState(v, column.style); return this.defaultCellFormatter(map.text, column.style); } } } if (mappingType === 2 && column.style.rangeMaps) { for (let i = 0; i < column.style.rangeMaps.length; i++) { const map = column.style.rangeMaps[i]; if (v === null) { if (map.from === 'null' && map.to === 'null') { return map.text; } continue; } if (Number(map.from) <= Number(v) && Number(map.to) >= Number(v)) { this.setColorState(v, column.style); return this.defaultCellFormatter(map.text, column.style); } } } if (v === null || v === void 0) { return '-'; } this.setColorState(v, column.style); return this.defaultCellFormatter(v, column.style); }; } if (column.style.type === 'number') { const valueFormatter = getValueFormat(column.unit || column.style.unit); return (v: any): any => { if (v === null || v === void 0) { return '-'; } if (isNaN(v) || _.isArray(v)) { return this.defaultCellFormatter(v, column.style); } this.setColorState(v, column.style); return formattedValueToString(valueFormatter(v, column.style.decimals, null)); }; } return (value: any) => { return this.defaultCellFormatter(value, column.style); }; } setColorState(value: any, style: ColumnStyle) { if (!style.colorMode) { return; } if (value === null || value === void 0 || _.isArray(value)) { return; } const numericValue = Number(value); if (isNaN(numericValue)) { return; } this.colorState[style.colorMode] = this.getColorForValue(numericValue, style); } renderRowVariables(rowIndex: number) { const scopedVars: ScopedVars = {}; let cellVariable; const row = this.table.rows[rowIndex]; for (let i = 0; i < row.length; i++) { cellVariable = `__cell_${i}`; scopedVars[cellVariable] = { value: row[i], text: row[i] ? row[i].toString() : '' }; } return scopedVars; } formatColumnValue(colIndex: number, value: any) { const fmt = this.formatters[colIndex]; if (fmt) { return fmt(value); } return value; } renderCell(columnIndex: number, rowIndex: number, value: any, addWidthHack = false) { value = this.formatColumnValue(columnIndex, value); const column = this.table.columns[columnIndex]; const cellStyles = []; let cellStyle = ''; const cellClasses = []; let cellClass = ''; if (this.colorState.cell) { cellStyles.push('background-color:' + this.colorState.cell); cellClasses.push('table-panel-color-cell'); this.colorState.cell = null; } else if (this.colorState.value) { cellStyles.push('color:' + this.colorState.value); this.colorState.value = null; } // because of the fixed table headers css only solution // there is an issue if header cell is wider the cell // this hack adds header content to cell (not visible) let columnHtml = ''; if (addWidthHack) { columnHtml = '<div class="table-panel-width-hack">' + this.table.columns[columnIndex].title + '</div>'; } if (value === undefined) { cellStyles.push('display:none'); column.hidden = true; } else { column.hidden = false; } if (column.hidden === true) { return ''; } if (column.style && column.style.preserveFormat) { cellClasses.push('table-panel-cell-pre'); } if (column.style && column.style.align) { const textAlign = _.find(ColumnOptionsCtrl.alignTypesEnum, ['text', column.style.align]); if (textAlign && textAlign['value']) { cellStyles.push(`text-align:${textAlign['value']}`); } } if (cellStyles.length) { cellStyle = ' style="' + cellStyles.join(';') + '"'; } if (column.style && column.style.link) { // Render cell as link const scopedVars = this.renderRowVariables(rowIndex); scopedVars['__cell'] = { value: value, text: value ? value.toString() : '' }; const cellLink = this.templateSrv.replace(column.style.linkUrl, scopedVars, encodeURIComponent); const sanitizedCellLink = sanitizeUrl(cellLink); const cellLinkTooltip = this.templateSrv.replace(column.style.linkTooltip, scopedVars); const cellTarget = column.style.linkTargetBlank ? '_blank' : ''; cellClasses.push('table-panel-cell-link'); columnHtml += ` <a href="${sanitizedCellLink}" target="${cellTarget}" data-link-tooltip data-original-title="${cellLinkTooltip}" data-placement="right"${cellStyle}> ${value} </a> `; } else { columnHtml += value; } if (column.filterable) { cellClasses.push('table-panel-cell-filterable'); columnHtml += ` <a class="table-panel-filter-link" data-link-tooltip data-original-title="Filter out value" data-placement="bottom" data-row="${rowIndex}" data-column="${columnIndex}" data-operator="!="> <i class="fa fa-search-minus"></i> </a> <a class="table-panel-filter-link" data-link-tooltip data-original-title="Filter for value" data-placement="bottom" data-row="${rowIndex}" data-column="${columnIndex}" data-operator="="> <i class="fa fa-search-plus"></i> </a>`; } if (cellClasses.length) { cellClass = ' class="' + cellClasses.join(' ') + '"'; } columnHtml = '<td' + cellClass + cellStyle + '>' + columnHtml + '</td>'; return columnHtml; } render(page: number) { const pageSize = this.panel.pageSize || 100; const startPos = page * pageSize; const endPos = Math.min(startPos + pageSize, this.table.rows.length); let html = ''; for (let y = startPos; y < endPos; y++) { const row = this.table.rows[y]; let cellHtml = ''; let rowStyle = ''; const rowClasses = []; let rowClass = ''; for (let i = 0; i < this.table.columns.length; i++) { cellHtml += this.renderCell(i, y, row[i], y === startPos); } if (this.colorState.row) { rowStyle = ' style="background-color:' + this.colorState.row + '"'; rowClasses.push('table-panel-color-row'); this.colorState.row = null; } if (rowClasses.length) { rowClass = ' class="' + rowClasses.join(' ') + '"'; } html += '<tr ' + rowClass + rowStyle + '>' + cellHtml + '</tr>'; } return html; } render_values() { const rows = []; const visibleColumns = this.table.columns.filter(column => !column.hidden); for (let y = 0; y < this.table.rows.length; y++) { const row = this.table.rows[y]; const newRow = []; for (let i = 0; i < this.table.columns.length; i++) { if (!this.table.columns[i].hidden) { newRow.push(this.formatColumnValue(i, row[i])); } } rows.push(newRow); } return { columns: visibleColumns, rows: rows, }; } }
public/app/plugins/panel/table/renderer.ts
1
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.997143566608429, 0.09685693681240082, 0.00016258968389593065, 0.0005869329324923456, 0.2824845016002655 ]
{ "id": 1, "code_window": [ "\n", " if (column.filterable) {\n", " cellClasses.push('table-panel-cell-filterable');\n", " columnHtml += `\n", " <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"!=\">\n", " <i class=\"fa fa-search-minus\"></i>\n", " </a>\n", " <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"=\">\n", " <i class=\"fa fa-search-plus\"></i>\n", " </a>`;\n", " }\n", "\n", " if (cellClasses.length) {\n", " cellClass = ' class=\"' + cellClasses.join(' ') + '\"';\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " columnHtml += `<a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"!=\">`;\n", " columnHtml += `<i class=\"fa fa-search-minus\"></i>`;\n", " columnHtml += `</a>`;\n", " columnHtml += `<a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"=\">`;\n", " columnHtml += `<i class=\"fa fa-search-plus\"></i>`;\n", " columnHtml += `</a>`;\n" ], "file_path": "public/app/plugins/panel/table/renderer.ts", "type": "replace", "edit_start_line_idx": 318 }
user1:$apr1$1odeeQb.$kwV8D/VAAGUDU7pnHuKoV0 user2:$apr1$A2kf25r.$6S0kp3C7vIuixS5CL0XA9. admin:$apr1$IWn4DoRR$E2ol7fS/dkI18eU4bXnBO1
devenv/docker/blocks/nginx_proxy/htpasswd
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.00016858955495990813, 0.00016858955495990813, 0.00016858955495990813, 0.00016858955495990813, 0 ]
{ "id": 1, "code_window": [ "\n", " if (column.filterable) {\n", " cellClasses.push('table-panel-cell-filterable');\n", " columnHtml += `\n", " <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"!=\">\n", " <i class=\"fa fa-search-minus\"></i>\n", " </a>\n", " <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"=\">\n", " <i class=\"fa fa-search-plus\"></i>\n", " </a>`;\n", " }\n", "\n", " if (cellClasses.length) {\n", " cellClass = ' class=\"' + cellClasses.join(' ') + '\"';\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " columnHtml += `<a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"!=\">`;\n", " columnHtml += `<i class=\"fa fa-search-minus\"></i>`;\n", " columnHtml += `</a>`;\n", " columnHtml += `<a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"=\">`;\n", " columnHtml += `<i class=\"fa fa-search-plus\"></i>`;\n", " columnHtml += `</a>`;\n" ], "file_path": "public/app/plugins/panel/table/renderer.ts", "type": "replace", "edit_start_line_idx": 318 }
package migrations import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator" func addUserAuthMigrations(mg *Migrator) { userAuthV1 := Table{ Name: "user_auth", Columns: []*Column{ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true}, {Name: "user_id", Type: DB_BigInt, Nullable: false}, {Name: "auth_module", Type: DB_NVarchar, Length: 190, Nullable: false}, {Name: "auth_id", Type: DB_NVarchar, Length: 100, Nullable: false}, {Name: "created", Type: DB_DateTime, Nullable: false}, }, Indices: []*Index{ {Cols: []string{"auth_module", "auth_id"}}, }, } // create table mg.AddMigration("create user auth table", NewAddTableMigration(userAuthV1)) // add indices addTableIndicesMigrations(mg, "v1", userAuthV1) mg.AddMigration("alter user_auth.auth_id to length 190", NewRawSqlMigration(""). Postgres("ALTER TABLE user_auth ALTER COLUMN auth_id TYPE VARCHAR(190);"). Mysql("ALTER TABLE user_auth MODIFY auth_id VARCHAR(190);")) mg.AddMigration("Add OAuth access token to user_auth", NewAddColumnMigration(userAuthV1, &Column{ Name: "o_auth_access_token", Type: DB_Text, Nullable: true, })) mg.AddMigration("Add OAuth refresh token to user_auth", NewAddColumnMigration(userAuthV1, &Column{ Name: "o_auth_refresh_token", Type: DB_Text, Nullable: true, })) mg.AddMigration("Add OAuth token type to user_auth", NewAddColumnMigration(userAuthV1, &Column{ Name: "o_auth_token_type", Type: DB_Text, Nullable: true, })) mg.AddMigration("Add OAuth expiry to user_auth", NewAddColumnMigration(userAuthV1, &Column{ Name: "o_auth_expiry", Type: DB_DateTime, Nullable: true, })) mg.AddMigration("Add index to user_id column in user_auth", NewAddIndexMigration(userAuthV1, &Index{ Cols: []string{"user_id"}, })) }
pkg/services/sqlstore/migrations/user_auth_mig.go
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.00016933678125496954, 0.0001673687220318243, 0.00016341981245204806, 0.00016814647824503481, 0.000002046580220849137 ]
{ "id": 1, "code_window": [ "\n", " if (column.filterable) {\n", " cellClasses.push('table-panel-cell-filterable');\n", " columnHtml += `\n", " <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"!=\">\n", " <i class=\"fa fa-search-minus\"></i>\n", " </a>\n", " <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"=\">\n", " <i class=\"fa fa-search-plus\"></i>\n", " </a>`;\n", " }\n", "\n", " if (cellClasses.length) {\n", " cellClass = ' class=\"' + cellClasses.join(' ') + '\"';\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " columnHtml += `<a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"!=\">`;\n", " columnHtml += `<i class=\"fa fa-search-minus\"></i>`;\n", " columnHtml += `</a>`;\n", " columnHtml += `<a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n", " data-row=\"${rowIndex}\" data-column=\"${columnIndex}\" data-operator=\"=\">`;\n", " columnHtml += `<i class=\"fa fa-search-plus\"></i>`;\n", " columnHtml += `</a>`;\n" ], "file_path": "public/app/plugins/panel/table/renderer.ts", "type": "replace", "edit_start_line_idx": 318 }
package login import ( "testing" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" log "github.com/inconshreveable/log15" "github.com/stretchr/testify/require" ) func Test_syncOrgRoles_doesNotBreakWhenTryingToRemoveLastOrgAdmin(t *testing.T) { user := createSimpleUser() externalUser := createSimpleExternalUser() remResp := createResponseWithOneErrLastOrgAdminItem() bus.ClearBusHandlers() defer bus.ClearBusHandlers() bus.AddHandler("test", func(q *models.GetUserOrgListQuery) error { q.Result = createUserOrgDTO() return nil }) bus.AddHandler("test", func(cmd *models.RemoveOrgUserCommand) error { testData := remResp[0] remResp = remResp[1:] require.Equal(t, testData.orgId, cmd.OrgId) return testData.response }) bus.AddHandler("test", func(cmd *models.SetUsingOrgCommand) error { return nil }) err := syncOrgRoles(&user, &externalUser) require.Empty(t, remResp) require.NoError(t, err) } func Test_syncOrgRoles_whenTryingToRemoveLastOrgLogsError(t *testing.T) { var logOutput string logger.SetHandler(log.FuncHandler(func(r *log.Record) error { logOutput = r.Msg return nil })) user := createSimpleUser() externalUser := createSimpleExternalUser() remResp := createResponseWithOneErrLastOrgAdminItem() bus.ClearBusHandlers() defer bus.ClearBusHandlers() bus.AddHandler("test", func(q *models.GetUserOrgListQuery) error { q.Result = createUserOrgDTO() return nil }) bus.AddHandler("test", func(cmd *models.RemoveOrgUserCommand) error { testData := remResp[0] remResp = remResp[1:] require.Equal(t, testData.orgId, cmd.OrgId) return testData.response }) bus.AddHandler("test", func(cmd *models.SetUsingOrgCommand) error { return nil }) err := syncOrgRoles(&user, &externalUser) require.NoError(t, err) require.Equal(t, models.ErrLastOrgAdmin.Error(), logOutput) } func createSimpleUser() models.User { user := models.User{ Id: 1, } return user } func createUserOrgDTO() []*models.UserOrgDTO { users := []*models.UserOrgDTO{ { OrgId: 1, Name: "Bar", Role: models.ROLE_VIEWER, }, { OrgId: 10, Name: "Foo", Role: models.ROLE_ADMIN, }, { OrgId: 11, Name: "Stuff", Role: models.ROLE_VIEWER, }, } return users } func createSimpleExternalUser() models.ExternalUserInfo { externalUser := models.ExternalUserInfo{ AuthModule: "ldap", OrgRoles: map[int64]models.RoleType{ 1: models.ROLE_VIEWER, }, } return externalUser } func createResponseWithOneErrLastOrgAdminItem() []struct { orgId int64 response error } { remResp := []struct { orgId int64 response error }{ { orgId: 10, response: models.ErrLastOrgAdmin, }, { orgId: 11, response: nil, }, } return remResp }
pkg/services/login/login_test.go
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.00017351038695778698, 0.00017112074419856071, 0.00016672539641149342, 0.00017130939522758126, 0.0000015584809034407954 ]
{ "id": 2, "code_window": [ " it('link should render as', () => {\n", " const html = renderer.renderCell(7, 0, 'host1');\n", " const expectedHtml = `\n", " <td class=\"table-panel-cell-link\">\n", " <a href=\"/dashboard?param=host1&param_1=1230&param_2=40\"\n", " target=\"_blank\" data-link-tooltip data-original-title=\"host1 1230 my.host.com\" data-placement=\"right\">\n", " host1\n", " </a>\n", " </td>\n", " `;\n", " expect(normalize(html)).toBe(normalize(expectedHtml));\n", " });\n", "\n", " it('Array column should not use number as formatter', () => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td class=\"table-panel-cell-link\"><a href=\"/dashboard?param=host1&param_1=1230&param_2=40\"\n", " target=\"_blank\" data-link-tooltip data-original-title=\"host1 1230 my.host.com\"\n", "\t\t\tdata-placement=\"right\">host1</a></td>\n" ], "file_path": "public/app/plugins/panel/table/specs/renderer.test.ts", "type": "replace", "edit_start_line_idx": 319 }
import _ from 'lodash'; import TableModel from 'app/core/table_model'; import { TableRenderer } from '../renderer'; import { getColorDefinitionByName, ScopedVars } from '@grafana/data'; import { ColumnRender } from '../types'; const sanitize = (value: any): string => { return 'sanitized'; }; const templateSrv = { replace: (value: any, scopedVars: ScopedVars) => { if (scopedVars) { // For testing variables replacement in link _.each(scopedVars, (val, key) => { value = value.replace('$' + key, val.value); }); } return value; }, }; describe('when rendering table', () => { const SemiDarkOrange = getColorDefinitionByName('semi-dark-orange'); describe('given 13 columns', () => { const table = new TableModel(); table.columns = [ { text: 'Time' }, { text: 'Value' }, { text: 'Colored' }, { text: 'Undefined' }, { text: 'String' }, { text: 'United', unit: 'bps' }, { text: 'Sanitized' }, { text: 'Link' }, { text: 'Array' }, { text: 'Mapping' }, { text: 'RangeMapping' }, { text: 'MappingColored' }, { text: 'RangeMappingColored' }, { text: 'HiddenType' }, { text: 'RightAligned' }, ]; table.rows = [ [ 1388556366666, 1230, 40, undefined, '', '', 'my.host.com', 'host1', ['value1', 'value2'], 1, 2, 1, 2, 'ignored', 42, ], ]; const panel = { pageSize: 10, styles: [ { pattern: 'Time', type: 'date', format: 'LLL', alias: 'Timestamp', }, { pattern: '/(Val)ue/', type: 'number', unit: 'ms', decimals: 3, alias: '$1', }, { pattern: 'Colored', type: 'number', unit: 'none', decimals: 1, colorMode: 'value', thresholds: [50, 80], colors: ['#00ff00', SemiDarkOrange.name, 'rgb(1,0,0)'], }, { pattern: 'String', type: 'string', }, { pattern: 'String', type: 'string', }, { pattern: 'United', type: 'number', unit: 'ms', decimals: 2, }, { pattern: 'Sanitized', type: 'string', sanitize: true, }, { pattern: 'Link', type: 'string', link: true, linkUrl: '/dashboard?param=$__cell&param_1=$__cell_1&param_2=$__cell_2', linkTooltip: '$__cell $__cell_1 $__cell_6', linkTargetBlank: true, }, { pattern: 'Array', type: 'number', unit: 'ms', decimals: 3, }, { pattern: 'Mapping', type: 'string', mappingType: 1, valueMaps: [ { value: '1', text: 'on', }, { value: '0', text: 'off', }, { value: 'HELLO WORLD', text: 'HELLO GRAFANA', }, { value: 'value1, value2', text: 'value3, value4', }, ], }, { pattern: 'RangeMapping', type: 'string', mappingType: 2, rangeMaps: [ { from: '1', to: '3', text: 'on', }, { from: '3', to: '6', text: 'off', }, ], }, { pattern: 'MappingColored', type: 'string', mappingType: 1, valueMaps: [ { value: '1', text: 'on', }, { value: '0', text: 'off', }, ], colorMode: 'value', thresholds: [1, 2], colors: ['#00ff00', SemiDarkOrange.name, 'rgb(1,0,0)'], }, { pattern: 'RangeMappingColored', type: 'string', mappingType: 2, rangeMaps: [ { from: '1', to: '3', text: 'on', }, { from: '3', to: '6', text: 'off', }, ], colorMode: 'value', thresholds: [2, 5], colors: ['#00ff00', SemiDarkOrange.name, 'rgb(1,0,0)'], }, { pattern: 'HiddenType', type: 'hidden', }, { pattern: 'RightAligned', align: 'right', }, ], }; //@ts-ignore const renderer = new TableRenderer(panel, table, 'utc', sanitize, templateSrv); it('time column should be formatted', () => { const html = renderer.renderCell(0, 0, 1388556366666); expect(html).toBe('<td>2014-01-01T06:06:06Z</td>'); }); it('time column with epoch as string should be formatted', () => { const html = renderer.renderCell(0, 0, '1388556366666'); expect(html).toBe('<td>2014-01-01T06:06:06Z</td>'); }); it('time column with RFC2822 date as string should be formatted', () => { const html = renderer.renderCell(0, 0, 'Sat, 01 Dec 2018 01:00:00 GMT'); expect(html).toBe('<td>2018-12-01T01:00:00Z</td>'); }); it('time column with ISO date as string should be formatted', () => { const html = renderer.renderCell(0, 0, '2018-12-01T01:00:00Z'); expect(html).toBe('<td>2018-12-01T01:00:00Z</td>'); }); it('undefined time column should be rendered as -', () => { const html = renderer.renderCell(0, 0, undefined); expect(html).toBe('<td>-</td>'); }); it('null time column should be rendered as -', () => { const html = renderer.renderCell(0, 0, null); expect(html).toBe('<td>-</td>'); }); it('number column with unit specified should ignore style unit', () => { const html = renderer.renderCell(5, 0, 1230); expect(html).toBe('<td>1.23 kbps</td>'); }); it('number column should be formated', () => { const html = renderer.renderCell(1, 0, 1230); expect(html).toBe('<td>1.230 s</td>'); }); it('number column should format numeric string values', () => { const html = renderer.renderCell(1, 0, '1230'); expect(html).toBe('<td>1.230 s</td>'); }); it('number style should ignore string non-numeric values', () => { const html = renderer.renderCell(1, 0, 'asd'); expect(html).toBe('<td>asd</td>'); }); it('colored cell should have style (handles HEX color values)', () => { const html = renderer.renderCell(2, 0, 40); expect(html).toBe('<td style="color:#00ff00">40.0</td>'); }); it('colored cell should have style (handles named color values', () => { const html = renderer.renderCell(2, 0, 55); expect(html).toBe(`<td style="color:${SemiDarkOrange.variants.dark}">55.0</td>`); }); it('colored cell should have style handles(rgb color values)', () => { const html = renderer.renderCell(2, 0, 85); expect(html).toBe('<td style="color:rgb(1,0,0)">85.0</td>'); }); it('unformated undefined should be rendered as string', () => { const html = renderer.renderCell(3, 0, 'value'); expect(html).toBe('<td>value</td>'); }); it('string style with escape html should return escaped html', () => { const html = renderer.renderCell(4, 0, '&breaking <br /> the <br /> row'); expect(html).toBe('<td>&amp;breaking &lt;br /&gt; the &lt;br /&gt; row</td>'); }); it('undefined formater should return escaped html', () => { const html = renderer.renderCell(3, 0, '&breaking <br /> the <br /> row'); expect(html).toBe('<td>&amp;breaking &lt;br /&gt; the &lt;br /&gt; row</td>'); }); it('undefined value should render as -', () => { const html = renderer.renderCell(3, 0, undefined); expect(html).toBe('<td></td>'); }); it('sanitized value should render as', () => { const html = renderer.renderCell(6, 0, 'text <a href="http://google.com">link</a>'); expect(html).toBe('<td>sanitized</td>'); }); it('Time column title should be Timestamp', () => { expect(table.columns[0].title).toBe('Timestamp'); }); it('Value column title should be Val', () => { expect(table.columns[1].title).toBe('Val'); }); it('Colored column title should be Colored', () => { expect(table.columns[2].title).toBe('Colored'); }); it('link should render as', () => { const html = renderer.renderCell(7, 0, 'host1'); const expectedHtml = ` <td class="table-panel-cell-link"> <a href="/dashboard?param=host1&param_1=1230&param_2=40" target="_blank" data-link-tooltip data-original-title="host1 1230 my.host.com" data-placement="right"> host1 </a> </td> `; expect(normalize(html)).toBe(normalize(expectedHtml)); }); it('Array column should not use number as formatter', () => { const html = renderer.renderCell(8, 0, ['value1', 'value2']); expect(html).toBe('<td>value1, value2</td>'); }); it('numeric value should be mapped to text', () => { const html = renderer.renderCell(9, 0, 1); expect(html).toBe('<td>on</td>'); }); it('string numeric value should be mapped to text', () => { const html = renderer.renderCell(9, 0, '0'); expect(html).toBe('<td>off</td>'); }); it('string value should be mapped to text', () => { const html = renderer.renderCell(9, 0, 'HELLO WORLD'); expect(html).toBe('<td>HELLO GRAFANA</td>'); }); it('array column value should be mapped to text', () => { const html = renderer.renderCell(9, 0, ['value1', 'value2']); expect(html).toBe('<td>value3, value4</td>'); }); it('value should be mapped to text (range)', () => { const html = renderer.renderCell(10, 0, 2); expect(html).toBe('<td>on</td>'); }); it('value should be mapped to text (range)', () => { const html = renderer.renderCell(10, 0, 5); expect(html).toBe('<td>off</td>'); }); it('array column value should not be mapped to text', () => { const html = renderer.renderCell(10, 0, ['value1', 'value2']); expect(html).toBe('<td>value1, value2</td>'); }); it('value should be mapped to text and colored cell should have style', () => { const html = renderer.renderCell(11, 0, 1); expect(html).toBe(`<td style="color:${SemiDarkOrange.variants.dark}">on</td>`); }); it('value should be mapped to text and colored cell should have style', () => { const html = renderer.renderCell(11, 0, '1'); expect(html).toBe(`<td style="color:${SemiDarkOrange.variants.dark}">on</td>`); }); it('value should be mapped to text and colored cell should have style', () => { const html = renderer.renderCell(11, 0, 0); expect(html).toBe('<td style="color:#00ff00">off</td>'); }); it('value should be mapped to text and colored cell should have style', () => { const html = renderer.renderCell(11, 0, '0'); expect(html).toBe('<td style="color:#00ff00">off</td>'); }); it('value should be mapped to text and colored cell should have style', () => { const html = renderer.renderCell(11, 0, '2.1'); expect(html).toBe('<td style="color:rgb(1,0,0)">2.1</td>'); }); it('value should be mapped to text (range) and colored cell should have style', () => { const html = renderer.renderCell(12, 0, 0); expect(html).toBe('<td style="color:#00ff00">0</td>'); }); it('value should be mapped to text (range) and colored cell should have style', () => { const html = renderer.renderCell(12, 0, 1); expect(html).toBe('<td style="color:#00ff00">on</td>'); }); it('value should be mapped to text (range) and colored cell should have style', () => { const html = renderer.renderCell(12, 0, 4); expect(html).toBe(`<td style="color:${SemiDarkOrange.variants.dark}">off</td>`); }); it('value should be mapped to text (range) and colored cell should have style', () => { const html = renderer.renderCell(12, 0, '7.1'); expect(html).toBe('<td style="color:rgb(1,0,0)">7.1</td>'); }); it('hidden columns should not be rendered', () => { const html = renderer.renderCell(13, 0, 'ignored'); expect(html).toBe(''); }); it('right aligned column should have correct text-align style', () => { const html = renderer.renderCell(14, 0, 42); expect(html).toBe('<td style="text-align:right">42</td>'); }); it('render_values should ignore hidden columns', () => { renderer.render(0); // this computes the hidden markers on the columns const { columns, rows } = renderer.render_values(); expect(rows).toHaveLength(1); expect(columns).toHaveLength(table.columns.length - 1); expect(columns.filter((col: ColumnRender) => col.hidden)).toHaveLength(0); }); }); }); describe('when rendering table with different patterns', () => { it.each` column | pattern | expected ${'Requests (Failed)'} | ${'/Requests \\(Failed\\)/'} | ${'<td>1.230 s</td>'} ${'Requests (Failed)'} | ${'/(Req)uests \\(Failed\\)/'} | ${'<td>1.230 s</td>'} ${'Requests (Failed)'} | ${'Requests (Failed)'} | ${'<td>1.230 s</td>'} ${'Requests (Failed)'} | ${'Requests \\(Failed\\)'} | ${'<td>1.230 s</td>'} ${'Requests (Failed)'} | ${'/.*/'} | ${'<td>1.230 s</td>'} ${'Some other column'} | ${'/.*/'} | ${'<td>1.230 s</td>'} ${'Requests (Failed)'} | ${'/Requests (Failed)/'} | ${'<td>1230</td>'} ${'Requests (Failed)'} | ${'Response (Failed)'} | ${'<td>1230</td>'} `( 'number column should be formatted for a column:$column with the pattern:$pattern', ({ column, pattern, expected }) => { const table = new TableModel(); table.columns = [{ text: 'Time' }, { text: column }]; table.rows = [[1388556366666, 1230]]; const panel = { pageSize: 10, styles: [ { pattern: 'Time', type: 'date', format: 'LLL', alias: 'Timestamp', }, { pattern: pattern, type: 'number', unit: 'ms', decimals: 3, alias: pattern, }, ], }; //@ts-ignore const renderer = new TableRenderer(panel, table, 'utc', sanitize, templateSrv); const html = renderer.renderCell(1, 0, 1230); expect(html).toBe(expected); } ); }); describe('when rendering cells with different alignment options', () => { const cases = [ //align, preserve fmt, color mode, expected ['', false, null, '<td>42</td>'], ['invalid_option', false, null, '<td>42</td>'], ['alert("no xss");', false, null, '<td>42</td>'], ['auto', false, null, '<td>42</td>'], ['justify', false, null, '<td>42</td>'], ['auto', true, null, '<td class="table-panel-cell-pre">42</td>'], ['left', false, null, '<td style="text-align:left">42</td>'], ['left', true, null, '<td class="table-panel-cell-pre" style="text-align:left">42</td>'], ['center', false, null, '<td style="text-align:center">42</td>'], [ 'center', true, 'cell', '<td class="table-panel-color-cell table-panel-cell-pre" style="background-color:rgba(50, 172, 45, 0.97);text-align:center">42</td>', ], [ 'right', false, 'cell', '<td class="table-panel-color-cell" style="background-color:rgba(50, 172, 45, 0.97);text-align:right">42</td>', ], [ 'right', true, 'cell', '<td class="table-panel-color-cell table-panel-cell-pre" style="background-color:rgba(50, 172, 45, 0.97);text-align:right">42</td>', ], ]; it.each(cases)( 'align option:"%s", preformatted:%s columns should be formatted with correct style', (align: string, preserveFormat: boolean, colorMode, expected: string) => { const table = new TableModel(); table.columns = [{ text: 'Time' }, { text: align }]; table.rows = [[0, 42]]; const panel = { pageSize: 10, styles: [ { pattern: 'Time', type: 'date', format: 'LLL', alias: 'Timestamp', }, { pattern: `/${align}/`, align: align, type: 'number', unit: 'none', preserveFormat: preserveFormat, colorMode: colorMode, thresholds: [1, 2], colors: ['rgba(245, 54, 54, 0.9)', 'rgba(237, 129, 40, 0.89)', 'rgba(50, 172, 45, 0.97)'], }, ], }; //@ts-ignore const renderer = new TableRenderer(panel, table, 'utc', sanitize, templateSrv); const html = renderer.renderCell(1, 0, 42); expect(html).toBe(expected); } ); }); function normalize(str: string) { return str.replace(/\s+/gm, ' ').trim(); }
public/app/plugins/panel/table/specs/renderer.test.ts
1
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.9982643723487854, 0.03710954636335373, 0.00016229940229095519, 0.00025275343796238303, 0.18497444689273834 ]
{ "id": 2, "code_window": [ " it('link should render as', () => {\n", " const html = renderer.renderCell(7, 0, 'host1');\n", " const expectedHtml = `\n", " <td class=\"table-panel-cell-link\">\n", " <a href=\"/dashboard?param=host1&param_1=1230&param_2=40\"\n", " target=\"_blank\" data-link-tooltip data-original-title=\"host1 1230 my.host.com\" data-placement=\"right\">\n", " host1\n", " </a>\n", " </td>\n", " `;\n", " expect(normalize(html)).toBe(normalize(expectedHtml));\n", " });\n", "\n", " it('Array column should not use number as formatter', () => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td class=\"table-panel-cell-link\"><a href=\"/dashboard?param=host1&param_1=1230&param_2=40\"\n", " target=\"_blank\" data-link-tooltip data-original-title=\"host1 1230 my.host.com\"\n", "\t\t\tdata-placement=\"right\">host1</a></td>\n" ], "file_path": "public/app/plugins/panel/table/specs/renderer.test.ts", "type": "replace", "edit_start_line_idx": 319 }
import _ from 'lodash'; export function getMessageFromError(err: any): string | null { if (err && !_.isString(err)) { if (err.message) { return err.message; } else if (err.data && err.data.message) { return err.data.message; } else if (err.statusText) { return err.statusText; } else { return JSON.stringify(err); } } return err; }
public/app/core/utils/errors.ts
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.00016817869618535042, 0.00016685746959410608, 0.00016553624300286174, 0.00016685746959410608, 0.00000132122659124434 ]
{ "id": 2, "code_window": [ " it('link should render as', () => {\n", " const html = renderer.renderCell(7, 0, 'host1');\n", " const expectedHtml = `\n", " <td class=\"table-panel-cell-link\">\n", " <a href=\"/dashboard?param=host1&param_1=1230&param_2=40\"\n", " target=\"_blank\" data-link-tooltip data-original-title=\"host1 1230 my.host.com\" data-placement=\"right\">\n", " host1\n", " </a>\n", " </td>\n", " `;\n", " expect(normalize(html)).toBe(normalize(expectedHtml));\n", " });\n", "\n", " it('Array column should not use number as formatter', () => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td class=\"table-panel-cell-link\"><a href=\"/dashboard?param=host1&param_1=1230&param_2=40\"\n", " target=\"_blank\" data-link-tooltip data-original-title=\"host1 1230 my.host.com\"\n", "\t\t\tdata-placement=\"right\">host1</a></td>\n" ], "file_path": "public/app/plugins/panel/table/specs/renderer.test.ts", "type": "replace", "edit_start_line_idx": 319 }
import React, { PureComponent } from 'react'; import { rangeUtil, RawTimeRange, LogLevel, TimeZone, AbsoluteTimeRange, LogsMetaKind, LogsDedupStrategy, LogRowModel, LogsDedupDescription, LogsMetaItem, GraphSeriesXY, LinkModel, Field, } from '@grafana/data'; import { Switch, LogLabels, ToggleButtonGroup, ToggleButton, LogRows } from '@grafana/ui'; import store from 'app/core/store'; import { ExploreGraphPanel } from './ExploreGraphPanel'; const SETTINGS_KEYS = { showLabels: 'grafana.explore.logs.showLabels', showTime: 'grafana.explore.logs.showTime', wrapLogMessage: 'grafana.explore.logs.wrapLogMessage', }; function renderMetaItem(value: any, kind: LogsMetaKind) { if (kind === LogsMetaKind.LabelsMap) { return ( <span className="logs-meta-item__labels"> <LogLabels labels={value} /> </span> ); } return value; } interface Props { logRows?: LogRowModel[]; logsMeta?: LogsMetaItem[]; logsSeries?: GraphSeriesXY[]; dedupedRows?: LogRowModel[]; width: number; highlighterExpressions?: string[]; loading: boolean; absoluteRange: AbsoluteTimeRange; timeZone: TimeZone; scanning?: boolean; scanRange?: RawTimeRange; dedupStrategy: LogsDedupStrategy; onChangeTime: (range: AbsoluteTimeRange) => void; onClickFilterLabel?: (key: string, value: string) => void; onClickFilterOutLabel?: (key: string, value: string) => void; onStartScanning?: () => void; onStopScanning?: () => void; onDedupStrategyChange: (dedupStrategy: LogsDedupStrategy) => void; onToggleLogLevel: (hiddenLogLevels: LogLevel[]) => void; getRowContext?: (row: LogRowModel, options?: any) => Promise<any>; getFieldLinks: (field: Field, rowIndex: number) => Array<LinkModel<Field>>; } interface State { showLabels: boolean; showTime: boolean; wrapLogMessage: boolean; } export class Logs extends PureComponent<Props, State> { state = { showLabels: store.getBool(SETTINGS_KEYS.showLabels, false), showTime: store.getBool(SETTINGS_KEYS.showTime, true), wrapLogMessage: store.getBool(SETTINGS_KEYS.wrapLogMessage, true), }; onChangeDedup = (dedup: LogsDedupStrategy) => { const { onDedupStrategyChange } = this.props; if (this.props.dedupStrategy === dedup) { return onDedupStrategyChange(LogsDedupStrategy.none); } return onDedupStrategyChange(dedup); }; onChangeLabels = (event?: React.SyntheticEvent) => { const target = event && (event.target as HTMLInputElement); if (target) { const showLabels = target.checked; this.setState({ showLabels, }); store.set(SETTINGS_KEYS.showLabels, showLabels); } }; onChangeTime = (event?: React.SyntheticEvent) => { const target = event && (event.target as HTMLInputElement); if (target) { const showTime = target.checked; this.setState({ showTime, }); store.set(SETTINGS_KEYS.showTime, showTime); } }; onChangewrapLogMessage = (event?: React.SyntheticEvent) => { const target = event && (event.target as HTMLInputElement); if (target) { const wrapLogMessage = target.checked; this.setState({ wrapLogMessage, }); store.set(SETTINGS_KEYS.wrapLogMessage, wrapLogMessage); } }; onToggleLogLevel = (hiddenRawLevels: string[]) => { const hiddenLogLevels: LogLevel[] = hiddenRawLevels.map(level => LogLevel[level as LogLevel]); this.props.onToggleLogLevel(hiddenLogLevels); }; onClickScan = (event: React.SyntheticEvent) => { event.preventDefault(); if (this.props.onStartScanning) { this.props.onStartScanning(); } }; onClickStopScan = (event: React.SyntheticEvent) => { event.preventDefault(); if (this.props.onStopScanning) { this.props.onStopScanning(); } }; render() { const { logRows, logsMeta, logsSeries, highlighterExpressions, loading = false, onClickFilterLabel, onClickFilterOutLabel, timeZone, scanning, scanRange, width, dedupedRows, absoluteRange, onChangeTime, getFieldLinks, } = this.props; if (!logRows) { return null; } const { showLabels, showTime, wrapLogMessage } = this.state; const { dedupStrategy } = this.props; const hasData = logRows && logRows.length > 0; const dedupCount = dedupedRows ? dedupedRows.reduce((sum, row) => (row.duplicates ? sum + row.duplicates : sum), 0) : 0; const meta = logsMeta ? [...logsMeta] : []; if (dedupStrategy !== LogsDedupStrategy.none) { meta.push({ label: 'Dedup count', value: dedupCount, kind: LogsMetaKind.Number, }); } const scanText = scanRange ? `Scanning ${rangeUtil.describeTimeRange(scanRange)}` : 'Scanning...'; const series = logsSeries ? logsSeries : []; return ( <div className="logs-panel"> <div className="logs-panel-graph"> <ExploreGraphPanel series={series} width={width} onHiddenSeriesChanged={this.onToggleLogLevel} loading={loading} absoluteRange={absoluteRange} isStacked={true} showPanel={false} showingGraph={true} showingTable={true} timeZone={timeZone} showBars={true} showLines={false} onUpdateTimeRange={onChangeTime} /> </div> <div className="logs-panel-options"> <div className="logs-panel-controls"> <Switch label="Time" checked={showTime} onChange={this.onChangeTime} transparent /> <Switch label="Unique labels" checked={showLabels} onChange={this.onChangeLabels} transparent /> <Switch label="Wrap lines" checked={wrapLogMessage} onChange={this.onChangewrapLogMessage} transparent /> <ToggleButtonGroup label="Dedup" transparent={true}> {Object.keys(LogsDedupStrategy).map((dedupType: string, i) => ( <ToggleButton key={i} value={dedupType} onChange={this.onChangeDedup} selected={dedupStrategy === dedupType} // @ts-ignore tooltip={LogsDedupDescription[dedupType]} > {dedupType} </ToggleButton> ))} </ToggleButtonGroup> </div> </div> {hasData && meta && ( <div className="logs-panel-meta"> {meta.map(item => ( <div className="logs-panel-meta__item" key={item.label}> <span className="logs-panel-meta__label">{item.label}:</span> <span className="logs-panel-meta__value">{renderMetaItem(item.value, item.kind)}</span> </div> ))} </div> )} <LogRows logRows={logRows} deduplicatedRows={dedupedRows} dedupStrategy={dedupStrategy} getRowContext={this.props.getRowContext} highlighterExpressions={highlighterExpressions} rowLimit={logRows ? logRows.length : undefined} onClickFilterLabel={onClickFilterLabel} onClickFilterOutLabel={onClickFilterOutLabel} showLabels={showLabels} showTime={showTime} wrapLogMessage={wrapLogMessage} timeZone={timeZone} getFieldLinks={getFieldLinks} /> {!loading && !hasData && !scanning && ( <div className="logs-panel-nodata"> No logs found. <a className="link" onClick={this.onClickScan}> Scan for older logs </a> </div> )} {scanning && ( <div className="logs-panel-nodata"> <span>{scanText}</span> <a className="link" onClick={this.onClickStopScan}> Stop scan </a> </div> )} </div> ); } }
public/app/features/explore/Logs.tsx
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.0004717579286079854, 0.0001824354549171403, 0.000161141186254099, 0.0001703166199149564, 0.00005723583308281377 ]
{ "id": 2, "code_window": [ " it('link should render as', () => {\n", " const html = renderer.renderCell(7, 0, 'host1');\n", " const expectedHtml = `\n", " <td class=\"table-panel-cell-link\">\n", " <a href=\"/dashboard?param=host1&param_1=1230&param_2=40\"\n", " target=\"_blank\" data-link-tooltip data-original-title=\"host1 1230 my.host.com\" data-placement=\"right\">\n", " host1\n", " </a>\n", " </td>\n", " `;\n", " expect(normalize(html)).toBe(normalize(expectedHtml));\n", " });\n", "\n", " it('Array column should not use number as formatter', () => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td class=\"table-panel-cell-link\"><a href=\"/dashboard?param=host1&param_1=1230&param_2=40\"\n", " target=\"_blank\" data-link-tooltip data-original-title=\"host1 1230 my.host.com\"\n", "\t\t\tdata-placement=\"right\">host1</a></td>\n" ], "file_path": "public/app/plugins/panel/table/specs/renderer.test.ts", "type": "replace", "edit_start_line_idx": 319 }
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'; const grafanaURL = 'https://api.github.com/repos/grafana/grafana'; const enterpriseURL = 'https://api.github.com/repos/grafana/grafana-enterprise'; // Encapsulates the creation of a client for the Github API // // Two key things: // 1. You can specify whenever you want the credentials to be required or not when imported. // 2. If the the credentials are available as part of the environment, even if // they're not required - the library will use them. This allows us to overcome // any API rate limiting imposed without authentication. interface GithubClientProps { required?: boolean; enterprise?: boolean; } class GithubClient { client: AxiosInstance; constructor({ required = false, enterprise = false }: GithubClientProps = {}) { const username = process.env.GITHUB_USERNAME; const token = process.env.GITHUB_ACCESS_TOKEN; const clientConfig: AxiosRequestConfig = { baseURL: enterprise ? enterpriseURL : grafanaURL, timeout: 10000, }; if (required && !username && !token) { throw new Error('operation needs a GITHUB_USERNAME and GITHUB_ACCESS_TOKEN environment variables'); } if (username && token) { clientConfig.auth = { username: username, password: token }; } this.client = this.createClient(clientConfig); } private createClient(clientConfig: AxiosRequestConfig) { return axios.create(clientConfig); } } export default GithubClient;
packages/grafana-toolkit/src/cli/utils/githubClient.ts
0
https://github.com/grafana/grafana/commit/427629b4d5684b9a3bba37af1784169f887ca3d1
[ 0.00017482116527389735, 0.00017060412210412323, 0.00016722886357456446, 0.00017090031178668141, 0.0000027544367640075507 ]
{ "id": 0, "code_window": [ " \"\"\"\n", "\n", " #\n", " # Download Bazel toolchain dependencies as needed by build actions\n", " #\n", " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " # TODO(gmagolan): updated to next tagged rules_typescript release\n" ], "file_path": "packages/bazel/package.bzl", "type": "add", "edit_start_line_idx": 23 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.9874104857444763, 0.02781057357788086, 0.00016508245607838035, 0.0001728996867313981, 0.16220349073410034 ]
{ "id": 0, "code_window": [ " \"\"\"\n", "\n", " #\n", " # Download Bazel toolchain dependencies as needed by build actions\n", " #\n", " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " # TODO(gmagolan): updated to next tagged rules_typescript release\n" ], "file_path": "packages/bazel/package.bzl", "type": "add", "edit_start_line_idx": 23 }
<!DOCTYPE html> <html lang="en"> <head> <title>User Input</title> <base href="/"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="assets/user-input-styles.css"> </head> <body> <app-root></app-root> </body> </html>
aio/content/examples/user-input/src/index.html
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017332567949779332, 0.0001708853233139962, 0.00016844495257828385, 0.0001708853233139962, 0.0000024403634597547352 ]
{ "id": 0, "code_window": [ " \"\"\"\n", "\n", " #\n", " # Download Bazel toolchain dependencies as needed by build actions\n", " #\n", " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " # TODO(gmagolan): updated to next tagged rules_typescript release\n" ], "file_path": "packages/bazel/package.bzl", "type": "add", "edit_start_line_idx": 23 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {InjectionToken, Injector, NgModule, destroyPlatform} from '@angular/core'; import {async} from '@angular/core/testing'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {UpgradeModule, downgradeInjectable, getAngularJSGlobal, setAngularJSGlobal} from '@angular/upgrade/static'; import * as angular from '@angular/upgrade/static/src/common/angular1'; import {$INJECTOR, INJECTOR_KEY} from '@angular/upgrade/static/src/common/constants'; import {bootstrap, html, withEachNg1Version} from '../test_helpers'; withEachNg1Version(() => { describe('injection', () => { beforeEach(() => destroyPlatform()); afterEach(() => destroyPlatform()); it('should downgrade ng2 service to ng1', async(() => { // Tokens used in ng2 to identify services const Ng2Service = new InjectionToken('ng2-service'); // Sample ng1 NgModule for tests @NgModule({ imports: [BrowserModule, UpgradeModule], providers: [ {provide: Ng2Service, useValue: 'ng2 service value'}, ] }) class Ng2Module { ngDoBootstrap() {} } // create the ng1 module that will import an ng2 service const ng1Module = angular.module('ng1Module', []).factory('ng2Service', downgradeInjectable(Ng2Service)); bootstrap(platformBrowserDynamic(), Ng2Module, html('<div>'), ng1Module) .then((upgrade) => { const ng1Injector = upgrade.$injector; expect(ng1Injector.get('ng2Service')).toBe('ng2 service value'); }); })); it('should upgrade ng1 service to ng2', async(() => { // Tokens used in ng2 to identify services const Ng1Service = new InjectionToken('ng1-service'); // Sample ng1 NgModule for tests @NgModule({ imports: [BrowserModule, UpgradeModule], providers: [ // the following line is the "upgrade" of an AngularJS service { provide: Ng1Service, useFactory: (i: angular.IInjectorService) => i.get('ng1Service'), deps: ['$injector'] } ] }) class Ng2Module { ngDoBootstrap() {} } // create the ng1 module that will import an ng2 service const ng1Module = angular.module('ng1Module', []).value('ng1Service', 'ng1 service value'); bootstrap(platformBrowserDynamic(), Ng2Module, html('<div>'), ng1Module) .then((upgrade) => { const ng2Injector = upgrade.injector; expect(ng2Injector.get(Ng1Service)).toBe('ng1 service value'); }); })); it('should initialize the upgraded injector before application run blocks are executed', async(() => { let runBlockTriggered = false; const ng1Module = angular.module('ng1Module', []).run([ INJECTOR_KEY, function(injector: Injector) { runBlockTriggered = true; expect(injector.get($INJECTOR)).toBeDefined(); } ]); @NgModule({imports: [BrowserModule, UpgradeModule]}) class Ng2Module { ngDoBootstrap() {} } bootstrap(platformBrowserDynamic(), Ng2Module, html('<div>'), ng1Module).then(() => { expect(runBlockTriggered).toBeTruthy(); }); })); it('should allow resetting angular at runtime', async(() => { let wrappedBootstrapCalled = false; const n: any = getAngularJSGlobal(); setAngularJSGlobal({ bootstrap: (...args: any[]) => { wrappedBootstrapCalled = true; n.bootstrap(...args); }, module: n.module, element: n.element, version: n.version, resumeBootstrap: n.resumeBootstrap, getTestability: n.getTestability }); @NgModule({imports: [BrowserModule, UpgradeModule]}) class Ng2Module { ngDoBootstrap() {} } const ng1Module = angular.module('ng1Module', []); bootstrap(platformBrowserDynamic(), Ng2Module, html('<div>'), ng1Module) .then(upgrade => expect(wrappedBootstrapCalled).toBe(true)) .then(() => setAngularJSGlobal(n)); // Reset the AngularJS global. })); }); });
packages/upgrade/test/static/integration/injection_spec.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017603572632651776, 0.00017077925440389663, 0.0001661231799516827, 0.00017057592049241066, 0.0000033325447930110386 ]
{ "id": 0, "code_window": [ " \"\"\"\n", "\n", " #\n", " # Download Bazel toolchain dependencies as needed by build actions\n", " #\n", " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_typescript\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " # TODO(gmagolan): updated to next tagged rules_typescript release\n" ], "file_path": "packages/bazel/package.bzl", "type": "add", "edit_start_line_idx": 23 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license """Run Angular's AOT template compiler """ load( ":external.bzl", "COMMON_ATTRIBUTES", "COMMON_OUTPUTS", "DEFAULT_NG_COMPILER", "DEFAULT_NG_XI18N", "DEPS_ASPECTS", "NodeModuleInfo", "collect_node_modules_aspect", "compile_ts", "ts_providers_dict_to_struct", "tsc_wrapped_tsconfig", ) def compile_strategy(ctx): """Detect which strategy should be used to implement ng_module. Depending on the value of the 'compile' define flag or the '_global_mode' attribute, ng_module can be implemented in various ways. This function reads the configuration passed by the user and determines which mode is active. Args: ctx: skylark rule execution context Returns: one of 'legacy', 'aot', 'jit', or 'global' depending on the configuration in ctx """ strategy = "legacy" if "compile" in ctx.var: strategy = ctx.var["compile"] if strategy not in ["legacy", "aot", "jit"]: fail("Unknown --define=compile value '%s'" % strategy) if strategy == "legacy" and hasattr(ctx.attr, "_global_mode") and ctx.attr._global_mode: strategy = "global" return strategy def _compiler_name(ctx): """Selects a user-visible name depending on the current compilation strategy. Args: ctx: skylark rule execution context Returns: the name of the current compiler to be displayed in build output """ strategy = compile_strategy(ctx) if strategy == "legacy": return "ngc" elif strategy == "global": return "ngc.ivy" elif strategy == "aot": return "ngtsc" elif strategy == "jit": return "tsc" else: fail("unreachable") def _enable_ivy_value(ctx): """Determines the value of the enableIvy option in the generated tsconfig. Args: ctx: skylark rule execution context Returns: the value of enableIvy that needs to be set in angularCompilerOptions in the generated tsconfig """ strategy = compile_strategy(ctx) if strategy == "legacy": return False elif strategy == "global": return True elif strategy == "aot": return "ngtsc" elif strategy == "jit": return "tsc" else: fail("unreachable") def _include_ng_files(ctx): """Determines whether Angular outputs will be produced by the current compilation strategy. Args: ctx: skylark rule execution context Returns: true iff the current compilation strategy will produce View Engine compilation outputs (such as factory files), false otherwise """ strategy = compile_strategy(ctx) return strategy == "legacy" or strategy == "global" def _basename_of(ctx, file): ext_len = len(".ts") if file.short_path.endswith(".ng.html"): ext_len = len(".ng.html") elif file.short_path.endswith(".html"): ext_len = len(".html") return file.short_path[len(ctx.label.package) + 1:-ext_len] # Return true if run with bazel (the open-sourced version of blaze), false if # run with blaze. def _is_bazel(): return not hasattr(native, "genmpm") def _flat_module_out_file(ctx): """Provide a default for the flat_module_out_file attribute. We cannot use the default="" parameter of ctx.attr because the value is calculated from other attributes (name) Args: ctx: skylark rule execution context Returns: a basename used for the flat module out (no extension) """ if hasattr(ctx.attr, "flat_module_out_file") and ctx.attr.flat_module_out_file: return ctx.attr.flat_module_out_file return "%s_public_index" % ctx.label.name def _should_produce_flat_module_outs(ctx): """Should we produce flat module outputs. We only produce flat module outs when we expect the ng_module is meant to be published, based on the presence of the module_name attribute. Args: ctx: skylark rule execution context Returns: true iff we should run the bundle_index_host to produce flat module metadata and bundle index """ return _is_bazel() and ctx.attr.module_name # Calculate the expected output of the template compiler for every source in # in the library. Most of these will be produced as empty files but it is # unknown, without parsing, which will be empty. def _expected_outs(ctx): include_ng_files = _include_ng_files(ctx) devmode_js_files = [] closure_js_files = [] declaration_files = [] summary_files = [] metadata_files = [] factory_basename_set = depset([_basename_of(ctx, src) for src in ctx.files.factories]) for src in ctx.files.srcs + ctx.files.assets: package_prefix = ctx.label.package + "/" if ctx.label.package else "" # Strip external repository name from path if src is from external repository # If src is from external repository, it's short_path will be ../<external_repo_name>/... short_path = src.short_path if src.short_path[0:2] != ".." else "/".join(src.short_path.split("/")[2:]) if short_path.endswith(".ts") and not short_path.endswith(".d.ts"): basename = short_path[len(package_prefix):-len(".ts")] if include_ng_files and (len(factory_basename_set) == 0 or basename in factory_basename_set): devmode_js = [ ".ngfactory.js", ".ngsummary.js", ".js", ] summaries = [".ngsummary.json"] metadata = [".metadata.json"] else: devmode_js = [".js"] if not _is_bazel(): devmode_js += [".ngfactory.js"] summaries = [] metadata = [] elif include_ng_files and short_path.endswith(".css"): basename = short_path[len(package_prefix):-len(".css")] devmode_js = [ ".css.shim.ngstyle.js", ".css.ngstyle.js", ] summaries = [] metadata = [] else: continue filter_summaries = ctx.attr.filter_summaries closure_js = [f.replace(".js", ".closure.js") for f in devmode_js if not filter_summaries or not f.endswith(".ngsummary.js")] declarations = [f.replace(".js", ".d.ts") for f in devmode_js] devmode_js_files += [ctx.actions.declare_file(basename + ext) for ext in devmode_js] closure_js_files += [ctx.actions.declare_file(basename + ext) for ext in closure_js] declaration_files += [ctx.actions.declare_file(basename + ext) for ext in declarations] summary_files += [ctx.actions.declare_file(basename + ext) for ext in summaries] if not _is_bazel(): metadata_files += [ctx.actions.declare_file(basename + ext) for ext in metadata] # We do this just when producing a flat module index for a publishable ng_module if include_ng_files and _should_produce_flat_module_outs(ctx): flat_module_out = _flat_module_out_file(ctx) devmode_js_files.append(ctx.actions.declare_file("%s.js" % flat_module_out)) closure_js_files.append(ctx.actions.declare_file("%s.closure.js" % flat_module_out)) bundle_index_typings = ctx.actions.declare_file("%s.d.ts" % flat_module_out) declaration_files.append(bundle_index_typings) metadata_files.append(ctx.actions.declare_file("%s.metadata.json" % flat_module_out)) else: bundle_index_typings = None # TODO(alxhub): i18n is only produced by the legacy compiler currently. This should be re-enabled # when ngtsc can extract messages if include_ng_files: i18n_messages_files = [ctx.new_file(ctx.genfiles_dir, ctx.label.name + "_ngc_messages.xmb")] else: i18n_messages_files = [] return struct( closure_js = closure_js_files, devmode_js = devmode_js_files, declarations = declaration_files, summaries = summary_files, metadata = metadata_files, bundle_index_typings = bundle_index_typings, i18n_messages = i18n_messages_files, ) def _ngc_tsconfig(ctx, files, srcs, **kwargs): outs = _expected_outs(ctx) include_ng_files = _include_ng_files(ctx) if "devmode_manifest" in kwargs: expected_outs = outs.devmode_js + outs.declarations + outs.summaries + outs.metadata else: expected_outs = outs.closure_js angular_compiler_options = { "enableResourceInlining": ctx.attr.inline_resources, "generateCodeForLibraries": False, "allowEmptyCodegenFiles": True, # Summaries are only enabled if Angular outputs are to be produced. "enableSummariesForJit": include_ng_files, "enableIvy": _enable_ivy_value(ctx), "fullTemplateTypeCheck": ctx.attr.type_check, # FIXME: wrong place to de-dupe "expectedOut": depset([o.path for o in expected_outs]).to_list(), } if _should_produce_flat_module_outs(ctx): angular_compiler_options["flatModuleId"] = ctx.attr.module_name angular_compiler_options["flatModuleOutFile"] = _flat_module_out_file(ctx) angular_compiler_options["flatModulePrivateSymbolPrefix"] = "_".join( [ctx.workspace_name] + ctx.label.package.split("/") + [ctx.label.name, ""], ) return dict(tsc_wrapped_tsconfig(ctx, files, srcs, **kwargs), **{ "angularCompilerOptions": angular_compiler_options, }) def _collect_summaries_aspect_impl(target, ctx): results = depset(target.angular.summaries if hasattr(target, "angular") else []) # If we are visiting empty-srcs ts_library, this is a re-export srcs = ctx.rule.attr.srcs if hasattr(ctx.rule.attr, "srcs") else [] # "re-export" rules should expose all the files of their deps if not srcs and hasattr(ctx.rule.attr, "deps"): for dep in ctx.rule.attr.deps: if (hasattr(dep, "angular")): results = depset(dep.angular.summaries, transitive = [results]) return struct(collect_summaries_aspect_result = results) _collect_summaries_aspect = aspect( implementation = _collect_summaries_aspect_impl, attr_aspects = ["deps"], ) # Extra options passed to Node when running ngc. _EXTRA_NODE_OPTIONS_FLAGS = [ # Expose the v8 garbage collection API to JS. "--node_options=--expose-gc", ] def ngc_compile_action( ctx, label, inputs, outputs, messages_out, tsconfig_file, node_opts, locale = None, i18n_args = []): """Helper function to create the ngc action. This is exposed for google3 to wire up i18n replay rules, and is not intended as part of the public API. Args: ctx: skylark context label: the label of the ng_module being compiled inputs: passed to the ngc action's inputs outputs: passed to the ngc action's outputs messages_out: produced xmb files tsconfig_file: tsconfig file with settings used for the compilation node_opts: list of strings, extra nodejs options. locale: i18n locale, or None i18n_args: additional command-line arguments to ngc Returns: the parameters of the compilation which will be used to replay the ngc action for i18N. """ include_ng_files = _include_ng_files(ctx) mnemonic = "AngularTemplateCompile" progress_message = "Compiling Angular templates (%s) %s" % (_compiler_name(ctx), label) if locale: mnemonic = "AngularI18NMerging" supports_workers = "0" progress_message = ("Recompiling Angular templates (ngc) %s for locale %s" % (label, locale)) else: supports_workers = str(int(ctx.attr._supports_workers)) arguments = (list(_EXTRA_NODE_OPTIONS_FLAGS) + ["--node_options=%s" % opt for opt in node_opts]) # One at-sign makes this a params-file, enabling the worker strategy. # Two at-signs escapes the argument so it's passed through to ngc # rather than the contents getting expanded. if supports_workers == "1": arguments += ["@@" + tsconfig_file.path] else: arguments += ["-p", tsconfig_file.path] arguments += i18n_args ctx.actions.run( progress_message = progress_message, mnemonic = mnemonic, inputs = inputs, outputs = outputs, arguments = arguments, executable = ctx.executable.compiler, execution_requirements = { "supports-workers": supports_workers, }, ) if include_ng_files and messages_out != None: ctx.actions.run( inputs = list(inputs), outputs = messages_out, executable = ctx.executable.ng_xi18n, arguments = (_EXTRA_NODE_OPTIONS_FLAGS + [tsconfig_file.path] + # The base path is bin_dir because of the way the ngc # compiler host is configured. So we need to explicitly # point to genfiles/ to redirect the output. ["../genfiles/" + messages_out[0].short_path]), progress_message = "Extracting Angular 2 messages (ng_xi18n)", mnemonic = "Angular2MessageExtractor", ) if not locale and not ctx.attr.no_i18n: return struct( label = label, tsconfig = tsconfig_file, inputs = inputs, outputs = outputs, compiler = ctx.executable.compiler, ) return None def _filter_ts_inputs(all_inputs): # The compiler only needs to see TypeScript sources from the npm dependencies, # but may need to look at package.json and ngsummary.json files as well. return [ f for f in all_inputs if f.path.endswith(".js") or f.path.endswith(".ts") or f.path.endswith(".json") ] def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file, node_opts): # Give the Angular compiler all the user-listed assets file_inputs = list(ctx.files.assets) if hasattr(ctx.attr, "node_modules"): file_inputs.extend(_filter_ts_inputs(ctx.files.node_modules)) # If the user supplies a tsconfig.json file, the Angular compiler needs to read it if hasattr(ctx.attr, "tsconfig") and ctx.file.tsconfig: file_inputs.append(ctx.file.tsconfig) # Also include files from npm fine grained deps as action_inputs. # These deps are identified by the NodeModuleInfo provider. for d in ctx.attr.deps: if NodeModuleInfo in d: file_inputs.extend(_filter_ts_inputs(d.files)) # Collect the inputs and summary files from our deps action_inputs = depset( file_inputs, transitive = [inputs] + [ dep.collect_summaries_aspect_result for dep in ctx.attr.deps if hasattr(dep, "collect_summaries_aspect_result") ], ) return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file, node_opts) def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts): outs = _expected_outs(ctx) return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file, node_opts) def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts): outs = _expected_outs(ctx) compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries + outs.metadata _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts) def _ts_expected_outs(ctx, label, srcs_files = []): # rules_typescript expects a function with two or more arguments, but our # implementation doesn't use the label(and **kwargs). _ignored = [label, srcs_files] return _expected_outs(ctx) def ng_module_impl(ctx, ts_compile_actions): """Implementation function for the ng_module rule. This is exposed so that google3 can have its own entry point that re-uses this and is not meant as a public API. Args: ctx: the skylark rule context ts_compile_actions: generates all the actions to run an ngc compilation Returns: the result of the ng_module rule as a dict, suitable for conversion by ts_providers_dict_to_struct """ include_ng_files = _include_ng_files(ctx) providers = ts_compile_actions( ctx, is_library = True, # Filter out the node_modules from deps passed to TypeScript compiler # since they don't have the required providers. # They were added to the action inputs for tsc_wrapped already. # strict_deps checking currently skips node_modules. # TODO(alexeagle): turn on strict deps checking when we have a real # provider for JS/DTS inputs to ts_library. deps = [d for d in ctx.attr.deps if not NodeModuleInfo in d], compile_action = _prodmode_compile_action, devmode_compile_action = _devmode_compile_action, tsc_wrapped_tsconfig = _ngc_tsconfig, outputs = _ts_expected_outs, ) outs = _expected_outs(ctx) if include_ng_files: providers["angular"] = { "summaries": outs.summaries, "metadata": outs.metadata, } providers["ngc_messages"] = outs.i18n_messages if include_ng_files and _should_produce_flat_module_outs(ctx): if len(outs.metadata) > 1: fail("expecting exactly one metadata output for " + str(ctx.label)) providers["angular"]["flat_module_metadata"] = struct( module_name = ctx.attr.module_name, metadata_file = outs.metadata[0], typings_file = outs.bundle_index_typings, flat_module_out_file = _flat_module_out_file(ctx), ) return providers def _ng_module_impl(ctx): return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts)) local_deps_aspects = [collect_node_modules_aspect, _collect_summaries_aspect] # Workaround skydoc bug which assumes DEPS_ASPECTS is a str type [local_deps_aspects.append(a) for a in DEPS_ASPECTS] NG_MODULE_ATTRIBUTES = { "srcs": attr.label_list(allow_files = [".ts"]), # Note: DEPS_ASPECTS is already a list, we add the cast to workaround # https://github.com/bazelbuild/skydoc/issues/21 "deps": attr.label_list( doc = "Targets that are imported by this target", aspects = local_deps_aspects, ), "assets": attr.label_list( doc = ".html and .css files needed by the Angular compiler", allow_files = [ ".css", # TODO(alexeagle): change this to ".ng.html" when usages updated ".html", ], ), "factories": attr.label_list( allow_files = [".ts", ".html"], mandatory = False, ), "filter_summaries": attr.bool(default = False), "type_check": attr.bool(default = True), "inline_resources": attr.bool(default = True), "no_i18n": attr.bool(default = False), "compiler": attr.label( doc = """Sets a different ngc compiler binary to use for this library. The default ngc compiler depends on the `@npm//@angular/bazel` target which is setup for projects that use bazel managed npm deps that fetch the @angular/bazel npm package. It is recommended that you use the workspace name `@npm` for bazel managed deps so the default compiler works out of the box. Otherwise, you'll have to override the compiler attribute manually. """, default = Label(DEFAULT_NG_COMPILER), executable = True, cfg = "host", ), "ng_xi18n": attr.label( default = Label(DEFAULT_NG_XI18N), executable = True, cfg = "host", ), "_supports_workers": attr.bool(default = True), } NG_MODULE_RULE_ATTRS = dict(dict(COMMON_ATTRIBUTES, **NG_MODULE_ATTRIBUTES), **{ "tsconfig": attr.label(allow_files = True, single_file = True), "node_modules": attr.label( doc = """The npm packages which should be available during the compile. The default value of `@npm//typescript:typescript__typings` is for projects that use bazel managed npm deps. It is recommended that you use the workspace name `@npm` for bazel managed deps so the default value works out of the box. Otherwise, you'll have to override the node_modules attribute manually. This default is in place since code compiled by ng_module will always depend on at least the typescript default libs which are provided by `@npm//typescript:typescript__typings`. This attribute is DEPRECATED. As of version 0.18.0 the recommended approach to npm dependencies is to use fine grained npm dependencies which are setup with the `yarn_install` or `npm_install` rules. For example, in targets that used a `//:node_modules` filegroup, ``` ng_module( name = "my_lib", ... node_modules = "//:node_modules", ) ``` which specifies all files within the `//:node_modules` filegroup to be inputs to the `my_lib`. Using fine grained npm dependencies, `my_lib` is defined with only the npm dependencies that are needed: ``` ng_module( name = "my_lib", ... deps = [ "@npm//@types/foo", "@npm//@types/bar", "@npm//foo", "@npm//bar", ... ], ) ``` In this case, only the listed npm packages and their transitive deps are includes as inputs to the `my_lib` target which reduces the time required to setup the runfiles for this target (see https://github.com/bazelbuild/bazel/issues/5153). The default typescript libs are also available via the node_modules default in this case. The @npm external repository and the fine grained npm package targets are setup using the `yarn_install` or `npm_install` rule in your WORKSPACE file: yarn_install( name = "npm", package_json = "//:package.json", yarn_lock = "//:yarn.lock", ) """, default = Label("@npm//typescript:typescript__typings"), ), "entry_point": attr.string(), # Default is %{name}_public_index # The suffix points to the generated "bundle index" files that users import from # The default is intended to avoid collisions with the users input files. # Later packaging rules will point to these generated files as the entry point # into the package. # See the flatModuleOutFile documentation in # https://github.com/angular/angular/blob/master/packages/compiler-cli/src/transformers/api.ts "flat_module_out_file": attr.string(), }) ng_module = rule( implementation = _ng_module_impl, attrs = NG_MODULE_RULE_ATTRS, outputs = COMMON_OUTPUTS, ) """ Run the Angular AOT template compiler. This rule extends the [ts_library] rule. [ts_library]: http://tsetse.info/api/build_defs.html#ts_library """ # TODO(alxhub): this rule causes legacy ngc to produce Ivy outputs from global analysis information. # It exists to facilitate testing of the Ivy runtime until ngtsc is mature enough to be used # instead, and should be removed once ngtsc is capable of fulfilling the same requirements. internal_global_ng_module = rule( implementation = _ng_module_impl, attrs = dict(NG_MODULE_RULE_ATTRS, **{ "_global_mode": attr.bool( default = True, ), }), outputs = COMMON_OUTPUTS, )
packages/bazel/src/ng_module.bzl
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.018948005512356758, 0.0005588682834059, 0.00016117731865961105, 0.00017151120118796825, 0.002300631022080779 ]
{ "id": 1, "code_window": [ " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/0.20.3.zip\",\n", " strip_prefix = \"rules_typescript-0.20.3\",\n", " sha256 = \"2a03b23c30c5109ab0863cfa60acce73ceb56337d41efc2dd67f8455a1c1d5f3\",\n", " )\n", "\n", " # Needed for Remote Execution\n", " _maybe(\n", " http_archive,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " url = \"https://github.com/bazelbuild/rules_typescript/archive/8ea1a55cf5cf8be84ddfeefc0940769b80da792f.zip\",\n", " strip_prefix = \"rules_typescript-8ea1a55cf5cf8be84ddfeefc0940769b80da792f\",\n" ], "file_path": "packages/bazel/package.bzl", "type": "replace", "edit_start_line_idx": 26 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0008568545454181731, 0.00020781089551746845, 0.0001636448287172243, 0.00017206440679728985, 0.0001242553989868611 ]
{ "id": 1, "code_window": [ " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/0.20.3.zip\",\n", " strip_prefix = \"rules_typescript-0.20.3\",\n", " sha256 = \"2a03b23c30c5109ab0863cfa60acce73ceb56337d41efc2dd67f8455a1c1d5f3\",\n", " )\n", "\n", " # Needed for Remote Execution\n", " _maybe(\n", " http_archive,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " url = \"https://github.com/bazelbuild/rules_typescript/archive/8ea1a55cf5cf8be84ddfeefc0940769b80da792f.zip\",\n", " strip_prefix = \"rules_typescript-8ea1a55cf5cf8be84ddfeefc0940769b80da792f\",\n" ], "file_path": "packages/bazel/package.bzl", "type": "replace", "edit_start_line_idx": 26 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [['шөнө дунд', 'үд дунд', 'өглөө', 'өдөр', 'орой', 'шөнө'], u, u], u, [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ];
packages/common/locales/extra/mn.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017540874250698835, 0.00017255179409403354, 0.0001699026906862855, 0.00017234397819265723, 0.000002252634658361785 ]
{ "id": 1, "code_window": [ " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/0.20.3.zip\",\n", " strip_prefix = \"rules_typescript-0.20.3\",\n", " sha256 = \"2a03b23c30c5109ab0863cfa60acce73ceb56337d41efc2dd67f8455a1c1d5f3\",\n", " )\n", "\n", " # Needed for Remote Execution\n", " _maybe(\n", " http_archive,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " url = \"https://github.com/bazelbuild/rules_typescript/archive/8ea1a55cf5cf8be84ddfeefc0940769b80da792f.zip\",\n", " strip_prefix = \"rules_typescript-8ea1a55cf5cf8be84ddfeefc0940769b80da792f\",\n" ], "file_path": "packages/bazel/package.bzl", "type": "replace", "edit_start_line_idx": 26 }
import * as foo from './somewhere'; /** @publicApi */ export declare class A extends foo.Bar { }
tools/ts-api-guardian/test/fixtures/module_identifier.d.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.000173955675563775, 0.000173955675563775, 0.000173955675563775, 0.000173955675563775, 0 ]
{ "id": 1, "code_window": [ " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_typescript\",\n", " url = \"https://github.com/bazelbuild/rules_typescript/archive/0.20.3.zip\",\n", " strip_prefix = \"rules_typescript-0.20.3\",\n", " sha256 = \"2a03b23c30c5109ab0863cfa60acce73ceb56337d41efc2dd67f8455a1c1d5f3\",\n", " )\n", "\n", " # Needed for Remote Execution\n", " _maybe(\n", " http_archive,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " url = \"https://github.com/bazelbuild/rules_typescript/archive/8ea1a55cf5cf8be84ddfeefc0940769b80da792f.zip\",\n", " strip_prefix = \"rules_typescript-8ea1a55cf5cf8be84ddfeefc0940769b80da792f\",\n" ], "file_path": "packages/bazel/package.bzl", "type": "replace", "edit_start_line_idx": 26 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'vo', [['AM', 'PM'], u, u], u, [['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], u, u], u, [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], u ], u, [['BCE', 'CE'], u, u], 1, [6, 0], ['y-MM-dd', 'y MMM d', 'y MMMM d', 'y MMMM d, EEEE'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], u, u, {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural ];
packages/common/locales/vo.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017540890257805586, 0.00017311255214735866, 0.00016990235599223524, 0.00017356946773361415, 0.000002042767164311954 ]
{ "id": 2, "code_window": [ "\"\"\"\n", "\n", "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n", "\n", "# This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.1/package.bzl\n", "VERSION = \"0.15.1\"\n", "\n", "def rules_nodejs_dependencies():\n", " \"\"\"\n", " Fetch our transitive dependencies.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "# This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.3/package.bzl\n", "VERSION = \"0.15.3\"\n" ], "file_path": "packages/bazel/rules_nodejs_package.bzl", "type": "replace", "edit_start_line_idx": 21 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0020684502087533474, 0.0003071547544095665, 0.0001658731052884832, 0.0001743253378663212, 0.00040548600372858346 ]
{ "id": 2, "code_window": [ "\"\"\"\n", "\n", "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n", "\n", "# This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.1/package.bzl\n", "VERSION = \"0.15.1\"\n", "\n", "def rules_nodejs_dependencies():\n", " \"\"\"\n", " Fetch our transitive dependencies.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "# This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.3/package.bzl\n", "VERSION = \"0.15.3\"\n" ], "file_path": "packages/bazel/rules_nodejs_package.bzl", "type": "replace", "edit_start_line_idx": 21 }
{ "compileOnSave": false, "compilerOptions": { "strict": true, "noImplicitAny": false, // disabled because this is on by default in tsc 2.7 breaking our codebase - we need to refactor "strictPropertyInitialization": false, // disabled because of https://github.com/angular/angular/issues/22877 "skipLibCheck": true, "outDir": "./dist/out-tsc", "baseUrl": "src", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "noUnusedLocals": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2016", "dom" ] }, "exclude": [ "content", "tools", "aio-builds-setup", "node_modules", "scripts" ] }
aio/tsconfig.json
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017488186131231487, 0.00017010318697430193, 0.00016833336849231273, 0.0001685987808741629, 0.000002762880740192486 ]
{ "id": 2, "code_window": [ "\"\"\"\n", "\n", "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n", "\n", "# This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.1/package.bzl\n", "VERSION = \"0.15.1\"\n", "\n", "def rules_nodejs_dependencies():\n", " \"\"\"\n", " Fetch our transitive dependencies.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "# This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.3/package.bzl\n", "VERSION = \"0.15.3\"\n" ], "file_path": "packages/bazel/rules_nodejs_package.bzl", "type": "replace", "edit_start_line_idx": 21 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {getDebugNode} from '@angular/core'; import {NodeFlags, Services, asTextData, elementDef, textDef} from '@angular/core/src/view/index'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {ARG_TYPE_VALUES, checkNodeInlineOrDynamic, compViewDef, createAndGetRootNodes} from './helper'; { describe(`View Text`, () => { describe('create', () => { it('should create text nodes without parents', () => { const rootNodes = createAndGetRootNodes(compViewDef([textDef(0, null, ['a'])])).rootNodes; expect(rootNodes.length).toBe(1); expect(getDOM().getText(rootNodes[0])).toBe('a'); }); it('should create views with multiple root text nodes', () => { const rootNodes = createAndGetRootNodes(compViewDef([ textDef(0, null, ['a']), textDef(1, null, ['b']), ])).rootNodes; expect(rootNodes.length).toBe(2); }); it('should create text nodes with parents', () => { const rootNodes = createAndGetRootNodes(compViewDef([ elementDef(0, NodeFlags.None, null, null, 1, 'div'), textDef(1, null, ['a']), ])).rootNodes; expect(rootNodes.length).toBe(1); const textNode = getDOM().firstChild(rootNodes[0]); expect(getDOM().getText(textNode)).toBe('a'); }); it('should add debug information to the renderer', () => { const someContext = new Object(); const {view, rootNodes} = createAndGetRootNodes(compViewDef([textDef(0, null, ['a'])]), someContext); expect(getDebugNode(rootNodes[0]) !.nativeNode).toBe(asTextData(view, 0).renderText); }); }); describe('change text', () => { ARG_TYPE_VALUES.forEach((inlineDynamic) => { it(`should update via strategy ${inlineDynamic}`, () => { const {view, rootNodes} = createAndGetRootNodes(compViewDef( [ textDef(0, null, ['0', '1', '2']), ], null !, (check, view) => { checkNodeInlineOrDynamic(check, view, 0, inlineDynamic, ['a', 'b']); })); Services.checkAndUpdateView(view); expect(getDOM().getText(rootNodes[0])).toBe('0a1b2'); }); }); }); }); }
packages/core/test/view/text_spec.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017448226572014391, 0.00017320088227279484, 0.00016981473891064525, 0.00017367668624501675, 0.000001441062863705156 ]
{ "id": 2, "code_window": [ "\"\"\"\n", "\n", "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n", "\n", "# This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.1/package.bzl\n", "VERSION = \"0.15.1\"\n", "\n", "def rules_nodejs_dependencies():\n", " \"\"\"\n", " Fetch our transitive dependencies.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "# This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.3/package.bzl\n", "VERSION = \"0.15.3\"\n" ], "file_path": "packages/bazel/rules_nodejs_package.bzl", "type": "replace", "edit_start_line_idx": 21 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CompilerConfig} from '../config'; import {MissingTranslationStrategy, ViewEncapsulation} from '../core'; import {DirectiveNormalizer} from '../directive_normalizer'; import {DirectiveResolver} from '../directive_resolver'; import {Lexer} from '../expression_parser/lexer'; import {Parser} from '../expression_parser/parser'; import {I18NHtmlParser} from '../i18n/i18n_html_parser'; import {InjectableCompiler} from '../injectable_compiler'; import {CompileMetadataResolver} from '../metadata_resolver'; import {HtmlParser} from '../ml_parser/html_parser'; import {NgModuleCompiler} from '../ng_module_compiler'; import {NgModuleResolver} from '../ng_module_resolver'; import {TypeScriptEmitter} from '../output/ts_emitter'; import {PipeResolver} from '../pipe_resolver'; import {DomElementSchemaRegistry} from '../schema/dom_element_schema_registry'; import {StyleCompiler} from '../style_compiler'; import {TemplateParser} from '../template_parser/template_parser'; import {UrlResolver} from '../url_resolver'; import {syntaxError} from '../util'; import {TypeCheckCompiler} from '../view_compiler/type_check_compiler'; import {ViewCompiler} from '../view_compiler/view_compiler'; import {AotCompiler} from './compiler'; import {AotCompilerHost} from './compiler_host'; import {AotCompilerOptions} from './compiler_options'; import {StaticReflector} from './static_reflector'; import {StaticSymbol, StaticSymbolCache} from './static_symbol'; import {StaticSymbolResolver} from './static_symbol_resolver'; import {AotSummaryResolver} from './summary_resolver'; export function createAotUrlResolver(host: { resourceNameToFileName(resourceName: string, containingFileName: string): string | null; }): UrlResolver { return { resolve: (basePath: string, url: string) => { const filePath = host.resourceNameToFileName(url, basePath); if (!filePath) { throw syntaxError(`Couldn't resolve resource ${url} from ${basePath}`); } return filePath; } }; } /** * Creates a new AotCompiler based on options and a host. */ export function createAotCompiler( compilerHost: AotCompilerHost, options: AotCompilerOptions, errorCollector?: (error: any, type?: any) => void): {compiler: AotCompiler, reflector: StaticReflector} { let translations: string = options.translations || ''; const urlResolver = createAotUrlResolver(compilerHost); const symbolCache = new StaticSymbolCache(); const summaryResolver = new AotSummaryResolver(compilerHost, symbolCache); const symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver); const staticReflector = new StaticReflector(summaryResolver, symbolResolver, [], [], errorCollector); let htmlParser: I18NHtmlParser; if (!!options.enableIvy) { // Ivy handles i18n at the compiler level so we must use a regular parser htmlParser = new HtmlParser() as I18NHtmlParser; } else { htmlParser = new I18NHtmlParser( new HtmlParser(), translations, options.i18nFormat, options.missingTranslation, console); } const config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false, missingTranslation: options.missingTranslation, preserveWhitespaces: options.preserveWhitespaces, strictInjectionParameters: options.strictInjectionParameters, }); const normalizer = new DirectiveNormalizer( {get: (url: string) => compilerHost.loadResource(url)}, urlResolver, htmlParser, config); const expressionParser = new Parser(new Lexer()); const elementSchemaRegistry = new DomElementSchemaRegistry(); const tmplParser = new TemplateParser( config, staticReflector, expressionParser, elementSchemaRegistry, htmlParser, console, []); const resolver = new CompileMetadataResolver( config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector, errorCollector); // TODO(vicb): do not pass options.i18nFormat here const viewCompiler = new ViewCompiler(staticReflector); const typeCheckCompiler = new TypeCheckCompiler(options, staticReflector); const compiler = new AotCompiler( config, options, compilerHost, staticReflector, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, typeCheckCompiler, new NgModuleCompiler(staticReflector), new InjectableCompiler(staticReflector, !!options.enableIvy), new TypeScriptEmitter(), summaryResolver, symbolResolver); return {compiler, reflector: staticReflector}; }
packages/compiler/src/aot/compiler_factory.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017573620425537229, 0.00017344701336696744, 0.00017014896729961038, 0.00017388352716807276, 0.000001837315721786581 ]
{ "id": 3, "code_window": [ " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_nodejs\",\n", " urls = [\"https://github.com/bazelbuild/rules_nodejs/archive/0.15.1.zip\"],\n", " sha256 = \"a0a91a2e0cee32e9304f1aeea9e6c1b611afba548058c5980217d44ee11e3dd7\",\n", " strip_prefix = \"rules_nodejs-0.15.1\",\n", " )\n", "\n", " # ts_web_test depends on the web testing rules to provision browsers.\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " urls = [\"https://github.com/bazelbuild/rules_nodejs/archive/0.15.3.zip\"],\n", " strip_prefix = \"rules_nodejs-0.15.3\",\n" ], "file_path": "packages/bazel/rules_typescript_package.bzl", "type": "replace", "edit_start_line_idx": 37 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.004566736053675413, 0.0004060228238813579, 0.0001621482806513086, 0.00017176085384562612, 0.0007744053145870566 ]
{ "id": 3, "code_window": [ " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_nodejs\",\n", " urls = [\"https://github.com/bazelbuild/rules_nodejs/archive/0.15.1.zip\"],\n", " sha256 = \"a0a91a2e0cee32e9304f1aeea9e6c1b611afba548058c5980217d44ee11e3dd7\",\n", " strip_prefix = \"rules_nodejs-0.15.1\",\n", " )\n", "\n", " # ts_web_test depends on the web testing rules to provision browsers.\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " urls = [\"https://github.com/bazelbuild/rules_nodejs/archive/0.15.3.zip\"],\n", " strip_prefix = \"rules_nodejs-0.15.3\",\n" ], "file_path": "packages/bazel/rules_typescript_package.bzl", "type": "replace", "edit_start_line_idx": 37 }
{$ doc.data | json $}
aio/tools/transforms/templates/json-doc.template.json
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0001710758951958269, 0.0001710758951958269, 0.0001710758951958269, 0.0001710758951958269, 0 ]
{ "id": 3, "code_window": [ " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_nodejs\",\n", " urls = [\"https://github.com/bazelbuild/rules_nodejs/archive/0.15.1.zip\"],\n", " sha256 = \"a0a91a2e0cee32e9304f1aeea9e6c1b611afba548058c5980217d44ee11e3dd7\",\n", " strip_prefix = \"rules_nodejs-0.15.1\",\n", " )\n", "\n", " # ts_web_test depends on the web testing rules to provision browsers.\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " urls = [\"https://github.com/bazelbuild/rules_nodejs/archive/0.15.3.zip\"],\n", " strip_prefix = \"rules_nodejs-0.15.3\",\n" ], "file_path": "packages/bazel/rules_typescript_package.bzl", "type": "replace", "edit_start_line_idx": 37 }
load("@io_bazel_skydoc//skylark:skylark.bzl", "skylark_doc") skylark_doc( name = "docs", srcs = [ "//packages/bazel/src:ng_module.bzl", "//packages/bazel/src:ng_rollup_bundle.bzl", "//packages/bazel/src:ng_setup_workspace.bzl", "//packages/bazel/src/ng_package:ng_package.bzl", "//packages/bazel/src/protractor:protractor_web_test.bzl", ], format = "html", site_root = "/bazel-builds", strip_prefix = "packages/bazel/", visibility = ["//packages/bazel:__subpackages__"], )
packages/bazel/docs/BUILD.bazel
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0002852327888831496, 0.0002798688365146518, 0.0002745049132499844, 0.0002798688365146518, 0.00000536393781658262 ]
{ "id": 3, "code_window": [ " _maybe(\n", " http_archive,\n", " name = \"build_bazel_rules_nodejs\",\n", " urls = [\"https://github.com/bazelbuild/rules_nodejs/archive/0.15.1.zip\"],\n", " sha256 = \"a0a91a2e0cee32e9304f1aeea9e6c1b611afba548058c5980217d44ee11e3dd7\",\n", " strip_prefix = \"rules_nodejs-0.15.1\",\n", " )\n", "\n", " # ts_web_test depends on the web testing rules to provision browsers.\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " urls = [\"https://github.com/bazelbuild/rules_nodejs/archive/0.15.3.zip\"],\n", " strip_prefix = \"rules_nodejs-0.15.3\",\n" ], "file_path": "packages/bazel/rules_typescript_package.bzl", "type": "replace", "edit_start_line_idx": 37 }
hr { margin: 20px 0; border: 0; border-top: 1px dashed #c5c5c5; border-bottom: 1px dashed #f7f7f7; } .learn a { font-weight: normal; text-decoration: none; color: #b83f45; } .learn a:hover { text-decoration: underline; color: #787e7e; } .learn h3, .learn h4, .learn h5 { margin: 10px 0; font-weight: 500; line-height: 1.2; color: #000; } .learn h3 { font-size: 24px; } .learn h4 { font-size: 18px; } .learn h5 { margin-bottom: 0; font-size: 14px; } .learn ul { padding: 0; margin: 0 0 30px 25px; } .learn li { line-height: 20px; } .learn p { font-size: 15px; font-weight: 300; line-height: 1.3; margin-top: 0; margin-bottom: 0; } #issue-count { display: none; } .quote { border: none; margin: 20px 0 60px 0; } .quote p { font-style: italic; } .quote p:before { content: '“'; font-size: 50px; opacity: .15; position: absolute; top: -20px; left: 3px; } .quote p:after { content: '”'; font-size: 50px; opacity: .15; position: absolute; bottom: -42px; right: 3px; } .quote footer { position: absolute; bottom: -40px; right: 0; } .quote footer img { border-radius: 3px; } .quote footer a { margin-left: 5px; vertical-align: middle; } .speech-bubble { position: relative; padding: 10px; background: rgba(0, 0, 0, .04); border-radius: 5px; } .speech-bubble:after { content: ''; position: absolute; top: 100%; right: 30px; border: 13px solid transparent; border-top-color: rgba(0, 0, 0, .04); } .learn-bar > .learn { position: absolute; width: 272px; top: 8px; left: -300px; padding: 10px; border-radius: 5px; background-color: rgba(255, 255, 255, .6); transition-property: left; transition-duration: 500ms; } @media (min-width: 899px) { .learn-bar { width: auto; padding-left: 300px; } .learn-bar > .learn { left: 8px; } }
packages/core/test/bundling/todo/base.css
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017661877791397274, 0.00017384918464813381, 0.00017063587438315153, 0.00017411248700227588, 0.0000015864104625507025 ]
{ "id": 4, "code_window": [ " // then the 'environment' will equal 'local' and\n", " // 'webTestFiles' will contain the path to the binary to use\n", " const webTestNamedFiles = webTestMetadata['webTestFiles'][0]['namedFiles'];\n", " const headless = !process.env['DISPLAY'];\n", " if (webTestNamedFiles['CHROMIUM']) {\n", " const chromeBin = path.join(process.cwd(), 'external', webTestNamedFiles['CHROMIUM']);\n", " const args = [];\n", " if (headless) {\n", " args.push('--headless');\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const chromeBin = require.resolve(webTestNamedFiles['CHROMIUM']);\n", " const chromeDriver = require.resolve(webTestNamedFiles['CHROMEDRIVER']);\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 102 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const path = require('path'); const DEBUG = false; const configPath = 'TMPL_config'; const onPreparePath = 'TMPL_on_prepare'; const workspace = 'TMPL_workspace'; const server = 'TMPL_server'; if (DEBUG) console.info(`Protractor test starting with: cwd: ${process.cwd()} configPath: ${configPath} onPreparePath: ${onPreparePath} workspace: ${workspace} server: ${server}`); // Helper function to warn when a user specified value is being overwritten function setConf(conf, name, value, msg) { if (conf[name] && conf[name] !== value) { console.warn( `Your protractor configuration specifies an option which is overwritten by Bazel: '${name}' ${msg}`); } conf[name] = value; } let conf = {}; // Import the user's base protractor configuration if specified if (configPath) { const baseConf = require(configPath); if (!baseConf.config) { throw new Error('Invalid base protractor configration. Expected config to be exported.'); } conf = baseConf.config; } // Import the user's on prepare function if specified if (onPreparePath) { const onPrepare = require(onPreparePath); if (typeof onPrepare === 'function') { const original = conf.onPrepare; conf.onPrepare = function() { return Promise.resolve(original ? original() : null) .then(() => Promise.resolve(onPrepare({workspace, server}))); }; } else { throw new Error( 'Invalid protractor on_prepare script. Expected a function as the default export.'); } } // Override the user's base protractor configuration as appropriate based on the // ts_web_test_suite & rules_webtesting WEB_TEST_METADATA attributes setConf(conf, 'framework', 'jasmine2', 'is set to jasmine2'); const specs = [TMPL_specs].map(s => require.resolve(s)).filter(s => /\b(spec|test)\.js$/.test(s)); setConf(conf, 'specs', specs, 'are determined by the srcs and deps attribute'); // WEB_TEST_METADATA is configured in rules_webtesting based on value // of the browsers attribute passed to ts_web_test_suite // We setup the protractor configuration based on the values in this object if (process.env['WEB_TEST_METADATA']) { const webTestMetadata = require(process.env['WEB_TEST_METADATA']); if (DEBUG) console.info(`WEB_TEST_METADATA: ${JSON.stringify(webTestMetadata, null, 2)}`); if (webTestMetadata['environment'] === 'sauce') { // If a sauce labs browser is chosen for the test such as // "@io_bazel_rules_webtesting//browsers/sauce:chrome-win10" // than the 'environment' will equal 'sauce'. // We expect that a SAUCE_USERNAME and SAUCE_ACCESS_KEY is available // from the environment for this test to run // TODO(gmagolan): implement sauce labs support for protractor throw new Error('Saucelabs not yet support by protractor_web_test_suite.'); // if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) { // console.error('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are // set.'); // process.exit(1); // } // setConf(conf, 'sauceUser', process.env.SAUCE_USERNAME, 'is determined by the SAUCE_USERNAME // environment variable'); // setConf(conf, 'sauceKey', process.env.SAUCE_ACCESS_KEY, 'is determined by the // SAUCE_ACCESS_KEY environment variable'); } else if (webTestMetadata['environment'] === 'local') { // When a local chrome or firefox browser is chosen such as // "@io_bazel_rules_webtesting//browsers:chromium-local" or // "@io_bazel_rules_webtesting//browsers:firefox-local" // then the 'environment' will equal 'local' and // 'webTestFiles' will contain the path to the binary to use const webTestNamedFiles = webTestMetadata['webTestFiles'][0]['namedFiles']; const headless = !process.env['DISPLAY']; if (webTestNamedFiles['CHROMIUM']) { const chromeBin = path.join(process.cwd(), 'external', webTestNamedFiles['CHROMIUM']); const args = []; if (headless) { args.push('--headless'); args.push('--disable-gpu'); } setConf(conf, 'directConnect', true, 'is set to true for chrome'); setConf( conf, 'chromeDriver', path.join(process.cwd(), 'external', webTestNamedFiles['CHROMEDRIVER']), 'is determined by the browsers attribute'); setConf( conf, 'capabilities', { browserName: 'chrome', chromeOptions: { binary: chromeBin, args: args, } }, 'is determined by the browsers attribute'); } if (webTestNamedFiles['FIREFOX']) { // TODO(gmagolan): implement firefox support for protractor throw new Error('Firefox not yet support by protractor_web_test_suite'); // const firefoxBin = path.join('external', webTestNamedFiles['FIREFOX']); // const args = []; // if (headless) { // args.push("--headless") // args.push("--marionette") // } // setConf(conf, 'seleniumAddress', process.env.WEB_TEST_HTTP_SERVER.trim() + "/wd/hub", 'is // configured by Bazel for firefox browser') // setConf(conf, 'capabilities', { // browserName: "firefox", // 'moz:firefoxOptions': { // binary: firefoxBin, // args: args, // } // }, 'is determined by the browsers attribute'); } } else { console.warn(`Unknown WEB_TEST_METADATA environment '${webTestMetadata['environment']}'`); } } // Export the complete protractor configuration if (DEBUG) console.info(`Protractor configuration: ${JSON.stringify(conf, null, 2)}`); exports.config = conf;
packages/bazel/src/protractor/protractor.conf.js
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.9991727471351624, 0.29387781023979187, 0.00016713640070520341, 0.0003624410310294479, 0.44014090299606323 ]
{ "id": 4, "code_window": [ " // then the 'environment' will equal 'local' and\n", " // 'webTestFiles' will contain the path to the binary to use\n", " const webTestNamedFiles = webTestMetadata['webTestFiles'][0]['namedFiles'];\n", " const headless = !process.env['DISPLAY'];\n", " if (webTestNamedFiles['CHROMIUM']) {\n", " const chromeBin = path.join(process.cwd(), 'external', webTestNamedFiles['CHROMIUM']);\n", " const args = [];\n", " if (headless) {\n", " args.push('--headless');\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const chromeBin = require.resolve(webTestNamedFiles['CHROMIUM']);\n", " const chromeDriver = require.resolve(webTestNamedFiles['CHROMEDRIVER']);\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 102 }
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // #docregion imports import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; // #enddocregion imports import { HeroDetailComponent } from './hero-detail.component'; import { HeroListComponent } from './hero-list.component'; import { SalesTaxComponent } from './sales-tax.component'; import { HeroService } from './hero.service'; import { BackendService } from './backend.service'; import { Logger } from './logger.service'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent, HeroDetailComponent, HeroListComponent, SalesTaxComponent ], // #docregion providers providers: [ BackendService, HeroService, Logger ], // #enddocregion providers bootstrap: [ AppComponent ] }) // #docregion export export class AppModule { } // #enddocregion export
aio/content/examples/architecture/src/app/app.module.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017654015391599387, 0.00017361185746267438, 0.00017129871412180364, 0.00017330428818240762, 0.0000019574049474613275 ]
{ "id": 4, "code_window": [ " // then the 'environment' will equal 'local' and\n", " // 'webTestFiles' will contain the path to the binary to use\n", " const webTestNamedFiles = webTestMetadata['webTestFiles'][0]['namedFiles'];\n", " const headless = !process.env['DISPLAY'];\n", " if (webTestNamedFiles['CHROMIUM']) {\n", " const chromeBin = path.join(process.cwd(), 'external', webTestNamedFiles['CHROMIUM']);\n", " const args = [];\n", " if (headless) {\n", " args.push('--headless');\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const chromeBin = require.resolve(webTestNamedFiles['CHROMIUM']);\n", " const chromeDriver = require.resolve(webTestNamedFiles['CHROMEDRIVER']);\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 102 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as e from '../../../src/expression_parser/ast'; import * as a from '../../../src/render3/r3_ast'; export function findExpression(tmpl: a.Node[], expr: string): e.AST|null { const res = tmpl.reduce((found, node) => { if (found !== null) { return found; } else { return findExpressionInNode(node, expr); } }, null as e.AST | null); if (res instanceof e.ASTWithSource) { return res.ast; } return res; } function findExpressionInNode(node: a.Node, expr: string): e.AST|null { if (node instanceof a.Element || node instanceof a.Template) { return findExpression( [ ...node.inputs, ...node.outputs, ...node.children, ], expr); } else if (node instanceof a.BoundAttribute || node instanceof a.BoundText) { const ts = toStringExpression(node.value); return toStringExpression(node.value) === expr ? node.value : null; } else if (node instanceof a.BoundEvent) { return toStringExpression(node.handler) === expr ? node.handler : null; } else { return null; } } export function toStringExpression(expr: e.AST): string { while (expr instanceof e.ASTWithSource) { expr = expr.ast; } if (expr instanceof e.PropertyRead) { if (expr.receiver instanceof e.ImplicitReceiver) { return expr.name; } else { return `${toStringExpression(expr.receiver)}.${expr.name}`; } } else if (expr instanceof e.ImplicitReceiver) { return ''; } else if (expr instanceof e.Interpolation) { let str = '{{'; for (let i = 0; i < expr.expressions.length; i++) { str += expr.strings[i] + toStringExpression(expr.expressions[i]); } str += expr.strings[expr.strings.length - 1] + '}}'; return str; } else { throw new Error(`Unsupported type: ${(expr as any).constructor.name}`); } }
packages/compiler/test/render3/view/util.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017584816669113934, 0.0001744115725159645, 0.0001735724217724055, 0.00017396330076735467, 9.090480830309389e-7 ]
{ "id": 4, "code_window": [ " // then the 'environment' will equal 'local' and\n", " // 'webTestFiles' will contain the path to the binary to use\n", " const webTestNamedFiles = webTestMetadata['webTestFiles'][0]['namedFiles'];\n", " const headless = !process.env['DISPLAY'];\n", " if (webTestNamedFiles['CHROMIUM']) {\n", " const chromeBin = path.join(process.cwd(), 'external', webTestNamedFiles['CHROMIUM']);\n", " const args = [];\n", " if (headless) {\n", " args.push('--headless');\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const chromeBin = require.resolve(webTestNamedFiles['CHROMIUM']);\n", " const chromeDriver = require.resolve(webTestNamedFiles['CHROMEDRIVER']);\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 102 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ɵglobal as global} from '@angular/core'; const CAMEL_CASE_REGEXP = /([A-Z])/g; const DASH_CASE_REGEXP = /-([a-z])/g; export function camelCaseToDashCase(input: string): string { return input.replace(CAMEL_CASE_REGEXP, (...m: string[]) => '-' + m[1].toLowerCase()); } export function dashCaseToCamelCase(input: string): string { return input.replace(DASH_CASE_REGEXP, (...m: string[]) => m[1].toUpperCase()); } /** * Exports the value under a given `name` in the global property `ng`. For example `ng.probe` if * `name` is `'probe'`. * @param name Name under which it will be exported. Keep in mind this will be a property of the * global `ng` object. * @param value The value to export. */ export function exportNgVar(name: string, value: any): void { if (typeof COMPILED === 'undefined' || !COMPILED) { // Note: we can't export `ng` when using closure enhanced optimization as: // - closure declares globals itself for minified names, which sometimes clobber our `ng` global // - we can't declare a closure extern as the namespace `ng` is already used within Google // for typings for angularJS (via `goog.provide('ng....')`). const ng = global['ng'] = (global['ng'] as{[key: string]: any} | undefined) || {}; ng[name] = value; } }
packages/platform-browser/src/dom/util.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017521115660201758, 0.00017358263721689582, 0.000172574698808603, 0.00017327234672848135, 0.0000010141350230696844 ]
{ "id": 5, "code_window": [ " setConf(conf, 'directConnect', true, 'is set to true for chrome');\n", " setConf(\n", " conf, 'chromeDriver',\n", " path.join(process.cwd(), 'external', webTestNamedFiles['CHROMEDRIVER']),\n", " 'is determined by the browsers attribute');\n", " setConf(\n", " conf, 'capabilities', {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " chromeDriver,\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 111 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0011777135077863932, 0.00022864429047331214, 0.00016465925727970898, 0.00017000228399410844, 0.0001849796244641766 ]
{ "id": 5, "code_window": [ " setConf(conf, 'directConnect', true, 'is set to true for chrome');\n", " setConf(\n", " conf, 'chromeDriver',\n", " path.join(process.cwd(), 'external', webTestNamedFiles['CHROMEDRIVER']),\n", " 'is determined by the browsers attribute');\n", " setConf(\n", " conf, 'capabilities', {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " chromeDriver,\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 111 }
# Feature Modules Feature modules are NgModules for the purpose of organizing code. #### Prerequisites A basic understanding of the following: * [Bootstrapping](guide/bootstrapping). * [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule). * [Frequently Used Modules](guide/frequent-ngmodules). For the final sample app with a feature module that this page describes, see the <live-example></live-example>. <hr> As your app grows, you can organize code relevant for a specific feature. This helps apply clear boundaries for features. With feature modules, you can keep code related to a specific functionality or feature separate from other code. Delineating areas of your app helps with collaboration between developers and teams, separating directives, and managing the size of the root module. ## Feature modules vs. root modules A feature module is an organizational best practice, as opposed to a concept of the core Angular API. A feature module delivers a cohesive set of functionality focused on a specific application need such as a user workflow, routing, or forms. While you can do everything within the root module, feature modules help you partition the app into focused areas. A feature module collaborates with the root module and with other modules through the services it provides and the components, directives, and pipes that it shares. ## How to make a feature module Assuming you already have an app that you created with the [Angular CLI](cli), create a feature module using the CLI by entering the following command in the root project directory. Replace `CustomerDashboard` with the name of your module. You can omit the "Module" suffix from the name because the CLI appends it: ```sh ng generate module CustomerDashboard ``` This causes the CLI to create a folder called `customer-dashboard` with a file inside called `customer-dashboard.module.ts` with the following contents: ```typescript import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @NgModule({ imports: [ CommonModule ], declarations: [] }) export class CustomerDashboardModule { } ``` The structure of an NgModule is the same whether it is a root module or a feature module. In the CLI generated feature module, there are two JavaScript import statements at the top of the file: the first imports `NgModule`, which, like the root module, lets you use the `@NgModule` decorator; the second imports `CommonModule`, which contributes many common directives such as `ngIf` and `ngFor`. Feature modules import `CommonModule` instead of `BrowserModule`, which is only imported once in the root module. `CommonModule` only contains information for common directives such as `ngIf` and `ngFor` which are needed in most templates, whereas `BrowserModule` configures the Angular app for the browser which needs to be done only once. The `declarations` array is available for you to add declarables, which are components, directives, and pipes that belong exclusively to this particular module. To add a component, enter the following command at the command line where `customer-dashboard` is the directory where the CLI generated the feature module and `CustomerDashboard` is the name of the component: ```sh ng generate component customer-dashboard/CustomerDashboard ``` This generates a folder for the new component within the customer-dashboard folder and updates the feature module with the `CustomerDashboardComponent` info: <code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard.module.ts" region="customer-dashboard-component" header="src/app/customer-dashboard/customer-dashboard.module.ts" linenums="false"> </code-example> The `CustomerDashboardComponent` is now in the JavaScript import list at the top and added to the `declarations` array, which lets Angular know to associate this new component with this feature module. ## Importing a feature module To incorporate the feature module into your app, you have to let the root module, `app.module.ts`, know about it. Notice the `CustomerDashboardModule` export at the bottom of `customer-dashboard.module.ts`. This exposes it so that other modules can get to it. To import it into the `AppModule`, add it to the imports in `app.module.ts` and to the `imports` array: <code-example path="feature-modules/src/app/app.module.ts" region="app-module" header="src/app/app.module.ts" linenums="false"> </code-example> Now the `AppModule` knows about the feature module. If you were to add any service providers to the feature module, `AppModule` would know about those too, as would any other feature modules. However, NgModules don’t expose their components. ## Rendering a feature module’s component template When the CLI generated the `CustomerDashboardComponent` for the feature module, it included a template, `customer-dashboard.component.html`, with the following markup: <code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard/customer-dashboard.component.html" region="feature-template" header="src/app/customer-dashboard/customer-dashboard/customer-dashboard.component.html" linenums="false"> </code-example> To see this HTML in the `AppComponent`, you first have to export the `CustomerDashboardComponent` in the `CustomerDashboardModule`. In `customer-dashboard.module.ts`, just beneath the `declarations` array, add an `exports` array containing `CustomerDashboardModule`: <code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard.module.ts" region="component-exports" header="src/app/customer-dashboard/customer-dashboard.module.ts" linenums="false"> </code-example> Next, in the `AppComponent`, `app.component.html`, add the tag `<app-customer-dashboard>`: <code-example path="feature-modules/src/app/app.component.html" region="app-component-template" header="src/app/app.component.html" linenums="false"> </code-example> Now, in addition to the title that renders by default, the `CustomerDashboardComponent` template renders too: <figure> <img src="generated/images/guide/feature-modules/feature-module.png" alt="feature module component"> </figure> <hr /> ## More on NgModules You may also be interested in the following: * [Lazy Loading Modules with the Angular Router](guide/lazy-loading-ngmodules). * [Providers](guide/providers). * [Types of Feature Modules](guide/module-types).
aio/content/guide/feature-modules.md
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0001736278791213408, 0.0001692422665655613, 0.00016294477973133326, 0.00016919038898777217, 0.0000031049803510541096 ]
{ "id": 5, "code_window": [ " setConf(conf, 'directConnect', true, 'is set to true for chrome');\n", " setConf(\n", " conf, 'chromeDriver',\n", " path.join(process.cwd(), 'external', webTestNamedFiles['CHROMEDRIVER']),\n", " 'is determined by the browsers attribute');\n", " setConf(\n", " conf, 'capabilities', {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " chromeDriver,\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 111 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CompileReflector} from './compile_reflector'; export enum LifecycleHooks { OnInit, OnDestroy, DoCheck, OnChanges, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked } export const LIFECYCLE_HOOKS_VALUES = [ LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges, LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit, LifecycleHooks.AfterViewChecked ]; export function hasLifecycleHook( reflector: CompileReflector, hook: LifecycleHooks, token: any): boolean { return reflector.hasLifecycleHook(token, getHookName(hook)); } export function getAllLifecycleHooks(reflector: CompileReflector, token: any): LifecycleHooks[] { return LIFECYCLE_HOOKS_VALUES.filter(hook => hasLifecycleHook(reflector, hook, token)); } function getHookName(hook: LifecycleHooks): string { switch (hook) { case LifecycleHooks.OnInit: return 'ngOnInit'; case LifecycleHooks.OnDestroy: return 'ngOnDestroy'; case LifecycleHooks.DoCheck: return 'ngDoCheck'; case LifecycleHooks.OnChanges: return 'ngOnChanges'; case LifecycleHooks.AfterContentInit: return 'ngAfterContentInit'; case LifecycleHooks.AfterContentChecked: return 'ngAfterContentChecked'; case LifecycleHooks.AfterViewInit: return 'ngAfterViewInit'; case LifecycleHooks.AfterViewChecked: return 'ngAfterViewChecked'; default: // This default case is not needed by TypeScript compiler, as the switch is exhaustive. // However Closure Compiler does not understand that and reports an error in typed mode. // The `throw new Error` below works around the problem, and the unexpected: never variable // makes sure tsc still checks this code is unreachable. const unexpected: never = hook; throw new Error(`unexpected ${unexpected}`); } }
packages/compiler/src/lifecycle_reflector.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00031201672391034663, 0.00019238311506342143, 0.00016973816673271358, 0.0001732875098241493, 0.000048881611292017624 ]
{ "id": 5, "code_window": [ " setConf(conf, 'directConnect', true, 'is set to true for chrome');\n", " setConf(\n", " conf, 'chromeDriver',\n", " path.join(process.cwd(), 'external', webTestNamedFiles['CHROMEDRIVER']),\n", " 'is determined by the browsers attribute');\n", " setConf(\n", " conf, 'capabilities', {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " chromeDriver,\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 111 }
Language: JavaScript BasedOnStyle: Google ColumnLimit: 100
.clang-format
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017333426512777805, 0.00017333426512777805, 0.00017333426512777805, 0.00017333426512777805, 0 ]
{ "id": 6, "code_window": [ " if (webTestNamedFiles['FIREFOX']) {\n", " // TODO(gmagolan): implement firefox support for protractor\n", " throw new Error('Firefox not yet support by protractor_web_test_suite');\n", "\n", " // const firefoxBin = path.join('external', webTestNamedFiles['FIREFOX']);\n", " // const args = [];\n", " // if (headless) {\n", " // args.push(\"--headless\")\n", " // args.push(\"--marionette\")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // const firefoxBin = require.resolve(webTestNamedFiles['FIREFOX'])\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 127 }
# Copyright 2018 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dependency-related rules defining our version and dependency versions. Fulfills similar role as the package.json file. """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_nodejs/0.15.1/package.bzl VERSION = "0.15.1" def rules_nodejs_dependencies(): """ Fetch our transitive dependencies. If the user wants to get a different version of these, they can just fetch it from their WORKSPACE before calling this function, or not call this function at all. """ _maybe( http_archive, name = "bazel_skylib", url = "https://github.com/bazelbuild/bazel-skylib/archive/0.3.1.zip", strip_prefix = "bazel-skylib-0.3.1", sha256 = "95518adafc9a2b656667bbf517a952e54ce7f350779d0dd95133db4eb5c27fb1", ) # Needed for Remote Build Execution # See https://releases.bazel.build/bazel-toolchains.html # Not strictly a dependency for all users, but it is convenient for them to have this repository # defined to reduce the effort required to on-board to remote execution. http_archive( name = "bazel_toolchains", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/archive/cdea5b8675914d0a354d89f108de5d28e54e0edc.tar.gz", "https://github.com/bazelbuild/bazel-toolchains/archive/cdea5b8675914d0a354d89f108de5d28e54e0edc.tar.gz", ], strip_prefix = "bazel-toolchains-cdea5b8675914d0a354d89f108de5d28e54e0edc", sha256 = "cefb6ccf86ca592baaa029bcef04148593c0efe8f734542f10293ea58f170715", ) def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs)
packages/bazel/rules_nodejs_package.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017768124234862626, 0.0001696736871963367, 0.0001644678122829646, 0.00016816853894852102, 0.000004817994977202034 ]
{ "id": 6, "code_window": [ " if (webTestNamedFiles['FIREFOX']) {\n", " // TODO(gmagolan): implement firefox support for protractor\n", " throw new Error('Firefox not yet support by protractor_web_test_suite');\n", "\n", " // const firefoxBin = path.join('external', webTestNamedFiles['FIREFOX']);\n", " // const args = [];\n", " // if (headless) {\n", " // args.push(\"--headless\")\n", " // args.push(\"--marionette\")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // const firefoxBin = require.resolve(webTestNamedFiles['FIREFOX'])\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 127 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Injector} from '../di'; import {DebugContext} from '../view/index'; export class EventListener { constructor(public name: string, public callback: Function) {} } /** * @publicApi */ export class DebugNode { listeners: EventListener[] = []; parent: DebugElement|null = null; constructor(public nativeNode: any, parent: DebugNode|null, private _debugContext: DebugContext) { if (parent && parent instanceof DebugElement) { parent.addChild(this); } } get injector(): Injector { return this._debugContext.injector; } get componentInstance(): any { return this._debugContext.component; } get context(): any { return this._debugContext.context; } get references(): {[key: string]: any} { return this._debugContext.references; } get providerTokens(): any[] { return this._debugContext.providerTokens; } } /** * @publicApi */ export class DebugElement extends DebugNode { name !: string; properties: {[key: string]: any} = {}; attributes: {[key: string]: string | null} = {}; classes: {[key: string]: boolean} = {}; styles: {[key: string]: string | null} = {}; childNodes: DebugNode[] = []; nativeElement: any; constructor(nativeNode: any, parent: any, _debugContext: DebugContext) { super(nativeNode, parent, _debugContext); this.nativeElement = nativeNode; } addChild(child: DebugNode) { if (child) { this.childNodes.push(child); child.parent = this; } } removeChild(child: DebugNode) { const childIndex = this.childNodes.indexOf(child); if (childIndex !== -1) { child.parent = null; this.childNodes.splice(childIndex, 1); } } insertChildrenAfter(child: DebugNode, newChildren: DebugNode[]) { const siblingIndex = this.childNodes.indexOf(child); if (siblingIndex !== -1) { this.childNodes.splice(siblingIndex + 1, 0, ...newChildren); newChildren.forEach(c => { if (c.parent) { c.parent.removeChild(c); } c.parent = this; }); } } insertBefore(refChild: DebugNode, newChild: DebugNode): void { const refIndex = this.childNodes.indexOf(refChild); if (refIndex === -1) { this.addChild(newChild); } else { if (newChild.parent) { newChild.parent.removeChild(newChild); } newChild.parent = this; this.childNodes.splice(refIndex, 0, newChild); } } query(predicate: Predicate<DebugElement>): DebugElement { const results = this.queryAll(predicate); return results[0] || null; } queryAll(predicate: Predicate<DebugElement>): DebugElement[] { const matches: DebugElement[] = []; _queryElementChildren(this, predicate, matches); return matches; } queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[] { const matches: DebugNode[] = []; _queryNodeChildren(this, predicate, matches); return matches; } get children(): DebugElement[] { return this.childNodes.filter((node) => node instanceof DebugElement) as DebugElement[]; } triggerEventHandler(eventName: string, eventObj: any) { this.listeners.forEach((listener) => { if (listener.name == eventName) { listener.callback(eventObj); } }); } } /** * @publicApi */ export function asNativeElements(debugEls: DebugElement[]): any { return debugEls.map((el) => el.nativeElement); } function _queryElementChildren( element: DebugElement, predicate: Predicate<DebugElement>, matches: DebugElement[]) { element.childNodes.forEach(node => { if (node instanceof DebugElement) { if (predicate(node)) { matches.push(node); } _queryElementChildren(node, predicate, matches); } }); } function _queryNodeChildren( parentNode: DebugNode, predicate: Predicate<DebugNode>, matches: DebugNode[]) { if (parentNode instanceof DebugElement) { parentNode.childNodes.forEach(node => { if (predicate(node)) { matches.push(node); } if (node instanceof DebugElement) { _queryNodeChildren(node, predicate, matches); } }); } } // Need to keep the nodes in a global Map so that multiple angular apps are supported. const _nativeNodeToDebugNode = new Map<any, DebugNode>(); /** * @publicApi */ export function getDebugNode(nativeNode: any): DebugNode|null { return _nativeNodeToDebugNode.get(nativeNode) || null; } export function getAllDebugNodes(): DebugNode[] { return Array.from(_nativeNodeToDebugNode.values()); } export function indexDebugNode(node: DebugNode) { _nativeNodeToDebugNode.set(node.nativeNode, node); } export function removeDebugNodeFromIndex(node: DebugNode) { _nativeNodeToDebugNode.delete(node.nativeNode); } /** * A boolean-valued function over a value, possibly including context information * regarding that value's position in an array. * * @publicApi */ export interface Predicate<T> { (value: T): boolean; }
packages/core/src/debug/debug_node.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017551581549923867, 0.00017089000903069973, 0.0001661499700276181, 0.0001713429664960131, 0.000002279425416418235 ]
{ "id": 6, "code_window": [ " if (webTestNamedFiles['FIREFOX']) {\n", " // TODO(gmagolan): implement firefox support for protractor\n", " throw new Error('Firefox not yet support by protractor_web_test_suite');\n", "\n", " // const firefoxBin = path.join('external', webTestNamedFiles['FIREFOX']);\n", " // const args = [];\n", " // if (headless) {\n", " // args.push(\"--headless\")\n", " // args.push(\"--marionette\")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // const firefoxBin = require.resolve(webTestNamedFiles['FIREFOX'])\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 127 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DoCheck, Input, TemplateRef, ViewContainerRef, ViewEncapsulation, createInjector, defineInjectable, defineInjector} from '../../src/core'; import {getRenderedText} from '../../src/render3/component'; import {AttributeMarker, ComponentFactory, LifecycleHooksFeature, defineComponent, directiveInject, markDirty, template} from '../../src/render3/index'; import {bind, container, containerRefreshEnd, containerRefreshStart, element, elementEnd, elementProperty, elementStart, embeddedViewEnd, embeddedViewStart, nextContext, text, textBinding, tick} from '../../src/render3/instructions'; import {ComponentDef, DirectiveDef, RenderFlags} from '../../src/render3/interfaces/definition'; import {createRendererType2} from '../../src/view/index'; import {NgIf} from './common_with_def'; import {getRendererFactory2} from './imported_renderer2'; import {ComponentFixture, containerEl, createComponent, renderComponent, renderToHtml, requestAnimationFrame, toHtml} from './render_util'; describe('component', () => { class CounterComponent { count = 0; increment() { this.count++; } static ngComponentDef = defineComponent({ type: CounterComponent, encapsulation: ViewEncapsulation.None, selectors: [['counter']], consts: 1, vars: 1, template: function(rf: RenderFlags, ctx: CounterComponent) { if (rf & RenderFlags.Create) { text(0); } if (rf & RenderFlags.Update) { textBinding(0, bind(ctx.count)); } }, factory: () => new CounterComponent, inputs: {count: 'count'}, }); } describe('renderComponent', () => { it('should render on initial call', () => { renderComponent(CounterComponent); expect(toHtml(containerEl)).toEqual('0'); }); it('should re-render on input change or method invocation', () => { const component = renderComponent(CounterComponent); expect(toHtml(containerEl)).toEqual('0'); component.count = 123; markDirty(component); expect(toHtml(containerEl)).toEqual('0'); requestAnimationFrame.flush(); expect(toHtml(containerEl)).toEqual('123'); component.increment(); markDirty(component); expect(toHtml(containerEl)).toEqual('123'); requestAnimationFrame.flush(); expect(toHtml(containerEl)).toEqual('124'); }); class MyService { constructor(public value: string) {} static ngInjectableDef = defineInjectable({providedIn: 'root', factory: () => new MyService('no-injector')}); } class MyComponent { constructor(public myService: MyService) {} static ngComponentDef = defineComponent({ type: MyComponent, encapsulation: ViewEncapsulation.None, selectors: [['my-component']], factory: () => new MyComponent(directiveInject(MyService)), consts: 1, vars: 1, template: function(fs: RenderFlags, ctx: MyComponent) { if (fs & RenderFlags.Create) { text(0); } if (fs & RenderFlags.Update) { textBinding(0, bind(ctx.myService.value)); } } }); } class MyModule { static ngInjectorDef = defineInjector({ factory: () => new MyModule(), providers: [{provide: MyService, useValue: new MyService('injector')}] }); } it('should support bootstrapping without injector', () => { const fixture = new ComponentFixture(MyComponent); expect(fixture.html).toEqual('no-injector'); }); it('should support bootstrapping with injector', () => { const fixture = new ComponentFixture(MyComponent, {injector: createInjector(MyModule)}); expect(fixture.html).toEqual('injector'); }); }); }); describe('component with a container', () => { function showItems(rf: RenderFlags, ctx: {items: string[]}) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); { for (const item of ctx.items) { const rf0 = embeddedViewStart(0, 1, 1); { if (rf0 & RenderFlags.Create) { text(0); } if (rf0 & RenderFlags.Update) { textBinding(0, bind(item)); } } embeddedViewEnd(); } } containerRefreshEnd(); } } class WrapperComponent { // TODO(issue/24571): remove '!'. items !: string[]; static ngComponentDef = defineComponent({ type: WrapperComponent, encapsulation: ViewEncapsulation.None, selectors: [['wrapper']], consts: 1, vars: 0, template: function ChildComponentTemplate(rf: RenderFlags, ctx: {items: string[]}) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); { const rf0 = embeddedViewStart(0, 1, 0); { showItems(rf0, {items: ctx.items}); } embeddedViewEnd(); } containerRefreshEnd(); } }, factory: () => new WrapperComponent, inputs: {items: 'items'} }); } function template(rf: RenderFlags, ctx: {items: string[]}) { if (rf & RenderFlags.Create) { element(0, 'wrapper'); } if (rf & RenderFlags.Update) { elementProperty(0, 'items', bind(ctx.items)); } } const defs = [WrapperComponent]; it('should re-render on input change', () => { const ctx: {items: string[]} = {items: ['a']}; expect(renderToHtml(template, ctx, 1, 1, defs)).toEqual('<wrapper>a</wrapper>'); ctx.items = [...ctx.items, 'b']; expect(renderToHtml(template, ctx, 1, 1, defs)).toEqual('<wrapper>ab</wrapper>'); }); }); // TODO: add tests with Native once tests are run in real browser (domino doesn't support shadow // root) describe('encapsulation', () => { class WrapperComponent { static ngComponentDef = defineComponent({ type: WrapperComponent, encapsulation: ViewEncapsulation.None, selectors: [['wrapper']], consts: 1, vars: 0, template: function(rf: RenderFlags, ctx: WrapperComponent) { if (rf & RenderFlags.Create) { element(0, 'encapsulated'); } }, factory: () => new WrapperComponent, directives: () => [EncapsulatedComponent] }); } class EncapsulatedComponent { static ngComponentDef = defineComponent({ type: EncapsulatedComponent, selectors: [['encapsulated']], consts: 2, vars: 0, template: function(rf: RenderFlags, ctx: EncapsulatedComponent) { if (rf & RenderFlags.Create) { text(0, 'foo'); element(1, 'leaf'); } }, factory: () => new EncapsulatedComponent, encapsulation: ViewEncapsulation.Emulated, styles: [], data: {}, directives: () => [LeafComponent] }); } class LeafComponent { static ngComponentDef = defineComponent({ type: LeafComponent, encapsulation: ViewEncapsulation.None, selectors: [['leaf']], consts: 2, vars: 0, template: function(rf: RenderFlags, ctx: LeafComponent) { if (rf & RenderFlags.Create) { elementStart(0, 'span'); { text(1, 'bar'); } elementEnd(); } }, factory: () => new LeafComponent, }); } it('should encapsulate children, but not host nor grand children', () => { renderComponent(WrapperComponent, {rendererFactory: getRendererFactory2(document)}); expect(containerEl.outerHTML) .toMatch( /<div host=""><encapsulated _nghost-c(\d+)="">foo<leaf _ngcontent-c\1=""><span>bar<\/span><\/leaf><\/encapsulated><\/div>/); }); it('should encapsulate host', () => { renderComponent(EncapsulatedComponent, {rendererFactory: getRendererFactory2(document)}); expect(containerEl.outerHTML) .toMatch( /<div host="" _nghost-c(\d+)="">foo<leaf _ngcontent-c\1=""><span>bar<\/span><\/leaf><\/div>/); }); it('should encapsulate host and children with different attributes', () => { class WrapperComponentWith { static ngComponentDef = defineComponent({ type: WrapperComponentWith, selectors: [['wrapper']], consts: 1, vars: 0, template: function(rf: RenderFlags, ctx: WrapperComponentWith) { if (rf & RenderFlags.Create) { element(0, 'leaf'); } }, factory: () => new WrapperComponentWith, encapsulation: ViewEncapsulation.Emulated, styles: [], data: {}, directives: () => [LeafComponentwith] }); } class LeafComponentwith { static ngComponentDef = defineComponent({ type: LeafComponentwith, selectors: [['leaf']], consts: 2, vars: 0, template: function(rf: RenderFlags, ctx: LeafComponentwith) { if (rf & RenderFlags.Create) { elementStart(0, 'span'); { text(1, 'bar'); } elementEnd(); } }, factory: () => new LeafComponentwith, encapsulation: ViewEncapsulation.Emulated, styles: [], data: {}, }); } renderComponent(WrapperComponentWith, {rendererFactory: getRendererFactory2(document)}); expect(containerEl.outerHTML) .toMatch( /<div host="" _nghost-c(\d+)=""><leaf _ngcontent-c\1="" _nghost-c(\d+)=""><span _ngcontent-c\2="">bar<\/span><\/leaf><\/div>/); }); }); describe('recursive components', () => { let events: string[]; let count: number; beforeEach(() => { events = []; count = 0; }); class TreeNode { constructor( public value: number, public depth: number, public left: TreeNode|null, public right: TreeNode|null) {} } /** * {{ data.value }} * * % if (data.left != null) { * <tree-comp [data]="data.left"></tree-comp> * % } * % if (data.right != null) { * <tree-comp [data]="data.right"></tree-comp> * % } */ class TreeComponent { data: TreeNode = _buildTree(0); ngDoCheck() { events.push('check' + this.data.value); } ngOnDestroy() { events.push('destroy' + this.data.value); } static ngComponentDef = defineComponent({ type: TreeComponent, encapsulation: ViewEncapsulation.None, selectors: [['tree-comp']], factory: () => new TreeComponent(), consts: 3, vars: 1, template: (rf: RenderFlags, ctx: TreeComponent) => { if (rf & RenderFlags.Create) { text(0); container(1); container(2); } if (rf & RenderFlags.Update) { textBinding(0, bind(ctx.data.value)); containerRefreshStart(1); { if (ctx.data.left != null) { let rf0 = embeddedViewStart(0, 1, 1); if (rf0 & RenderFlags.Create) { element(0, 'tree-comp'); } if (rf0 & RenderFlags.Update) { elementProperty(0, 'data', bind(ctx.data.left)); } embeddedViewEnd(); } } containerRefreshEnd(); containerRefreshStart(2); { if (ctx.data.right != null) { let rf0 = embeddedViewStart(0, 1, 1); if (rf0 & RenderFlags.Create) { element(0, 'tree-comp'); } if (rf0 & RenderFlags.Update) { elementProperty(0, 'data', bind(ctx.data.right)); } embeddedViewEnd(); } } containerRefreshEnd(); } }, inputs: {data: 'data'} }); } (TreeComponent.ngComponentDef as ComponentDef<TreeComponent>).directiveDefs = () => [TreeComponent.ngComponentDef]; /** * {{ data.value }} * <ng-if-tree [data]="data.left" *ngIf="data.left"></ng-if-tree> * <ng-if-tree [data]="data.right" *ngIf="data.right"></ng-if-tree> */ class NgIfTree { data: TreeNode = _buildTree(0); ngOnDestroy() { events.push('destroy' + this.data.value); } static ngComponentDef = defineComponent({ type: NgIfTree, encapsulation: ViewEncapsulation.None, selectors: [['ng-if-tree']], factory: () => new NgIfTree(), consts: 3, vars: 3, template: (rf: RenderFlags, ctx: NgIfTree) => { if (rf & RenderFlags.Create) { text(0); template(1, IfTemplate, 1, 1, '', [AttributeMarker.SelectOnly, 'ngIf']); template(2, IfTemplate2, 1, 1, '', [AttributeMarker.SelectOnly, 'ngIf']); } if (rf & RenderFlags.Update) { textBinding(0, bind(ctx.data.value)); elementProperty(1, 'ngIf', bind(ctx.data.left)); elementProperty(2, 'ngIf', bind(ctx.data.right)); } }, inputs: {data: 'data'}, }); } function IfTemplate(rf: RenderFlags, left: any) { if (rf & RenderFlags.Create) { elementStart(0, 'ng-if-tree'); elementEnd(); } if (rf & RenderFlags.Update) { const parent = nextContext(); elementProperty(0, 'data', bind(parent.data.left)); } } function IfTemplate2(rf: RenderFlags, right: any) { if (rf & RenderFlags.Create) { elementStart(0, 'ng-if-tree'); elementEnd(); } if (rf & RenderFlags.Update) { const parent = nextContext(); elementProperty(0, 'data', bind(parent.data.right)); } } (NgIfTree.ngComponentDef as ComponentDef<NgIfTree>).directiveDefs = () => [NgIfTree.ngComponentDef, NgIf.ngDirectiveDef]; function _buildTree(currDepth: number): TreeNode { const children = currDepth < 2 ? _buildTree(currDepth + 1) : null; const children2 = currDepth < 2 ? _buildTree(currDepth + 1) : null; return new TreeNode(count++, currDepth, children, children2); } it('should check each component just once', () => { const comp = renderComponent(TreeComponent, {hostFeatures: [LifecycleHooksFeature]}); expect(getRenderedText(comp)).toEqual('6201534'); expect(events).toEqual(['check6', 'check2', 'check0', 'check1', 'check5', 'check3', 'check4']); events = []; tick(comp); expect(events).toEqual(['check6', 'check2', 'check0', 'check1', 'check5', 'check3', 'check4']); }); // This tests that the view tree is set up properly for recursive components it('should call onDestroys properly', () => { /** * % if (!skipContent) { * <tree-comp></tree-comp> * % } */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); if (!ctx.skipContent) { const rf0 = embeddedViewStart(0, 1, 0); if (rf0 & RenderFlags.Create) { elementStart(0, 'tree-comp'); elementEnd(); } embeddedViewEnd(); } containerRefreshEnd(); } }, 1, 0, [TreeComponent]); const fixture = new ComponentFixture(App); expect(getRenderedText(fixture.component)).toEqual('6201534'); events = []; fixture.component.skipContent = true; fixture.update(); expect(events).toEqual( ['destroy0', 'destroy1', 'destroy2', 'destroy3', 'destroy4', 'destroy5', 'destroy6']); }); it('should call onDestroys properly with ngIf', () => { /** * % if (!skipContent) { * <ng-if-tree></ng-if-tree> * % } */ const App = createComponent('app', function(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { container(0); } if (rf & RenderFlags.Update) { containerRefreshStart(0); if (!ctx.skipContent) { const rf0 = embeddedViewStart(0, 1, 0); if (rf0 & RenderFlags.Create) { elementStart(0, 'ng-if-tree'); elementEnd(); } embeddedViewEnd(); } containerRefreshEnd(); } }, 1, 0, [NgIfTree]); const fixture = new ComponentFixture(App); expect(getRenderedText(fixture.component)).toEqual('6201534'); events = []; fixture.component.skipContent = true; fixture.update(); expect(events).toEqual( ['destroy0', 'destroy1', 'destroy2', 'destroy3', 'destroy4', 'destroy5', 'destroy6']); }); it('should map inputs minified & unminified names', async() => { class TestInputsComponent { // TODO(issue/24571): remove '!'. minifiedName !: string; static ngComponentDef = defineComponent({ type: TestInputsComponent, encapsulation: ViewEncapsulation.None, selectors: [['test-inputs']], inputs: {minifiedName: 'unminifiedName'}, consts: 0, vars: 0, factory: () => new TestInputsComponent(), template: function(rf: RenderFlags, ctx: TestInputsComponent): void { // Template not needed for this test } }); } const testInputsComponentFactory = new ComponentFactory(TestInputsComponent.ngComponentDef); expect([ {propName: 'minifiedName', templateName: 'unminifiedName'} ]).toEqual(testInputsComponentFactory.inputs); }); });
packages/core/test/render3/component_spec.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017757048772182316, 0.00017304846551269293, 0.0001651797501835972, 0.00017325711087323725, 0.0000027633341233013198 ]
{ "id": 6, "code_window": [ " if (webTestNamedFiles['FIREFOX']) {\n", " // TODO(gmagolan): implement firefox support for protractor\n", " throw new Error('Firefox not yet support by protractor_web_test_suite');\n", "\n", " // const firefoxBin = path.join('external', webTestNamedFiles['FIREFOX']);\n", " // const args = [];\n", " // if (headless) {\n", " // args.push(\"--headless\")\n", " // args.push(\"--marionette\")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // const firefoxBin = require.resolve(webTestNamedFiles['FIREFOX'])\n" ], "file_path": "packages/bazel/src/protractor/protractor.conf.js", "type": "replace", "edit_start_line_idx": 127 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } export default [ 'en-IN', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 0, [0, 0], ['dd/MM/yy', 'dd-MMM-y', 'd MMMM y', 'EEEE, d MMMM, y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##,##0.###', '#,##,##0%', '¤ #,##,##0.00', '#E0'], '₹', 'Indian Rupee', {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural ];
packages/common/locales/en-IN.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017383246449753642, 0.0001718970452202484, 0.00017071010370273143, 0.00017175503307953477, 0.000001100170493373298 ]
{ "id": 7, "code_window": [ "\n", "_CONF_TMPL = \"//packages/bazel/src/protractor:protractor.conf.js\"\n", "\n", "def _protractor_web_test_impl(ctx):\n", " configuration = ctx.actions.declare_file(\n", " \"%s.conf.js\" % ctx.label.name,\n", " sibling = ctx.outputs.executable,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "def _short_path_to_manifest_path(ctx, short_path):\n", " if short_path.startswith(\"../\"):\n", " return short_path[3:]\n", " else:\n", " return ctx.workspace_name + \"/\" + short_path\n", "\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "add", "edit_start_line_idx": 17 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.9986316561698914, 0.3139537572860718, 0.00016510100977029651, 0.0037699281238019466, 0.4511088728904724 ]
{ "id": 7, "code_window": [ "\n", "_CONF_TMPL = \"//packages/bazel/src/protractor:protractor.conf.js\"\n", "\n", "def _protractor_web_test_impl(ctx):\n", " configuration = ctx.actions.declare_file(\n", " \"%s.conf.js\" % ctx.label.name,\n", " sibling = ctx.outputs.executable,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "def _short_path_to_manifest_path(ctx, short_path):\n", " if short_path.startswith(\"../\"):\n", " return short_path[3:]\n", " else:\n", " return ctx.workspace_name + \"/\" + short_path\n", "\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "add", "edit_start_line_idx": 17 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DeprecatedDatePipe} from '@angular/common'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_reflector'; import {browserDetection} from '@angular/platform-browser/testing/src/browser_util'; { describe('DeprecatedDatePipe', () => { let date: Date; const isoStringWithoutTime = '2015-01-01'; let pipe: DeprecatedDatePipe; // Check the transformation of a date into a pattern function expectDateFormatAs(date: Date | string, pattern: any, output: string): void { // disabled on chrome mobile because of the following bug affecting the intl API // https://bugs.chromium.org/p/chromium/issues/detail?id=796583 // the android 7 emulator of saucelabs uses chrome mobile 63 if (!browserDetection.isAndroid && !browserDetection.isWebkit) { expect(pipe.transform(date, pattern)).toEqual(output); } } // TODO: reactivate the disabled expectations once emulators are fixed in SauceLabs // In some old versions of Chrome in Android emulators, time formatting returns dates in the // timezone of the VM host, // instead of the device timezone. Same symptoms as // https://bugs.chromium.org/p/chromium/issues/detail?id=406382 // This happens locally and in SauceLabs, so some checks are disabled to avoid failures. // Tracking issue: https://github.com/angular/angular/issues/11187 beforeEach(() => { date = new Date(2015, 5, 15, 9, 3, 1); pipe = new DeprecatedDatePipe('en-US'); }); it('should be marked as pure', () => { expect(new PipeResolver(new JitReflector()).resolve(DeprecatedDatePipe) !.pure).toEqual(true); }); describe('supports', () => { it('should support date', () => { expect(() => pipe.transform(date)).not.toThrow(); }); it('should support int', () => { expect(() => pipe.transform(123456789)).not.toThrow(); }); it('should support numeric strings', () => { expect(() => pipe.transform('123456789')).not.toThrow(); }); it('should support decimal strings', () => { expect(() => pipe.transform('123456789.11')).not.toThrow(); }); it('should support ISO string', () => expect(() => pipe.transform('2015-06-15T21:43:11Z')).not.toThrow()); it('should return null for empty string', () => expect(pipe.transform('')).toEqual(null)); it('should return null for NaN', () => expect(pipe.transform(Number.NaN)).toEqual(null)); it('should support ISO string without time', () => { expect(() => pipe.transform(isoStringWithoutTime)).not.toThrow(); }); it('should not support other objects', () => expect(() => pipe.transform({})).toThrowError(/InvalidPipeArgument/)); }); describe('transform', () => { it('should format each component correctly', () => { const dateFixtures: any = { 'y': '2015', 'yy': '15', 'M': '6', 'MM': '06', 'MMM': 'Jun', 'MMMM': 'June', 'd': '15', 'dd': '15', 'EEE': 'Mon', 'EEEE': 'Monday' }; const isoStringWithoutTimeFixtures: any = { 'y': '2015', 'yy': '15', 'M': '1', 'MM': '01', 'MMM': 'Jan', 'MMMM': 'January', 'd': '1', 'dd': '01', 'EEE': 'Thu', 'EEEE': 'Thursday' }; if (!browserDetection.isOldChrome) { dateFixtures['h'] = '9'; dateFixtures['hh'] = '09'; dateFixtures['j'] = '9 AM'; isoStringWithoutTimeFixtures['h'] = '12'; isoStringWithoutTimeFixtures['hh'] = '12'; isoStringWithoutTimeFixtures['j'] = '12 AM'; } // IE and Edge can't format a date to minutes and seconds without hours if (!browserDetection.isEdge && !browserDetection.isIE || !browserDetection.supportsNativeIntlApi) { if (!browserDetection.isOldChrome) { dateFixtures['HH'] = '09'; isoStringWithoutTimeFixtures['HH'] = '00'; } dateFixtures['E'] = 'M'; dateFixtures['L'] = 'J'; dateFixtures['m'] = '3'; dateFixtures['s'] = '1'; dateFixtures['mm'] = '03'; dateFixtures['ss'] = '01'; isoStringWithoutTimeFixtures['m'] = '0'; isoStringWithoutTimeFixtures['s'] = '0'; isoStringWithoutTimeFixtures['mm'] = '00'; isoStringWithoutTimeFixtures['ss'] = '00'; } Object.keys(dateFixtures).forEach((pattern: string) => { expectDateFormatAs(date, pattern, dateFixtures[pattern]); }); if (!browserDetection.isOldChrome) { Object.keys(isoStringWithoutTimeFixtures).forEach((pattern: string) => { expectDateFormatAs( isoStringWithoutTime, pattern, isoStringWithoutTimeFixtures[pattern]); }); } expect(pipe.transform(date, 'Z')).toBeDefined(); }); it('should format common multi component patterns', () => { const dateFixtures: any = { 'EEE, M/d/y': 'Mon, 6/15/2015', 'EEE, M/d': 'Mon, 6/15', 'MMM d': 'Jun 15', 'dd/MM/yyyy': '15/06/2015', 'MM/dd/yyyy': '06/15/2015', 'yMEEEd': '20156Mon15', 'MEEEd': '6Mon15', 'MMMd': 'Jun15', 'yMMMMEEEEd': 'Monday, June 15, 2015' }; // IE and Edge can't format a date to minutes and seconds without hours if (!browserDetection.isEdge && !browserDetection.isIE || !browserDetection.supportsNativeIntlApi) { dateFixtures['ms'] = '31'; } if (!browserDetection.isOldChrome) { dateFixtures['jm'] = '9:03 AM'; } Object.keys(dateFixtures).forEach((pattern: string) => { expectDateFormatAs(date, pattern, dateFixtures[pattern]); }); }); it('should format with pattern aliases', () => { const dateFixtures: any = { 'MM/dd/yyyy': '06/15/2015', 'fullDate': 'Monday, June 15, 2015', 'longDate': 'June 15, 2015', 'mediumDate': 'Jun 15, 2015', 'shortDate': '6/15/2015' }; if (!browserDetection.isOldChrome) { // IE and Edge do not add a coma after the year in these 2 cases if ((browserDetection.isEdge || browserDetection.isIE) && browserDetection.supportsNativeIntlApi) { dateFixtures['medium'] = 'Jun 15, 2015 9:03:01 AM'; dateFixtures['short'] = '6/15/2015 9:03 AM'; } else { dateFixtures['medium'] = 'Jun 15, 2015, 9:03:01 AM'; dateFixtures['short'] = '6/15/2015, 9:03 AM'; } } if (!browserDetection.isOldChrome) { dateFixtures['mediumTime'] = '9:03:01 AM'; dateFixtures['shortTime'] = '9:03 AM'; } Object.keys(dateFixtures).forEach((pattern: string) => { expectDateFormatAs(date, pattern, dateFixtures[pattern]); }); }); it('should format invalid in IE ISO date', () => expect(pipe.transform('2017-01-11T09:25:14.014-0500')).toEqual('Jan 11, 2017')); it('should format invalid in Safari ISO date', () => expect(pipe.transform('2017-01-20T19:00:00+0000')).toEqual('Jan 20, 2017')); it('should remove bidi control characters', () => expect(pipe.transform(date, 'MM/dd/yyyy') !.length).toEqual(10)); }); }); }
packages/common/test/pipes/deprecated/date_pipe_spec.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017936970107257366, 0.00017569422197993845, 0.0001713330129859969, 0.00017584423767402768, 0.000002157079507014714 ]
{ "id": 7, "code_window": [ "\n", "_CONF_TMPL = \"//packages/bazel/src/protractor:protractor.conf.js\"\n", "\n", "def _protractor_web_test_impl(ctx):\n", " configuration = ctx.actions.declare_file(\n", " \"%s.conf.js\" % ctx.label.name,\n", " sibling = ctx.outputs.executable,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "def _short_path_to_manifest_path(ctx, short_path):\n", " if short_path.startswith(\"../\"):\n", " return short_path[3:]\n", " else:\n", " return ctx.workspace_name + \"/\" + short_path\n", "\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "add", "edit_start_line_idx": 17 }
<div ng-style="itemStyle"> <company-name company="offering.company" cell-width="companyNameWidth"> </company-name> <opportunity-name opportunity="offering.opportunity" cell-width="opportunityNameWidth"> </opportunity-name> <offering-name offering="offering" cell-width="offeringNameWidth"> </offering-name> <account-cell account="offering.account" cell-width="accountCellWidth"> </account-cell> <formatted-cell value="offering.basePoints" cell-width="basePointsWidth"> </formatted-cell> <formatted-cell value="offering.kickerPoints" cell-width="kickerPointsWidth"> </formatted-cell> <stage-buttons offering="offering" cell-width="stageButtonsWidth"> </stage-buttons> <formatted-cell value="offering.bundles" cell-width="bundlesWidth"> </formatted-cell> <formatted-cell value="offering.dueDate" cell-width="dueDateWidth"> </formatted-cell> <formatted-cell value="offering.endDate" cell-width="endDateWidth"> </formatted-cell> <formatted-cell value="offering.aatStatus" cell-width="aatStatusWidth"> </formatted-cell> </div>
modules/benchmarks_external/src/naive_infinite_scroll/scroll_item.html
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017672372632659972, 0.0001743197935866192, 0.00017302630294580013, 0.00017409538850188255, 0.0000012723456848107162 ]
{ "id": 7, "code_window": [ "\n", "_CONF_TMPL = \"//packages/bazel/src/protractor:protractor.conf.js\"\n", "\n", "def _protractor_web_test_impl(ctx):\n", " configuration = ctx.actions.declare_file(\n", " \"%s.conf.js\" % ctx.label.name,\n", " sibling = ctx.outputs.executable,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "def _short_path_to_manifest_path(ctx, short_path):\n", " if short_path.startswith(\"../\"):\n", " return short_path[3:]\n", " else:\n", " return ctx.workspace_name + \"/\" + short_path\n", "\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "add", "edit_start_line_idx": 17 }
/* tslint:disable component-selector */ import { Component, AfterViewInit, ViewChild, Input, ViewChildren, QueryList, OnInit } from '@angular/core'; import { CodeComponent } from './code.component'; export interface TabInfo { class: string|null; code: string; language: string|null; linenums: any; path: string; region: string; header: string|null; } /** * Renders a set of tab group of code snippets. * * The innerHTML of the `<code-tabs>` component should contain `<code-pane>` elements. * Each `<code-pane>` has the same interface as the embedded `<code-example>` component. * The optional `linenums` attribute is the default `linenums` for each code pane. */ @Component({ selector: 'code-tabs', template: ` <!-- Use content projection so that the provided HTML's code-panes can be split into tabs --> <div #content style="display: none"><ng-content></ng-content></div> <mat-card> <mat-tab-group class="code-tab-group" disableRipple> <mat-tab style="overflow-y: hidden;" *ngFor="let tab of tabs"> <ng-template mat-tab-label> <span class="{{ tab.class }}">{{ tab.header }}</span> </ng-template> <aio-code class="{{ tab.class }}" [language]="tab.language" [linenums]="tab.linenums" [path]="tab.path" [region]="tab.region" [header]="tab.header"> </aio-code> </mat-tab> </mat-tab-group> </mat-card> `, }) export class CodeTabsComponent implements OnInit, AfterViewInit { tabs: TabInfo[]; @Input('linenums') linenums: string; @ViewChild('content') content; @ViewChildren(CodeComponent) codeComponents: QueryList<CodeComponent>; ngOnInit() { this.tabs = []; const codeExamples = this.content.nativeElement.querySelectorAll('code-pane'); for (let i = 0; i < codeExamples.length; i++) { const tabContent = codeExamples[i]; this.tabs.push(this.getTabInfo(tabContent)); } } ngAfterViewInit() { this.codeComponents.toArray().forEach((codeComponent, i) => { codeComponent.code = this.tabs[i].code; }); } /** Gets the extracted TabInfo data from the provided code-pane element. */ private getTabInfo(tabContent: HTMLElement): TabInfo { return { class: tabContent.getAttribute('class'), code: tabContent.innerHTML, language: tabContent.getAttribute('language'), linenums: tabContent.getAttribute('linenums') || this.linenums, path: tabContent.getAttribute('path') || '', region: tabContent.getAttribute('region') || '', header: tabContent.getAttribute('header') }; } }
aio/src/app/custom-elements/code/code-tabs.component.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017577389371581376, 0.00017203966854140162, 0.000167801947100088, 0.0001713470701361075, 0.0000028404424483596813 ]
{ "id": 8, "code_window": [ "\n", " on_prepare_file = ctx.file.on_prepare\n", " if hasattr(ctx.attr.on_prepare, \"typescript\"):\n", " on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0]\n", "\n", " protractor_executable_path = ctx.executable.protractor.short_path\n", " if protractor_executable_path.startswith(\"..\"):\n", " protractor_executable_path = \"external\" + protractor_executable_path[2:]\n", "\n", " server_executable_path = \"\"\n", " if ctx.executable.server:\n", " server_executable_path = ctx.executable.server.short_path\n", " if server_executable_path.startswith(\"..\"):\n", " server_executable_path = \"external\" + protractor_executable_path[2:]\n", "\n", " ctx.actions.expand_template(\n", " output = configuration,\n", " template = ctx.file._conf_tmpl,\n", " substitutions = {\n", " \"TMPL_config\": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else \"\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 55 }
# Copyright 2018 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Package file which defines build_bazel_rules_typescript version in skylark check_rules_typescript_version can be used in downstream WORKSPACES to check against a minimum dependent build_bazel_rules_typescript version. """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # This file mirrored from https://raw.githubusercontent.com/bazelbuild/rules_typescript/0.20.3/package.bzl VERSION = "0.20.3" def rules_typescript_dependencies(): """ Fetch our transitive dependencies. If the user wants to get a different version of these, they can just fetch it from their WORKSPACE before calling this function, or not call this function at all. """ # TypeScript compiler runs on node.js runtime _maybe( http_archive, name = "build_bazel_rules_nodejs", urls = ["https://github.com/bazelbuild/rules_nodejs/archive/0.15.1.zip"], sha256 = "a0a91a2e0cee32e9304f1aeea9e6c1b611afba548058c5980217d44ee11e3dd7", strip_prefix = "rules_nodejs-0.15.1", ) # ts_web_test depends on the web testing rules to provision browsers. _maybe( http_archive, name = "io_bazel_rules_webtesting", urls = ["https://github.com/bazelbuild/rules_webtesting/archive/111d792b9a5b17f87b6e177e274dbbee46094791.zip"], strip_prefix = "rules_webtesting-111d792b9a5b17f87b6e177e274dbbee46094791", sha256 = "a13af63e928c34eff428d47d31bafeec4e38ee9b6940e70bf2c9cd47184c5c16", ) # ts_devserver depends on the Go rules. # See https://github.com/bazelbuild/rules_go#setup for the latest version. _maybe( http_archive, name = "io_bazel_rules_go", urls = ["https://github.com/bazelbuild/rules_go/archive/cbc1e32fba771845305f15e341fa26595d4a136d.zip"], strip_prefix = "rules_go-cbc1e32fba771845305f15e341fa26595d4a136d", sha256 = "d02b1d8d11fb67fb1e451645256e58a1542170eedd6e2ba160c8540c96f659da", ) # go_repository is defined in bazel_gazelle _maybe( http_archive, name = "bazel_gazelle", urls = ["https://github.com/bazelbuild/bazel-gazelle/archive/109bcfd6880aac2517a1a2d48987226da6337e11.zip"], strip_prefix = "bazel-gazelle-109bcfd6880aac2517a1a2d48987226da6337e11", sha256 = "8f80ce0f7a6f8a3fee1fb863c9a23e1de99d678c1cf3c6f0a128f3b883168208", ) # ts_auto_deps depends on com_github_bazelbuild_buildtools _maybe( http_archive, name = "com_github_bazelbuild_buildtools", url = "https://github.com/bazelbuild/buildtools/archive/0.12.0.zip", strip_prefix = "buildtools-0.12.0", sha256 = "ec495cbd19238c9dc488fd65ca1fee56dcb1a8d6d56ee69a49f2ebe69826c261", ) ############################################### # Repeat the dependencies of rules_nodejs here! # We can't load() from rules_nodejs yet, because we've only just fetched it. # But we also don't want to make users load and call the rules_nodejs_dependencies # function because we can do that for them, mostly hiding the transitive dependency. _maybe( http_archive, name = "bazel_skylib", url = "https://github.com/bazelbuild/bazel-skylib/archive/0.5.0.zip", strip_prefix = "bazel-skylib-0.5.0", sha256 = "ca4e3b8e4da9266c3a9101c8f4704fe2e20eb5625b2a6a7d2d7d45e3dd4efffd", ) def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs)
packages/bazel/rules_typescript_package.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0021391718182712793, 0.0003774231590796262, 0.00016163285181391984, 0.00017149117775261402, 0.0005877568037249148 ]
{ "id": 8, "code_window": [ "\n", " on_prepare_file = ctx.file.on_prepare\n", " if hasattr(ctx.attr.on_prepare, \"typescript\"):\n", " on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0]\n", "\n", " protractor_executable_path = ctx.executable.protractor.short_path\n", " if protractor_executable_path.startswith(\"..\"):\n", " protractor_executable_path = \"external\" + protractor_executable_path[2:]\n", "\n", " server_executable_path = \"\"\n", " if ctx.executable.server:\n", " server_executable_path = ctx.executable.server.short_path\n", " if server_executable_path.startswith(\"..\"):\n", " server_executable_path = \"external\" + protractor_executable_path[2:]\n", "\n", " ctx.actions.expand_template(\n", " output = configuration,\n", " template = ctx.file._conf_tmpl,\n", " substitutions = {\n", " \"TMPL_config\": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else \"\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 55 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ];
packages/common/locales/extra/en-MP.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00016749775386415422, 0.00016699766274541616, 0.00016620446695014834, 0.00016729073831811547, 5.671989811162348e-7 ]
{ "id": 8, "code_window": [ "\n", " on_prepare_file = ctx.file.on_prepare\n", " if hasattr(ctx.attr.on_prepare, \"typescript\"):\n", " on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0]\n", "\n", " protractor_executable_path = ctx.executable.protractor.short_path\n", " if protractor_executable_path.startswith(\"..\"):\n", " protractor_executable_path = \"external\" + protractor_executable_path[2:]\n", "\n", " server_executable_path = \"\"\n", " if ctx.executable.server:\n", " server_executable_path = ctx.executable.server.short_path\n", " if server_executable_path.startswith(\"..\"):\n", " server_executable_path = \"external\" + protractor_executable_path[2:]\n", "\n", " ctx.actions.expand_template(\n", " output = configuration,\n", " template = ctx.file._conf_tmpl,\n", " substitutions = {\n", " \"TMPL_config\": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else \"\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 55 }
const testPackage = require('../../helpers/test-package'); const processorFactory = require('./matchUpDirectiveDecorators'); const Dgeni = require('dgeni'); describe('matchUpDirectiveDecorators processor', () => { it('should be available on the injector', () => { const dgeni = new Dgeni([testPackage('angular-api-package')]); const injector = dgeni.configureInjector(); const processor = injector.get('matchUpDirectiveDecorators'); expect(processor.$process).toBeDefined(); expect(processor.$runAfter).toContain('ids-computed'); expect(processor.$runAfter).toContain('paths-computed'); expect(processor.$runBefore).toContain('rendering-docs'); }); it('should extract selector and exportAs from the directive decorator on directive docs', () => { const docs = [{ docType: 'directive', directiveOptions: { selector: 'a,b,c', exportAs: 'someExport' } }]; processorFactory().$process(docs); expect(docs[0].selector).toEqual('a,b,c'); expect(docs[0].exportAs).toEqual('someExport'); }); it('should ignore properties from the directive decorator on non-directive docs', () => { const docs = [{ docType: 'class', directiveOptions: { selector: 'a,b,c', exportAs: 'someExport' } }]; processorFactory().$process(docs); expect(docs[0].selector).toBeUndefined(); expect(docs[0].exportAs).toBeUndefined(); }); it('should strip whitespace and quotes off directive properties', () => { const docs = [ { docType: 'directive', directiveOptions: { selector: '"a,b,c"', exportAs: '\'someExport\'' } }, { docType: 'directive', directiveOptions: { selector: ' a,b,c ', exportAs: ' someExport ' } }, { docType: 'directive', directiveOptions: { selector: ' "a,b,c" ', exportAs: ' \'someExport\' ' } } ]; processorFactory().$process(docs); expect(docs[0].selector).toEqual('a,b,c'); expect(docs[0].exportAs).toEqual('someExport'); expect(docs[1].selector).toEqual('a,b,c'); expect(docs[1].exportAs).toEqual('someExport'); expect(docs[2].selector).toEqual('a,b,c'); expect(docs[2].exportAs).toEqual('someExport'); }); it('should extract inputs and outputs from the directive decorator', () => { const doc = { docType: 'directive', directiveOptions: { inputs: ['in1:in2', 'in3', ' in4:in5 ', ' in6 '], outputs: ['out1:out1', ' out2:out3 ', ' out4 '] }, members: [ { name: 'in1' }, { name: 'in3' }, { name: 'in4' }, { name: 'in6' }, { name: 'prop1' }, { name: 'out1' }, { name: 'out2' }, { name: 'out4' }, { name: 'prop2' }, ] }; processorFactory().$process([doc]); expect(doc.members).toEqual([ { name: 'in1', boundTo: { type: 'Input', propertyName: 'in1', bindingName: 'in2' } }, { name: 'in3', boundTo: { type: 'Input', propertyName: 'in3', bindingName: 'in3' } }, { name: 'in4', boundTo: { type: 'Input', propertyName: 'in4', bindingName: 'in5' } }, { name: 'in6', boundTo: { type: 'Input', propertyName: 'in6', bindingName: 'in6' }}, { name: 'prop1' }, { name: 'out1', boundTo: { type: 'Output', propertyName: 'out1', bindingName: 'out1' } }, { name: 'out2', boundTo: { type: 'Output', propertyName: 'out2', bindingName: 'out3' } }, { name: 'out4', boundTo: { type: 'Output', propertyName: 'out4', bindingName: 'out4' }}, { name: 'prop2' }, ]); }); it('should extract inputs and outputs from decorated properties', () => { const doc = { docType: 'directive', directiveOptions: {}, members: [ { name: 'a1', decorators: [{ name: 'Input', arguments: ['a2'] }] }, { name: 'b1', decorators: [{ name: 'Output', arguments: ['b2'] }] }, { name: 'c1', decorators: [{ name: 'Input', arguments: [] }] }, { name: 'd1', decorators: [{ name: 'Output', arguments: [] }] }, ] }; processorFactory().$process([doc]); expect(doc.members).toEqual([ { name: 'a1', decorators: [{ name: 'Input', arguments: ['a2'] }], boundTo: { type: 'Input', propertyName: 'a1', bindingName: 'a2' } }, { name: 'b1', decorators: [{ name: 'Output', arguments: ['b2'] }], boundTo: { type: 'Output', propertyName: 'b1', bindingName: 'b2' } }, { name: 'c1', decorators: [{ name: 'Input', arguments: [] }], boundTo: { type: 'Input', propertyName: 'c1', bindingName: 'c1' } }, { name: 'd1', decorators: [{ name: 'Output', arguments: [] }], boundTo: { type: 'Output', propertyName: 'd1', bindingName: 'd1' } }, ]); }); it('should merge directive inputs/outputs with decorator property inputs/outputs', () => { const doc = { docType: 'directive', directiveOptions: { inputs: ['a1:a2'], outputs: ['b1:b2'] }, members: [ { name: 'a1' }, { name: 'a3', decorators: [{ name: 'Input', arguments: ['a4'] }] }, { name: 'b1' }, { name: 'b3', decorators: [{ name: 'Output', arguments: ['b4'] }] }, ] }; processorFactory().$process([doc]); expect(doc.members).toEqual([ { name: 'a1', boundTo: { type: 'Input', propertyName: 'a1', bindingName: 'a2' } }, { name: 'a3', boundTo: { type: 'Input', propertyName: 'a3', bindingName: 'a4' }, decorators: [{ name: 'Input', arguments: ['a4'] }] }, { name: 'b1', boundTo: { type: 'Output', propertyName: 'b1', bindingName: 'b2' } }, { name: 'b3', boundTo: { type: 'Output', propertyName: 'b3', bindingName: 'b4' }, decorators: [{ name: 'Output', arguments: ['b4'] }] }, ]); }); });
aio/tools/transforms/angular-api-package/processors/matchUpDirectiveDecorators.spec.js
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0001715838152449578, 0.0001687031181063503, 0.0001668769691605121, 0.00016831843822728842, 0.0000013468225006363355 ]
{ "id": 8, "code_window": [ "\n", " on_prepare_file = ctx.file.on_prepare\n", " if hasattr(ctx.attr.on_prepare, \"typescript\"):\n", " on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0]\n", "\n", " protractor_executable_path = ctx.executable.protractor.short_path\n", " if protractor_executable_path.startswith(\"..\"):\n", " protractor_executable_path = \"external\" + protractor_executable_path[2:]\n", "\n", " server_executable_path = \"\"\n", " if ctx.executable.server:\n", " server_executable_path = ctx.executable.server.short_path\n", " if server_executable_path.startswith(\"..\"):\n", " server_executable_path = \"external\" + protractor_executable_path[2:]\n", "\n", " ctx.actions.expand_template(\n", " output = configuration,\n", " template = ctx.file._conf_tmpl,\n", " substitutions = {\n", " \"TMPL_config\": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else \"\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 55 }
{ "extends": "../tsconfig-build.json", "compilerOptions": { "baseUrl": ".", "rootDir": ".", "paths": { "@angular/core": ["../../dist/packages/core"], "@angular/core/testing": ["../../dist/packages/core/testing"], "@angular/common": ["../../dist/packages/common"], "@angular/common/testing": ["../../dist/packages/common/testing"], "@angular/compiler": ["../../dist/packages/compiler"], "@angular/compiler/testing": ["../../dist/packages/compiler/testing"], "@angular/platform-browser": ["../../dist/packages/platform-browser"] }, "outDir": "../../dist/packages/forms" }, "files": [ "public_api.ts", "../../node_modules/zone.js/dist/zone.js.d.ts" ], "angularCompilerOptions": { "annotateForClosureCompiler": true, "strictMetadataEmit": false, "skipTemplateCodegen": true, "flatModuleOutFile": "forms.js", "flatModuleId": "@angular/forms" } }
packages/forms/tsconfig-build.json
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00023512709594797343, 0.00018395385995972902, 0.0001659262488828972, 0.00016738104750402272, 0.00002956261596409604 ]
{ "id": 9, "code_window": [ " template = ctx.file._conf_tmpl,\n", " substitutions = {\n", " \"TMPL_config\": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else \"\",\n", " \"TMPL_on_prepare\": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else \"\",\n", " \"TMPL_workspace\": ctx.workspace_name,\n", " \"TMPL_server\": server_executable_path,\n", " \"TMPL_specs\": \"\\n\".join([\" '%s',\" % e for e in specs]),\n", " },\n", " )\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"TMPL_server\": ctx.executable.server.short_path if ctx.executable.server else \"\",\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 72 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.9973233342170715, 0.056257836520671844, 0.00016324040188919753, 0.00019081690697930753, 0.2280658483505249 ]
{ "id": 9, "code_window": [ " template = ctx.file._conf_tmpl,\n", " substitutions = {\n", " \"TMPL_config\": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else \"\",\n", " \"TMPL_on_prepare\": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else \"\",\n", " \"TMPL_workspace\": ctx.workspace_name,\n", " \"TMPL_server\": server_executable_path,\n", " \"TMPL_specs\": \"\\n\".join([\" '%s',\" % e for e in specs]),\n", " },\n", " )\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"TMPL_server\": ctx.executable.server.short_path if ctx.executable.server else \"\",\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 72 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u, ['minuit', 'midi', 'du matin', 'de l’après-midi', 'du soir', 'du matin'] ], [ ['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u, ['minuit', 'midi', 'matin', 'après-midi', 'soir', 'nuit'] ], [ '00:00', '12:00', ['04:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'], ['00:00', '04:00'] ] ];
packages/common/locales/extra/fr-MR.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0001767690700944513, 0.0001750871306285262, 0.00017343364015687257, 0.00017505869618616998, 0.0000013618321190733695 ]
{ "id": 9, "code_window": [ " template = ctx.file._conf_tmpl,\n", " substitutions = {\n", " \"TMPL_config\": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else \"\",\n", " \"TMPL_on_prepare\": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else \"\",\n", " \"TMPL_workspace\": ctx.workspace_name,\n", " \"TMPL_server\": server_executable_path,\n", " \"TMPL_specs\": \"\\n\".join([\" '%s',\" % e for e in specs]),\n", " },\n", " )\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"TMPL_server\": ctx.executable.server.short_path if ctx.executable.server else \"\",\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 72 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ml from '../../ml_parser/ast'; import {XmlParser} from '../../ml_parser/xml_parser'; import {digest} from '../digest'; import * as i18n from '../i18n_ast'; import {I18nError} from '../parse_util'; import {Serializer} from './serializer'; import * as xml from './xml_helper'; const _VERSION = '1.2'; const _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2'; // TODO(vicb): make this a param (s/_/-/) const _DEFAULT_SOURCE_LANG = 'en'; const _PLACEHOLDER_TAG = 'x'; const _MARKER_TAG = 'mrk'; const _FILE_TAG = 'file'; const _SOURCE_TAG = 'source'; const _SEGMENT_SOURCE_TAG = 'seg-source'; const _TARGET_TAG = 'target'; const _UNIT_TAG = 'trans-unit'; const _CONTEXT_GROUP_TAG = 'context-group'; const _CONTEXT_TAG = 'context'; // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html // http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html export class Xliff extends Serializer { write(messages: i18n.Message[], locale: string|null): string { const visitor = new _WriteVisitor(); const transUnits: xml.Node[] = []; messages.forEach(message => { let contextTags: xml.Node[] = []; message.sources.forEach((source: i18n.MessageSpan) => { let contextGroupTag = new xml.Tag(_CONTEXT_GROUP_TAG, {purpose: 'location'}); contextGroupTag.children.push( new xml.CR(10), new xml.Tag( _CONTEXT_TAG, {'context-type': 'sourcefile'}, [new xml.Text(source.filePath)]), new xml.CR(10), new xml.Tag( _CONTEXT_TAG, {'context-type': 'linenumber'}, [new xml.Text(`${source.startLine}`)]), new xml.CR(8)); contextTags.push(new xml.CR(8), contextGroupTag); }); const transUnit = new xml.Tag(_UNIT_TAG, {id: message.id, datatype: 'html'}); transUnit.children.push( new xml.CR(8), new xml.Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)), ...contextTags); if (message.description) { transUnit.children.push( new xml.CR(8), new xml.Tag( 'note', {priority: '1', from: 'description'}, [new xml.Text(message.description)])); } if (message.meaning) { transUnit.children.push( new xml.CR(8), new xml.Tag('note', {priority: '1', from: 'meaning'}, [new xml.Text(message.meaning)])); } transUnit.children.push(new xml.CR(6)); transUnits.push(new xml.CR(6), transUnit); }); const body = new xml.Tag('body', {}, [...transUnits, new xml.CR(4)]); const file = new xml.Tag( 'file', { 'source-language': locale || _DEFAULT_SOURCE_LANG, datatype: 'plaintext', original: 'ng2.template', }, [new xml.CR(4), body, new xml.CR(2)]); const xliff = new xml.Tag( 'xliff', {version: _VERSION, xmlns: _XMLNS}, [new xml.CR(2), file, new xml.CR()]); return xml.serialize([ new xml.Declaration({version: '1.0', encoding: 'UTF-8'}), new xml.CR(), xliff, new xml.CR() ]); } load(content: string, url: string): {locale: string, i18nNodesByMsgId: {[msgId: string]: i18n.Node[]}} { // xliff to xml nodes const xliffParser = new XliffParser(); const {locale, msgIdToHtml, errors} = xliffParser.parse(content, url); // xml nodes to i18n nodes const i18nNodesByMsgId: {[msgId: string]: i18n.Node[]} = {}; const converter = new XmlToI18n(); Object.keys(msgIdToHtml).forEach(msgId => { const {i18nNodes, errors: e} = converter.convert(msgIdToHtml[msgId], url); errors.push(...e); i18nNodesByMsgId[msgId] = i18nNodes; }); if (errors.length) { throw new Error(`xliff parse errors:\n${errors.join('\n')}`); } return {locale: locale !, i18nNodesByMsgId}; } digest(message: i18n.Message): string { return digest(message); } } class _WriteVisitor implements i18n.Visitor { visitText(text: i18n.Text, context?: any): xml.Node[] { return [new xml.Text(text.value)]; } visitContainer(container: i18n.Container, context?: any): xml.Node[] { const nodes: xml.Node[] = []; container.children.forEach((node: i18n.Node) => nodes.push(...node.visit(this))); return nodes; } visitIcu(icu: i18n.Icu, context?: any): xml.Node[] { const nodes = [new xml.Text(`{${icu.expressionPlaceholder}, ${icu.type}, `)]; Object.keys(icu.cases).forEach((c: string) => { nodes.push(new xml.Text(`${c} {`), ...icu.cases[c].visit(this), new xml.Text(`} `)); }); nodes.push(new xml.Text(`}`)); return nodes; } visitTagPlaceholder(ph: i18n.TagPlaceholder, context?: any): xml.Node[] { const ctype = getCtypeForTag(ph.tag); if (ph.isVoid) { // void tags have no children nor closing tags return [new xml.Tag( _PLACEHOLDER_TAG, {id: ph.startName, ctype, 'equiv-text': `<${ph.tag}/>`})]; } const startTagPh = new xml.Tag(_PLACEHOLDER_TAG, {id: ph.startName, ctype, 'equiv-text': `<${ph.tag}>`}); const closeTagPh = new xml.Tag(_PLACEHOLDER_TAG, {id: ph.closeName, ctype, 'equiv-text': `</${ph.tag}>`}); return [startTagPh, ...this.serialize(ph.children), closeTagPh]; } visitPlaceholder(ph: i18n.Placeholder, context?: any): xml.Node[] { return [new xml.Tag(_PLACEHOLDER_TAG, {id: ph.name, 'equiv-text': `{{${ph.value}}}`})]; } visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): xml.Node[] { const equivText = `{${ph.value.expression}, ${ph.value.type}, ${Object.keys(ph.value.cases).map((value: string) => value + ' {...}').join(' ')}}`; return [new xml.Tag(_PLACEHOLDER_TAG, {id: ph.name, 'equiv-text': equivText})]; } serialize(nodes: i18n.Node[]): xml.Node[] { return [].concat(...nodes.map(node => node.visit(this))); } } // TODO(vicb): add error management (structure) // Extract messages as xml nodes from the xliff file class XliffParser implements ml.Visitor { // TODO(issue/24571): remove '!'. private _unitMlString !: string | null; // TODO(issue/24571): remove '!'. private _errors !: I18nError[]; // TODO(issue/24571): remove '!'. private _msgIdToHtml !: {[msgId: string]: string}; private _locale: string|null = null; parse(xliff: string, url: string) { this._unitMlString = null; this._msgIdToHtml = {}; const xml = new XmlParser().parse(xliff, url, false); this._errors = xml.errors; ml.visitAll(this, xml.rootNodes, null); return { msgIdToHtml: this._msgIdToHtml, errors: this._errors, locale: this._locale, }; } visitElement(element: ml.Element, context: any): any { switch (element.name) { case _UNIT_TAG: this._unitMlString = null !; const idAttr = element.attrs.find((attr) => attr.name === 'id'); if (!idAttr) { this._addError(element, `<${_UNIT_TAG}> misses the "id" attribute`); } else { const id = idAttr.value; if (this._msgIdToHtml.hasOwnProperty(id)) { this._addError(element, `Duplicated translations for msg ${id}`); } else { ml.visitAll(this, element.children, null); if (typeof this._unitMlString === 'string') { this._msgIdToHtml[id] = this._unitMlString; } else { this._addError(element, `Message ${id} misses a translation`); } } } break; // ignore those tags case _SOURCE_TAG: case _SEGMENT_SOURCE_TAG: break; case _TARGET_TAG: const innerTextStart = element.startSourceSpan !.end.offset; const innerTextEnd = element.endSourceSpan !.start.offset; const content = element.startSourceSpan !.start.file.content; const innerText = content.slice(innerTextStart, innerTextEnd); this._unitMlString = innerText; break; case _FILE_TAG: const localeAttr = element.attrs.find((attr) => attr.name === 'target-language'); if (localeAttr) { this._locale = localeAttr.value; } ml.visitAll(this, element.children, null); break; default: // TODO(vicb): assert file structure, xliff version // For now only recurse on unhandled nodes ml.visitAll(this, element.children, null); } } visitAttribute(attribute: ml.Attribute, context: any): any {} visitText(text: ml.Text, context: any): any {} visitComment(comment: ml.Comment, context: any): any {} visitExpansion(expansion: ml.Expansion, context: any): any {} visitExpansionCase(expansionCase: ml.ExpansionCase, context: any): any {} private _addError(node: ml.Node, message: string): void { this._errors.push(new I18nError(node.sourceSpan !, message)); } } // Convert ml nodes (xliff syntax) to i18n nodes class XmlToI18n implements ml.Visitor { // TODO(issue/24571): remove '!'. private _errors !: I18nError[]; convert(message: string, url: string) { const xmlIcu = new XmlParser().parse(message, url, true); this._errors = xmlIcu.errors; const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ? [] : [].concat(...ml.visitAll(this, xmlIcu.rootNodes)); return { i18nNodes: i18nNodes, errors: this._errors, }; } visitText(text: ml.Text, context: any) { return new i18n.Text(text.value, text.sourceSpan !); } visitElement(el: ml.Element, context: any): i18n.Placeholder|ml.Node[]|null { if (el.name === _PLACEHOLDER_TAG) { const nameAttr = el.attrs.find((attr) => attr.name === 'id'); if (nameAttr) { return new i18n.Placeholder('', nameAttr.value, el.sourceSpan !); } this._addError(el, `<${_PLACEHOLDER_TAG}> misses the "id" attribute`); return null; } if (el.name === _MARKER_TAG) { return [].concat(...ml.visitAll(this, el.children)); } this._addError(el, `Unexpected tag`); return null; } visitExpansion(icu: ml.Expansion, context: any) { const caseMap: {[value: string]: i18n.Node} = {}; ml.visitAll(this, icu.cases).forEach((c: any) => { caseMap[c.value] = new i18n.Container(c.nodes, icu.sourceSpan); }); return new i18n.Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan); } visitExpansionCase(icuCase: ml.ExpansionCase, context: any): any { return { value: icuCase.value, nodes: ml.visitAll(this, icuCase.expression), }; } visitComment(comment: ml.Comment, context: any) {} visitAttribute(attribute: ml.Attribute, context: any) {} private _addError(node: ml.Node, message: string): void { this._errors.push(new I18nError(node.sourceSpan !, message)); } } function getCtypeForTag(tag: string): string { switch (tag.toLowerCase()) { case 'br': return 'lb'; case 'img': return 'image'; default: return `x-${tag}`; } }
packages/compiler/src/i18n/serializers/xliff.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.000687653198838234, 0.0001896238245535642, 0.0001604654680704698, 0.000173551743500866, 0.00008633394463686273 ]
{ "id": 9, "code_window": [ " template = ctx.file._conf_tmpl,\n", " substitutions = {\n", " \"TMPL_config\": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else \"\",\n", " \"TMPL_on_prepare\": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else \"\",\n", " \"TMPL_workspace\": ctx.workspace_name,\n", " \"TMPL_server\": server_executable_path,\n", " \"TMPL_specs\": \"\\n\".join([\" '%s',\" % e for e in specs]),\n", " },\n", " )\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"TMPL_server\": ctx.executable.server.short_path if ctx.executable.server else \"\",\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 72 }
a.to-toc { margin: 30px 0; } button { font-size: 100%; margin: 0 2px; } div[clickable] {cursor: pointer; max-width: 200px; margin: 16px 0} #noTrackByCnt, #withTrackByCnt {color: darkred; max-width: 450px; margin: 4px;} img {height: 100px;} .box {border: 1px solid black; padding: 6px; max-width: 450px;} .child-div {margin-left: 1em; font-weight: normal} .context {margin-left: 1em;} .hidden {display: none} .parent-div {margin-top: 1em; font-weight: bold} .special {font-weight:bold; font-size: x-large} .bad {color: red;} .saveable {color: limegreen;} .curly, .modified {font-family: "Brush Script MT"} .toe {margin-left: 1em; font-style: italic;} little-hero {color:blue; font-size: smaller; background-color: Turquoise } .to-toc {margin-top: 10px; display: block}
aio/content/examples/template-syntax/src/app/app.component.css
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017639344150666147, 0.00017601740546524525, 0.00017564136942382902, 0.00017601740546524525, 3.760360414162278e-7 ]
{ "id": 10, "code_window": [ "if [ -e \"$RUNFILE_MANIFEST_FILE\" ]; then\n", " while read line; do\n", " declare -a PARTS=($line)\n", " if [ \"${{PARTS[0]}}\" == \"angular/{TMPL_protractor}\" ]; then\n", " readonly PROTRACTOR=${{PARTS[1]}}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " if [ \"${{PARTS[0]}}\" == \"{TMPL_protractor}\" ]; then\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 86 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license """Package file which defines dependencies of Angular rules in skylark """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load(":rules_nodejs_package.bzl", "rules_nodejs_dependencies") load(":rules_typescript_package.bzl", "rules_typescript_dependencies") def rules_angular_dependencies(): """ Fetch our transitive dependencies. If the user wants to get a different version of these, they can just fetch it from their WORKSPACE before calling this function, or not call this function at all. """ # # Download Bazel toolchain dependencies as needed by build actions # _maybe( http_archive, name = "build_bazel_rules_typescript", url = "https://github.com/bazelbuild/rules_typescript/archive/0.20.3.zip", strip_prefix = "rules_typescript-0.20.3", sha256 = "2a03b23c30c5109ab0863cfa60acce73ceb56337d41efc2dd67f8455a1c1d5f3", ) # Needed for Remote Execution _maybe( http_archive, name = "bazel_toolchains", sha256 = "c3b08805602cd1d2b67ebe96407c1e8c6ed3d4ce55236ae2efe2f1948f38168d", strip_prefix = "bazel-toolchains-5124557861ebf4c0b67f98180bff1f8551e0b421", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/archive/5124557861ebf4c0b67f98180bff1f8551e0b421.tar.gz", "https://github.com/bazelbuild/bazel-toolchains/archive/5124557861ebf4c0b67f98180bff1f8551e0b421.tar.gz", ], ) rules_typescript_dependencies() rules_nodejs_dependencies() def rules_angular_dev_dependencies(): """ Fetch dependencies needed for local development, but not needed by users. These are in this file to keep version information in one place, and make the WORKSPACE shorter. """ # We have a source dependency on the Devkit repository, because it's built with # Bazel. # This allows us to edit sources and have the effect appear immediately without # re-packaging or "npm link"ing. # Even better, things like aspects will visit the entire graph including # ts_library rules in the devkit repository. http_archive( name = "angular_cli", sha256 = "8cf320ea58c321e103f39087376feea502f20eaf79c61a4fdb05c7286c8684fd", strip_prefix = "angular-cli-6.1.0-rc.0", url = "https://github.com/angular/angular-cli/archive/v6.1.0-rc.0.zip", ) http_archive( name = "org_brotli", sha256 = "774b893a0700b0692a76e2e5b7e7610dbbe330ffbe3fe864b4b52ca718061d5a", strip_prefix = "brotli-1.0.5", url = "https://github.com/google/brotli/archive/v1.0.5.zip", ) # Fetching the Bazel source code allows us to compile the Skylark linter http_archive( name = "io_bazel", sha256 = "978f7e0440dd82182563877e2e0b7c013b26b3368888b57837e9a0ae206fd396", strip_prefix = "bazel-0.18.0", url = "https://github.com/bazelbuild/bazel/archive/0.18.0.zip", ) # This commit matches the version of buildifier in angular/ngcontainer # If you change this, also check if it matches the version in the angular/ngcontainer # version in /.circleci/config.yml BAZEL_BUILDTOOLS_VERSION = "49a6c199e3fbf5d94534b2771868677d3f9c6de9" http_archive( name = "com_github_bazelbuild_buildtools", sha256 = "edf39af5fc257521e4af4c40829fffe8fba6d0ebff9f4dd69a6f8f1223ae047b", strip_prefix = "buildtools-%s" % BAZEL_BUILDTOOLS_VERSION, url = "https://github.com/bazelbuild/buildtools/archive/%s.zip" % BAZEL_BUILDTOOLS_VERSION, ) ############################################# # Dependencies for generating documentation # ############################################# http_archive( name = "io_bazel_rules_sass", sha256 = "dbe9fb97d5a7833b2a733eebc78c9c1e3880f676ac8af16e58ccf2139cbcad03", strip_prefix = "rules_sass-1.11.0", url = "https://github.com/bazelbuild/rules_sass/archive/1.11.0.zip", ) http_archive( name = "io_bazel_skydoc", sha256 = "7bfb5545f59792a2745f2523b9eef363f9c3e7274791c030885e7069f8116016", strip_prefix = "skydoc-fe2e9f888d28e567fef62ec9d4a93c425526d701", # TODO: switch to upstream when https://github.com/bazelbuild/skydoc/pull/103 is merged url = "https://github.com/alexeagle/skydoc/archive/fe2e9f888d28e567fef62ec9d4a93c425526d701.zip", ) def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs)
packages/bazel/package.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0006396914832293987, 0.00024713086895644665, 0.00016684278671164066, 0.00017477836809121072, 0.00015398005780298263 ]
{ "id": 10, "code_window": [ "if [ -e \"$RUNFILE_MANIFEST_FILE\" ]; then\n", " while read line; do\n", " declare -a PARTS=($line)\n", " if [ \"${{PARTS[0]}}\" == \"angular/{TMPL_protractor}\" ]; then\n", " readonly PROTRACTOR=${{PARTS[1]}}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " if [ \"${{PARTS[0]}}\" == \"{TMPL_protractor}\" ]; then\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 86 }
h1 { font-weight: normal; }
aio/content/examples/component-styles/src/app/hero-app.component.css
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017377414042130113, 0.00017377414042130113, 0.00017377414042130113, 0.00017377414042130113, 0 ]
{ "id": 10, "code_window": [ "if [ -e \"$RUNFILE_MANIFEST_FILE\" ]; then\n", " while read line; do\n", " declare -a PARTS=($line)\n", " if [ \"${{PARTS[0]}}\" == \"angular/{TMPL_protractor}\" ]; then\n", " readonly PROTRACTOR=${{PARTS[1]}}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " if [ \"${{PARTS[0]}}\" == \"{TMPL_protractor}\" ]; then\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 86 }
#!/bin/bash # Wait for Connect to be ready before exiting # Time out if we wait for more than 2 minutes, so that we can print logs. let "counter=0" while [ ! -f $BROWSER_PROVIDER_READY_FILE ]; do let "counter++" if [ $counter -gt 240 ]; then echo "Timed out after 2 minutes waiting for browser provider ready file" # We must manually print logs here because travis will not run # after_script commands if the failure occurs before the script # phase. ./scripts/ci/print-logs.sh exit 5 fi sleep .5 done
scripts/browserstack/waitfor_tunnel.sh
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0007569120498374104, 0.00046389258932322264, 0.0001708731142571196, 0.00046389258932322264, 0.0002930194605141878 ]
{ "id": 10, "code_window": [ "if [ -e \"$RUNFILE_MANIFEST_FILE\" ]; then\n", " while read line; do\n", " declare -a PARTS=($line)\n", " if [ \"${{PARTS[0]}}\" == \"angular/{TMPL_protractor}\" ]; then\n", " readonly PROTRACTOR=${{PARTS[1]}}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " if [ \"${{PARTS[0]}}\" == \"{TMPL_protractor}\" ]; then\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 86 }
#!/usr/bin/env bash set -u -e -o pipefail ( cd `dirname $0` ./build.sh gulp serve-examples & trap "kill $!" EXIT ( cd ../../ NODE_PATH=${NODE_PATH:-}:dist/all $(npm bin)/protractor protractor-examples-e2e.conf.js --bundles=true ) )
packages/examples/test.sh
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017057113291230053, 0.00016959948698058724, 0.00016862782649695873, 0.00016959948698058724, 9.716532076708972e-7 ]
{ "id": 11, "code_window": [ " readonly PROTRACTOR=${{PARTS[1]}}\n", " elif [ \"${{PARTS[0]}}\" == \"angular/{TMPL_conf}\" ]; then\n", " readonly CONF=${{PARTS[1]}}\n", " fi\n", " done < $RUNFILE_MANIFEST_FILE\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " elif [ \"${{PARTS[0]}}\" == \"{TMPL_conf}\" ]; then\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 88 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.9975002408027649, 0.03023659437894821, 0.00016530643915757537, 0.00017138825205620378, 0.16400165855884552 ]
{ "id": 11, "code_window": [ " readonly PROTRACTOR=${{PARTS[1]}}\n", " elif [ \"${{PARTS[0]}}\" == \"angular/{TMPL_conf}\" ]; then\n", " readonly CONF=${{PARTS[1]}}\n", " fi\n", " done < $RUNFILE_MANIFEST_FILE\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " elif [ \"${{PARTS[0]}}\" == \"{TMPL_conf}\" ]; then\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 88 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // #docregion enableProdMode import {NgModule, enableProdMode} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {MyComponent} from './my_component'; enableProdMode(); @NgModule({imports: [BrowserModule], bootstrap: [MyComponent]}) class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule); // #enddocregion
packages/examples/core/ts/prod_mode/prod_mode_example.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017345183005090803, 0.00017194350948557258, 0.00017062351980712265, 0.00017175519315060228, 0.000001162306148216885 ]
{ "id": 11, "code_window": [ " readonly PROTRACTOR=${{PARTS[1]}}\n", " elif [ \"${{PARTS[0]}}\" == \"angular/{TMPL_conf}\" ]; then\n", " readonly CONF=${{PARTS[1]}}\n", " fi\n", " done < $RUNFILE_MANIFEST_FILE\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " elif [ \"${{PARTS[0]}}\" == \"{TMPL_conf}\" ]; then\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 88 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {isPlatformBrowser} from '@angular/common'; import {APP_INITIALIZER, CUSTOM_ELEMENTS_SCHEMA, Compiler, Component, Directive, ErrorHandler, Inject, Input, LOCALE_ID, NgModule, OnDestroy, PLATFORM_ID, PLATFORM_INITIALIZER, Pipe, Provider, StaticProvider, Type, VERSION, createPlatformFactory} from '@angular/core'; import {ApplicationRef, destroyPlatform} from '@angular/core/src/application_ref'; import {Console} from '@angular/core/src/console'; import {ComponentRef} from '@angular/core/src/linker/component_factory'; import {Testability, TestabilityRegistry} from '@angular/core/src/testability/testability'; import {AsyncTestCompleter, Log, afterEach, beforeEach, beforeEachProviders, describe, fit, inject, it} from '@angular/core/testing/src/testing_internal'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens'; import {expect} from '@angular/platform-browser/testing/src/matchers'; @Component({selector: 'non-existent', template: ''}) class NonExistentComp { } @Component({selector: 'hello-app', template: '{{greeting}} world!'}) class HelloRootCmp { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'hello-app', template: 'before: <ng-content></ng-content> after: done'}) class HelloRootCmpContent { constructor() {} } @Component({selector: 'hello-app-2', template: '{{greeting}} world, again!'}) class HelloRootCmp2 { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'hello-app', template: ''}) class HelloRootCmp3 { appBinding: any /** TODO #9100 */; constructor(@Inject('appBinding') appBinding: any /** TODO #9100 */) { this.appBinding = appBinding; } } @Component({selector: 'hello-app', template: ''}) class HelloRootCmp4 { appRef: any /** TODO #9100 */; constructor(@Inject(ApplicationRef) appRef: ApplicationRef) { this.appRef = appRef; } } @Component({selector: 'hello-app'}) class HelloRootMissingTemplate { } @Directive({selector: 'hello-app'}) class HelloRootDirectiveIsNotCmp { } @Component({selector: 'hello-app', template: ''}) class HelloOnDestroyTickCmp implements OnDestroy { appRef: ApplicationRef; constructor(@Inject(ApplicationRef) appRef: ApplicationRef) { this.appRef = appRef; } ngOnDestroy(): void { this.appRef.tick(); } } @Component({selector: 'hello-app', templateUrl: './sometemplate.html'}) class HelloUrlCmp { greeting = 'hello'; } @Directive({selector: '[someDir]', host: {'[title]': 'someDir'}}) class SomeDirective { // TODO(issue/24571): remove '!'. @Input() someDir !: string; } @Pipe({name: 'somePipe'}) class SomePipe { transform(value: string): any { return `transformed ${value}`; } } @Component({selector: 'hello-app', template: `<div [someDir]="'someValue' | somePipe"></div>`}) class HelloCmpUsingPlatformDirectiveAndPipe { show: boolean = false; } @Component({selector: 'hello-app', template: '<some-el [someProp]="true">hello world!</some-el>'}) class HelloCmpUsingCustomElement { } class MockConsole { res: any[][] = []; error(...s: any[]): void { this.res.push(s); } } class DummyConsole implements Console { public warnings: string[] = []; log(message: string) {} warn(message: string) { this.warnings.push(message); } } class TestModule {} function bootstrap( cmpType: any, providers: Provider[] = [], platformProviders: StaticProvider[] = [], imports: Type<any>[] = []): Promise<any> { @NgModule({ imports: [BrowserModule, ...imports], declarations: [cmpType], bootstrap: [cmpType], providers: providers, schemas: [CUSTOM_ELEMENTS_SCHEMA] }) class TestModule { } return platformBrowserDynamic(platformProviders).bootstrapModule(TestModule); } { let el: any /** TODO #9100 */, el2: any /** TODO #9100 */, testProviders: Provider[], lightDom: any /** TODO #9100 */; describe('bootstrap factory method', () => { if (isNode) return; let compilerConsole: DummyConsole; beforeEachProviders(() => { return [Log]; }); beforeEach(inject([DOCUMENT], (doc: any) => { destroyPlatform(); compilerConsole = new DummyConsole(); testProviders = [{provide: Console, useValue: compilerConsole}]; const oldRoots = getDOM().querySelectorAll(doc, 'hello-app,hello-app-2,light-dom-el'); for (let i = 0; i < oldRoots.length; i++) { getDOM().remove(oldRoots[i]); } el = getDOM().createElement('hello-app', doc); el2 = getDOM().createElement('hello-app-2', doc); lightDom = getDOM().createElement('light-dom-el', doc); getDOM().appendChild(doc.body, el); getDOM().appendChild(doc.body, el2); getDOM().appendChild(el, lightDom); getDOM().setText(lightDom, 'loading'); })); afterEach(destroyPlatform); it('should throw if bootstrapped Directive is not a Component', inject([AsyncTestCompleter], (done: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; expect( () => bootstrap( HelloRootDirectiveIsNotCmp, [{provide: ErrorHandler, useValue: errorHandler}])) .toThrowError(`HelloRootDirectiveIsNotCmp cannot be used as an entry component.`); done.done(); })); it('should throw if no element is found', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; bootstrap(NonExistentComp, [ {provide: ErrorHandler, useValue: errorHandler} ]).then(null, (reason) => { expect(reason.message) .toContain('The selector "non-existent" did not match any elements'); async.done(); return null; }); })); it('should throw if no provider', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; class IDontExist {} @Component({selector: 'cmp', template: 'Cmp'}) class CustomCmp { constructor(iDontExist: IDontExist) {} } @Component({ selector: 'hello-app', template: '<cmp></cmp>', }) class RootCmp { } @NgModule({declarations: [CustomCmp], exports: [CustomCmp]}) class CustomModule { } bootstrap(RootCmp, [{provide: ErrorHandler, useValue: errorHandler}], [], [ CustomModule ]).then(null, (e: Error) => { expect(e.message).toContain( 'StaticInjectorError(TestModule)[CustomCmp -> IDontExist]: \n' + ' StaticInjectorError(Platform: core)[CustomCmp -> IDontExist]: \n' + ' NullInjectorError: No provider for IDontExist!'); async.done(); return null; }); })); if (getDOM().supportsDOMEvents()) { it('should forward the error to promise when bootstrap fails', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; const refPromise = bootstrap(NonExistentComp, [{provide: ErrorHandler, useValue: errorHandler}]); refPromise.then(null, (reason: any) => { expect(reason.message) .toContain('The selector "non-existent" did not match any elements'); async.done(); }); })); it('should invoke the default exception handler when bootstrap fails', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; const refPromise = bootstrap(NonExistentComp, [{provide: ErrorHandler, useValue: errorHandler}]); refPromise.then(null, (reason) => { expect(logger.res[0].join('#')) .toContain('ERROR#Error: The selector "non-existent" did not match any elements'); async.done(); return null; }); })); } it('should create an injector promise', () => { const refPromise = bootstrap(HelloRootCmp, testProviders); expect(refPromise).toEqual(jasmine.any(Promise)); }); it('should set platform name to browser', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap(HelloRootCmp, testProviders); refPromise.then((ref) => { expect(isPlatformBrowser(ref.injector.get(PLATFORM_ID))).toBe(true); async.done(); }); })); it('should display hello world', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap(HelloRootCmp, testProviders); refPromise.then((ref) => { expect(el).toHaveText('hello world!'); expect(el.getAttribute('ng-version')).toEqual(VERSION.full); async.done(); }); })); it('should throw a descriptive error if BrowserModule is installed again via a lazily loaded module', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @NgModule({imports: [BrowserModule]}) class AsyncModule { } bootstrap(HelloRootCmp, testProviders) .then((ref: ComponentRef<HelloRootCmp>) => { const compiler: Compiler = ref.injector.get(Compiler); return compiler.compileModuleAsync(AsyncModule).then(factory => { expect(() => factory.create(ref.injector)) .toThrowError( `BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.`); }); }) .then(() => async.done(), err => async.fail(err)); })); it('should support multiple calls to bootstrap', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise1 = bootstrap(HelloRootCmp, testProviders); const refPromise2 = bootstrap(HelloRootCmp2, testProviders); Promise.all([refPromise1, refPromise2]).then((refs) => { expect(el).toHaveText('hello world!'); expect(el2).toHaveText('hello world, again!'); async.done(); }); })); it('should not crash if change detection is invoked when the root component is disposed', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloOnDestroyTickCmp, testProviders).then((ref) => { expect(() => ref.destroy()).not.toThrow(); async.done(); }); })); it('should unregister change detectors when components are disposed', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloRootCmp, testProviders).then((ref) => { const appRef = ref.injector.get(ApplicationRef); ref.destroy(); expect(() => appRef.tick()).not.toThrow(); async.done(); }); })); it('should make the provided bindings available to the application component', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap( HelloRootCmp3, [testProviders, {provide: 'appBinding', useValue: 'BoundValue'}]); refPromise.then((ref) => { expect(ref.injector.get('appBinding')).toEqual('BoundValue'); async.done(); }); })); it('should not override locale provided during bootstrap', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap(HelloRootCmp, [testProviders], [{provide: LOCALE_ID, useValue: 'fr-FR'}]); refPromise.then(ref => { expect(ref.injector.get(LOCALE_ID)).toEqual('fr-FR'); async.done(); }); })); it('should avoid cyclic dependencies when root component requires Lifecycle through DI', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap(HelloRootCmp4, testProviders); refPromise.then((ref) => { const appRef = ref.injector.get(ApplicationRef); expect(appRef).toBeDefined(); async.done(); }); })); it('should run platform initializers', inject([Log, AsyncTestCompleter], (log: Log, async: AsyncTestCompleter) => { const p = createPlatformFactory(platformBrowserDynamic, 'someName', [ {provide: PLATFORM_INITIALIZER, useValue: log.fn('platform_init1'), multi: true}, {provide: PLATFORM_INITIALIZER, useValue: log.fn('platform_init2'), multi: true} ])(); @NgModule({ imports: [BrowserModule], providers: [ {provide: APP_INITIALIZER, useValue: log.fn('app_init1'), multi: true}, {provide: APP_INITIALIZER, useValue: log.fn('app_init2'), multi: true} ] }) class SomeModule { ngDoBootstrap() {} } expect(log.result()).toEqual('platform_init1; platform_init2'); log.clear(); p.bootstrapModule(SomeModule).then(() => { expect(log.result()).toEqual('app_init1; app_init2'); async.done(); }); })); it('should remove styles when transitioning from a server render', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @Component({ selector: 'root', template: 'root', }) class RootCmp { } @NgModule({ bootstrap: [RootCmp], declarations: [RootCmp], imports: [BrowserModule.withServerTransition({appId: 'my-app'})], }) class TestModule { } // First, set up styles to be removed. const dom = getDOM(); const platform = platformBrowserDynamic(); const document = platform.injector.get(DOCUMENT); const style = dom.createElement('style', document); dom.setAttribute(style, 'ng-transition', 'my-app'); dom.appendChild(document.head, style); const root = dom.createElement('root', document); dom.appendChild(document.body, root); platform.bootstrapModule(TestModule).then(() => { const styles: HTMLElement[] = Array.prototype.slice.apply(dom.getElementsByTagName(document, 'style') || []); styles.forEach( style => { expect(dom.getAttribute(style, 'ng-transition')).not.toBe('my-app'); }); async.done(); }); })); it('should register each application with the testability registry', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise1: Promise<ComponentRef<any>> = bootstrap(HelloRootCmp, testProviders); const refPromise2: Promise<ComponentRef<any>> = bootstrap(HelloRootCmp2, testProviders); Promise.all([refPromise1, refPromise2]).then((refs: ComponentRef<any>[]) => { const registry = refs[0].injector.get(TestabilityRegistry); const testabilities = [refs[0].injector.get(Testability), refs[1].injector.get(Testability)]; Promise.all(testabilities).then((testabilities: Testability[]) => { expect(registry.findTestabilityInTree(el)).toEqual(testabilities[0]); expect(registry.findTestabilityInTree(el2)).toEqual(testabilities[1]); async.done(); }); }); })); it('should allow to pass schemas', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloCmpUsingCustomElement, testProviders).then((compRef) => { expect(el).toHaveText('hello world!'); async.done(); }); })); }); }
packages/platform-browser/test/browser/bootstrap_spec.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00023767923994455487, 0.00017248463700525463, 0.00016333538223989308, 0.000170314364368096, 0.000011437082321208436 ]
{ "id": 11, "code_window": [ " readonly PROTRACTOR=${{PARTS[1]}}\n", " elif [ \"${{PARTS[0]}}\" == \"angular/{TMPL_conf}\" ]; then\n", " readonly CONF=${{PARTS[1]}}\n", " fi\n", " done < $RUNFILE_MANIFEST_FILE\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " elif [ \"${{PARTS[0]}}\" == \"{TMPL_conf}\" ]; then\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 88 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [['del mediodía', 'de la madrugada', 'de la mañana', 'de la tarde', 'de la noche'], u, u], [['mediodía', 'madrugada', 'mañana', 'tarde', 'noche'], u, u], ['12:00', ['00:00', '06:00'], ['06:00', '12:00'], ['12:00', '20:00'], ['20:00', '24:00']] ];
packages/common/locales/extra/es-HN.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017470552120357752, 0.00017450627638027072, 0.0001743070170050487, 0.00017450627638027072, 1.9925209926441312e-7 ]
{ "id": 12, "code_window": [ " readonly CONF=${{PARTS[1]}}\n", " fi\n", " done < $RUNFILE_MANIFEST_FILE\n", "else\n", " readonly PROTRACTOR={TMPL_protractor}\n", " readonly CONF={TMPL_conf}\n", "fi\n", "\n", "export HOME=$(mktemp -d)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " readonly PROTRACTOR=../{TMPL_protractor}\n", " readonly CONF=../{TMPL_conf}\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 93 }
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license "Run end-to-end tests with Protractor" load( "@build_bazel_rules_nodejs//internal:node.bzl", "expand_path_into_runfiles", "sources_aspect", ) load("@io_bazel_rules_webtesting//web:web.bzl", "web_test_suite") load("@io_bazel_rules_webtesting//web/internal:constants.bzl", "DEFAULT_WRAPPED_TEST_TAGS") load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") _CONF_TMPL = "//packages/bazel/src/protractor:protractor.conf.js" def _protractor_web_test_impl(ctx): configuration = ctx.actions.declare_file( "%s.conf.js" % ctx.label.name, sibling = ctx.outputs.executable, ) files = depset(ctx.files.srcs) for d in ctx.attr.deps: if hasattr(d, "node_sources"): files = depset(transitive = [files, d.node_sources]) elif hasattr(d, "files"): files = depset(transitive = [files, d.files]) specs = [ expand_path_into_runfiles(ctx, f.short_path) for f in files ] configuration_sources = [] if ctx.file.configuration: configuration_sources = [ctx.file.configuration] if hasattr(ctx.attr.configuration, "node_sources"): configuration_sources = ctx.attr.configuration.node_sources.to_list() configuration_file = ctx.file.configuration if hasattr(ctx.attr.configuration, "typescript"): configuration_file = ctx.attr.configuration.typescript.es5_sources.to_list()[0] on_prepare_sources = [] if ctx.file.on_prepare: on_prepare_sources = [ctx.file.on_prepare] if hasattr(ctx.attr.on_prepare, "node_sources"): on_prepare_sources = ctx.attr.on_prepare.node_sources.to_list() on_prepare_file = ctx.file.on_prepare if hasattr(ctx.attr.on_prepare, "typescript"): on_prepare_file = ctx.attr.on_prepare.typescript.es5_sources.to_list()[0] protractor_executable_path = ctx.executable.protractor.short_path if protractor_executable_path.startswith(".."): protractor_executable_path = "external" + protractor_executable_path[2:] server_executable_path = "" if ctx.executable.server: server_executable_path = ctx.executable.server.short_path if server_executable_path.startswith(".."): server_executable_path = "external" + protractor_executable_path[2:] ctx.actions.expand_template( output = configuration, template = ctx.file._conf_tmpl, substitutions = { "TMPL_config": expand_path_into_runfiles(ctx, configuration_file.short_path) if configuration_file else "", "TMPL_on_prepare": expand_path_into_runfiles(ctx, on_prepare_file.short_path) if on_prepare_file else "", "TMPL_workspace": ctx.workspace_name, "TMPL_server": server_executable_path, "TMPL_specs": "\n".join([" '%s'," % e for e in specs]), }, ) runfiles = [configuration] + configuration_sources + on_prepare_sources ctx.actions.write( output = ctx.outputs.executable, is_executable = True, content = """#!/usr/bin/env bash if [ -e "$RUNFILE_MANIFEST_FILE" ]; then while read line; do declare -a PARTS=($line) if [ "${{PARTS[0]}}" == "angular/{TMPL_protractor}" ]; then readonly PROTRACTOR=${{PARTS[1]}} elif [ "${{PARTS[0]}}" == "angular/{TMPL_conf}" ]; then readonly CONF=${{PARTS[1]}} fi done < $RUNFILE_MANIFEST_FILE else readonly PROTRACTOR={TMPL_protractor} readonly CONF={TMPL_conf} fi export HOME=$(mktemp -d) # Print the protractor version in the test log PROTRACTOR_VERSION=$($PROTRACTOR --version) echo "Protractor $PROTRACTOR_VERSION" # Run the protractor binary $PROTRACTOR $CONF """.format( TMPL_protractor = protractor_executable_path, TMPL_conf = configuration.short_path, ), ) return [DefaultInfo( files = depset([ctx.outputs.executable]), runfiles = ctx.runfiles( files = runfiles, transitive_files = files, # Propagate protractor_bin and its runfiles collect_data = True, collect_default = True, ), executable = ctx.outputs.executable, )] _protractor_web_test = rule( implementation = _protractor_web_test_impl, test = True, executable = True, attrs = { "configuration": attr.label( doc = "Protractor configuration file", allow_single_file = True, aspects = [sources_aspect], ), "srcs": attr.label_list( doc = "A list of JavaScript test files", allow_files = [".js"], ), "on_prepare": attr.label( doc = """A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests.""", allow_single_file = True, aspects = [sources_aspect], ), "deps": attr.label_list( doc = "Other targets which produce JavaScript such as `ts_library`", allow_files = True, aspects = [sources_aspect], ), "data": attr.label_list( doc = "Runtime dependencies", ), "server": attr.label( doc = "Optional server executable target", executable = True, cfg = "target", single_file = False, allow_files = True, ), "protractor": attr.label( doc = "Protractor executable target (set by protractor_web_test macro)", executable = True, cfg = "target", single_file = False, allow_files = True, ), "_conf_tmpl": attr.label( default = Label(_CONF_TMPL), allow_single_file = True, ), }, ) def protractor_web_test( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, tags = [], **kwargs): """Runs a protractor test in a browser. Args: name: The name of the test configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target tags: Standard Bazel tags, this macro adds one for ibazel **kwargs: passed through to `_protractor_web_test` """ protractor_bin_name = name + "_protractor_bin" nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask :protractor_bin_name for its runfiles attr web_test_data = data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, tags = tags + [ # Users don't need to know that this tag is required to run under ibazel "ibazel_notify_changes", ], **kwargs ) def protractor_web_test_suite( name, configuration = None, on_prepare = None, srcs = [], deps = [], data = [], server = None, browsers = ["@io_bazel_rules_webtesting//browsers:chromium-local"], args = None, browser_overrides = None, config = None, flaky = None, local = None, shard_count = None, size = None, tags = [], test_suite_tags = None, timeout = None, visibility = None, web_test_data = [], wrapped_test_tags = None, **remaining_keyword_args): """Defines a test_suite of web_test targets that wrap a protractor_web_test target. Args: name: The base name of the test. configuration: Protractor configuration file. on_prepare: A file with a node.js script to run once before all tests run. If the script exports a function which returns a promise, protractor will wait for the promise to resolve before beginning tests. srcs: JavaScript source files deps: Other targets which produce JavaScript such as `ts_library` data: Runtime dependencies server: Optional server executable target browsers: A sequence of labels specifying the browsers to use. args: Args for web_test targets generated by this extension. browser_overrides: Dictionary; optional; default is an empty dictionary. A dictionary mapping from browser names to browser-specific web_test attributes, such as shard_count, flakiness, timeout, etc. For example: {'//browsers:chrome-native': {'shard_count': 3, 'flaky': 1} '//browsers:firefox-native': {'shard_count': 1, 'timeout': 100}}. config: Label; optional; Configuration of web test features. flaky: A boolean specifying that the test is flaky. If set, the test will be retried up to 3 times (default: 0) local: boolean; optional. shard_count: The number of test shards to use per browser. (default: 1) size: A string specifying the test size. (default: 'large') tags: A list of test tag strings to apply to each generated web_test target. This macro adds a couple for ibazel. test_suite_tags: A list of tag strings for the generated test_suite. timeout: A string specifying the test timeout (default: computed from size) visibility: List of labels; optional. web_test_data: Data dependencies for the web_test. wrapped_test_tags: A list of test tag strings to use for the wrapped test **remaining_keyword_args: Arguments for the wrapped test target. """ # Check explicitly for None so that users can set this to the empty list if wrapped_test_tags == None: wrapped_test_tags = DEFAULT_WRAPPED_TEST_TAGS size = size or "large" wrapped_test_name = name + "_wrapped_test" protractor_bin_name = name + "_protractor_bin" # Users don't need to know that this tag is required to run under ibazel tags = tags + ["ibazel_notify_changes"] nodejs_binary( name = protractor_bin_name, entry_point = "protractor/bin/protractor", data = srcs + deps + data, testonly = 1, visibility = ["//visibility:private"], ) # Our binary dependency must be in data[] for collect_data to pick it up # FIXME: maybe we can just ask the :protractor_bin_name for its runfiles attr web_test_data = web_test_data + [":" + protractor_bin_name] if server: web_test_data += [server] _protractor_web_test( name = wrapped_test_name, configuration = configuration, on_prepare = on_prepare, srcs = srcs, deps = deps, data = web_test_data, server = server, protractor = protractor_bin_name, args = args, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = wrapped_test_tags, timeout = timeout, visibility = ["//visibility:private"], **remaining_keyword_args ) web_test_suite( name = name, launcher = ":" + wrapped_test_name, args = args, browsers = browsers, browser_overrides = browser_overrides, config = config, data = web_test_data, flaky = flaky, local = local, shard_count = shard_count, size = size, tags = tags, test = wrapped_test_name, test_suite_tags = test_suite_tags, timeout = timeout, visibility = visibility, )
packages/bazel/src/protractor/protractor_web_test.bzl
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.7691867351531982, 0.022971464321017265, 0.00016358007269445807, 0.00017123552970588207, 0.12636694312095642 ]
{ "id": 12, "code_window": [ " readonly CONF=${{PARTS[1]}}\n", " fi\n", " done < $RUNFILE_MANIFEST_FILE\n", "else\n", " readonly PROTRACTOR={TMPL_protractor}\n", " readonly CONF={TMPL_conf}\n", "fi\n", "\n", "export HOME=$(mktemp -d)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " readonly PROTRACTOR=../{TMPL_protractor}\n", " readonly CONF=../{TMPL_conf}\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 93 }
export * from './hero.model'; export * from './hero.service';
aio/content/examples/styleguide/src/05-04/app/heroes/shared/index.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.0001685840979916975, 0.0001685840979916975, 0.0001685840979916975, 0.0001685840979916975, 0 ]
{ "id": 12, "code_window": [ " readonly CONF=${{PARTS[1]}}\n", " fi\n", " done < $RUNFILE_MANIFEST_FILE\n", "else\n", " readonly PROTRACTOR={TMPL_protractor}\n", " readonly CONF={TMPL_conf}\n", "fi\n", "\n", "export HOME=$(mktemp -d)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " readonly PROTRACTOR=../{TMPL_protractor}\n", " readonly CONF=../{TMPL_conf}\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 93 }
{$ doc.contents | escape $}
aio/tools/transforms/templates/example-region.template.html
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017485134594608098, 0.00017485134594608098, 0.00017485134594608098, 0.00017485134594608098, 0 ]
{ "id": 12, "code_window": [ " readonly CONF=${{PARTS[1]}}\n", " fi\n", " done < $RUNFILE_MANIFEST_FILE\n", "else\n", " readonly PROTRACTOR={TMPL_protractor}\n", " readonly CONF={TMPL_conf}\n", "fi\n", "\n", "export HOME=$(mktemp -d)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " readonly PROTRACTOR=../{TMPL_protractor}\n", " readonly CONF=../{TMPL_conf}\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 93 }
{ "name": "angular-bazel", "description": "example and integration test for building Angular apps with Bazel", "version": "0.0.0", "license": "MIT", "dependencies": { }, "scripts": { "//": "deps are listed in src/package.json which is used by yarn_install", "//": "this package.json file is only here so that `yarn test` can be called by /integration/run_tests.sh", "test": "bazel build ... --noshow_progress && bazel test ..." } }
integration/bazel/package.json
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017436433699913323, 0.0001735782716423273, 0.00017279219173360616, 0.0001735782716423273, 7.860726327635348e-7 ]
{ "id": 13, "code_window": [ "# Run the protractor binary\n", "$PROTRACTOR $CONF\n", "\"\"\".format(\n", " TMPL_protractor = protractor_executable_path,\n", " TMPL_conf = configuration.short_path,\n", " ),\n", " )\n", " return [DefaultInfo(\n", " files = depset([ctx.outputs.executable]),\n", " runfiles = ctx.runfiles(\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " TMPL_protractor = _short_path_to_manifest_path(ctx, ctx.executable.protractor.short_path),\n", " TMPL_conf = _short_path_to_manifest_path(ctx, configuration.short_path),\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 106 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const path = require('path'); const DEBUG = false; const configPath = 'TMPL_config'; const onPreparePath = 'TMPL_on_prepare'; const workspace = 'TMPL_workspace'; const server = 'TMPL_server'; if (DEBUG) console.info(`Protractor test starting with: cwd: ${process.cwd()} configPath: ${configPath} onPreparePath: ${onPreparePath} workspace: ${workspace} server: ${server}`); // Helper function to warn when a user specified value is being overwritten function setConf(conf, name, value, msg) { if (conf[name] && conf[name] !== value) { console.warn( `Your protractor configuration specifies an option which is overwritten by Bazel: '${name}' ${msg}`); } conf[name] = value; } let conf = {}; // Import the user's base protractor configuration if specified if (configPath) { const baseConf = require(configPath); if (!baseConf.config) { throw new Error('Invalid base protractor configration. Expected config to be exported.'); } conf = baseConf.config; } // Import the user's on prepare function if specified if (onPreparePath) { const onPrepare = require(onPreparePath); if (typeof onPrepare === 'function') { const original = conf.onPrepare; conf.onPrepare = function() { return Promise.resolve(original ? original() : null) .then(() => Promise.resolve(onPrepare({workspace, server}))); }; } else { throw new Error( 'Invalid protractor on_prepare script. Expected a function as the default export.'); } } // Override the user's base protractor configuration as appropriate based on the // ts_web_test_suite & rules_webtesting WEB_TEST_METADATA attributes setConf(conf, 'framework', 'jasmine2', 'is set to jasmine2'); const specs = [TMPL_specs].map(s => require.resolve(s)).filter(s => /\b(spec|test)\.js$/.test(s)); setConf(conf, 'specs', specs, 'are determined by the srcs and deps attribute'); // WEB_TEST_METADATA is configured in rules_webtesting based on value // of the browsers attribute passed to ts_web_test_suite // We setup the protractor configuration based on the values in this object if (process.env['WEB_TEST_METADATA']) { const webTestMetadata = require(process.env['WEB_TEST_METADATA']); if (DEBUG) console.info(`WEB_TEST_METADATA: ${JSON.stringify(webTestMetadata, null, 2)}`); if (webTestMetadata['environment'] === 'sauce') { // If a sauce labs browser is chosen for the test such as // "@io_bazel_rules_webtesting//browsers/sauce:chrome-win10" // than the 'environment' will equal 'sauce'. // We expect that a SAUCE_USERNAME and SAUCE_ACCESS_KEY is available // from the environment for this test to run // TODO(gmagolan): implement sauce labs support for protractor throw new Error('Saucelabs not yet support by protractor_web_test_suite.'); // if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) { // console.error('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are // set.'); // process.exit(1); // } // setConf(conf, 'sauceUser', process.env.SAUCE_USERNAME, 'is determined by the SAUCE_USERNAME // environment variable'); // setConf(conf, 'sauceKey', process.env.SAUCE_ACCESS_KEY, 'is determined by the // SAUCE_ACCESS_KEY environment variable'); } else if (webTestMetadata['environment'] === 'local') { // When a local chrome or firefox browser is chosen such as // "@io_bazel_rules_webtesting//browsers:chromium-local" or // "@io_bazel_rules_webtesting//browsers:firefox-local" // then the 'environment' will equal 'local' and // 'webTestFiles' will contain the path to the binary to use const webTestNamedFiles = webTestMetadata['webTestFiles'][0]['namedFiles']; const headless = !process.env['DISPLAY']; if (webTestNamedFiles['CHROMIUM']) { const chromeBin = path.join(process.cwd(), 'external', webTestNamedFiles['CHROMIUM']); const args = []; if (headless) { args.push('--headless'); args.push('--disable-gpu'); } setConf(conf, 'directConnect', true, 'is set to true for chrome'); setConf( conf, 'chromeDriver', path.join(process.cwd(), 'external', webTestNamedFiles['CHROMEDRIVER']), 'is determined by the browsers attribute'); setConf( conf, 'capabilities', { browserName: 'chrome', chromeOptions: { binary: chromeBin, args: args, } }, 'is determined by the browsers attribute'); } if (webTestNamedFiles['FIREFOX']) { // TODO(gmagolan): implement firefox support for protractor throw new Error('Firefox not yet support by protractor_web_test_suite'); // const firefoxBin = path.join('external', webTestNamedFiles['FIREFOX']); // const args = []; // if (headless) { // args.push("--headless") // args.push("--marionette") // } // setConf(conf, 'seleniumAddress', process.env.WEB_TEST_HTTP_SERVER.trim() + "/wd/hub", 'is // configured by Bazel for firefox browser') // setConf(conf, 'capabilities', { // browserName: "firefox", // 'moz:firefoxOptions': { // binary: firefoxBin, // args: args, // } // }, 'is determined by the browsers attribute'); } } else { console.warn(`Unknown WEB_TEST_METADATA environment '${webTestMetadata['environment']}'`); } } // Export the complete protractor configuration if (DEBUG) console.info(`Protractor configuration: ${JSON.stringify(conf, null, 2)}`); exports.config = conf;
packages/bazel/src/protractor/protractor.conf.js
1
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.004425910767167807, 0.0006210149149410427, 0.00016418137238360941, 0.00021790314349345863, 0.0010580882662907243 ]
{ "id": 13, "code_window": [ "# Run the protractor binary\n", "$PROTRACTOR $CONF\n", "\"\"\".format(\n", " TMPL_protractor = protractor_executable_path,\n", " TMPL_conf = configuration.short_path,\n", " ),\n", " )\n", " return [DefaultInfo(\n", " files = depset([ctx.outputs.executable]),\n", " runfiles = ctx.runfiles(\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " TMPL_protractor = _short_path_to_manifest_path(ctx, ctx.executable.protractor.short_path),\n", " TMPL_conf = _short_path_to_manifest_path(ctx, configuration.short_path),\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 106 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, NgModule} from '@angular/core'; import {ActivatedRoute, RouterModule} from '@angular/router'; import {DbService, InboxRecord} from './inbox-app'; @Component({selector: 'inbox-detail', templateUrl: 'app/inbox-detail.html'}) export class InboxDetailCmp { private record: InboxRecord = new InboxRecord(); private ready: boolean = false; constructor(db: DbService, route: ActivatedRoute) { route.paramMap.forEach( p => { db.email(p.get('id')).then((data) => { this.record.setData(data); }); }); } } @NgModule({ declarations: [InboxDetailCmp], imports: [RouterModule.forChild([{path: ':id', component: InboxDetailCmp}])] }) export default class InboxDetailModule { }
modules/playground/src/routing/app/inbox-detail.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017759842739906162, 0.00017360749188810587, 0.00016721432621125132, 0.00017480860697105527, 0.000003956878117605811 ]
{ "id": 13, "code_window": [ "# Run the protractor binary\n", "$PROTRACTOR $CONF\n", "\"\"\".format(\n", " TMPL_protractor = protractor_executable_path,\n", " TMPL_conf = configuration.short_path,\n", " ),\n", " )\n", " return [DefaultInfo(\n", " files = depset([ctx.outputs.executable]),\n", " runfiles = ctx.runfiles(\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " TMPL_protractor = _short_path_to_manifest_path(ctx, ctx.executable.protractor.short_path),\n", " TMPL_conf = _short_path_to_manifest_path(ctx, configuration.short_path),\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 106 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; TestBed.initTestEnvironment( [BrowserDynamicTestingModule, NoopAnimationsModule], platformBrowserDynamicTesting()); (window as any).isNode = false; (window as any).isBrowser = true; (window as any).global = window;
tools/testing/init_browser_spec.ts
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017572144861333072, 0.00017424841644242406, 0.0001727753842715174, 0.00017424841644242406, 0.000001473032170906663 ]
{ "id": 13, "code_window": [ "# Run the protractor binary\n", "$PROTRACTOR $CONF\n", "\"\"\".format(\n", " TMPL_protractor = protractor_executable_path,\n", " TMPL_conf = configuration.short_path,\n", " ),\n", " )\n", " return [DefaultInfo(\n", " files = depset([ctx.outputs.executable]),\n", " runfiles = ctx.runfiles(\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " TMPL_protractor = _short_path_to_manifest_path(ctx, ctx.executable.protractor.short_path),\n", " TMPL_conf = _short_path_to_manifest_path(ctx, configuration.short_path),\n" ], "file_path": "packages/bazel/src/protractor/protractor_web_test.bzl", "type": "replace", "edit_start_line_idx": 106 }
All of our npm dependencies are locked via the `yarn.lock` file for the following reasons: - our project has lots of dependencies which update at unpredictable times, so it's important that we update them explicitly once in a while rather than implicitly when any of us runs `yarn install` - locked dependencies allow us to reuse yarn cache on travis, significantly speeding up our builds (by 5 minutes or more) - locked dependencies allow us to detect when node_modules folder is out of date after a branch switch which allows us to build the project with the correct dependencies every time Before changing a dependency, do the following: - make sure you are in sync with `upstream/master`: `git fetch upstream && git rebase upstream/master` - ensure that your `node_modules` directory is not stale by running `yarn install` To add a new dependency do the following: `yarn add <packagename> --dev` To update an existing dependency do the following: run `yarn upgrade <packagename>@<version|latest> --dev` or `yarn upgrade <packagename> --dev` to update to the latest version that matches version constraint in `package.json` To Remove an existing dependency do the following: run `yarn remove <packagename>` Once you've changed the dependency, commit the changes to `package.json` & `yarn.lock`, and you are done.
yarn.lock.readme.md
0
https://github.com/angular/angular/commit/7f39f37003ae2a7e84abace3e78680852e622534
[ 0.00017112288333009928, 0.0001706360635580495, 0.00016968850104603916, 0.00017109679174609482, 6.701091024297057e-7 ]
{ "id": 0, "code_window": [ "\tconsole.log(\"Callback called!\");\n", "});\n", "bootbox.alert({\n", "\tsize: \"medium\",\n", "\tmessage: \"Are we ok with callback and custom button?\",\n", "\tcallback: function () {\n", "\t\tconsole.log(\"Callback called!\");\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tsize: \"small\",\n" ], "file_path": "bootbox/bootbox-tests.ts", "type": "replace", "edit_start_line_idx": 8 }
// QUnit Tests for Bootbox 4.4.0 bootbox.alert("Are we ok?"); bootbox.alert("Are we ok with callback?", function () { console.log("Callback called!"); }); bootbox.alert({ size: "medium", message: "Are we ok with callback and custom button?", callback: function () { console.log("Callback called!"); } }); bootbox.confirm("Click cancel to pass test", function (result) { console.log(!result); }); bootbox.confirm({ title: "Click confirm to pass test", message: "Please confirm this.", callback: function (result) { console.log(result); } }); bootbox.prompt("Enter 'ok' to pass test", function (result) { console.log(result); }); bootbox.prompt({ title: "Enter 'ok' to pass test", callback: function (result) { console.log(result); } }); bootbox.prompt({ size: "large", title: "Enter 'ok' to pass test", callback: function (result) { console.log(result); } }); bootbox.dialog({ title: "Wassup?", message: "Test Dialog", callback: function () { } }); // Testing the return object of the call. Using the pointer to disable the animation on success callback. var bBox : JQuery; bBox = bootbox.dialog({ message: "Test Dialog", buttons: { cancel: { label: "Cancel" }, confirm: { label: "Continue", callback: function () { bBox.removeClass("fade"); console.log("Outer callback."); } } }, animate: true, }); var bdo: BootboxDialogOptions; var sampleButton: BootboxButton = { label: 'ButtonLabelToUse', callback: function () { return 'callback of button click' }, className: 'additionalButtonClassName' }; bdo = { message: '', className: 'callName', buttons: { 'ButtonTextLabel': sampleButton } }; bootbox.dialog(bdo); bootbox.setDefaults({ locale: 'en_US', animate: false, backdrop: false, className: 'newClassName', closeButton: true, show: true }) bootbox.hideAll(); var localeOptions: BootboxLocaleValues = { OK: 'Hus', CANCEL: 'Nai', CONFIRM: 'Pakka' } bootbox.addLocale("Nepali", localeOptions); bootbox.setLocale("Nepali"); bootbox.removeLocale("Nepali");
bootbox/bootbox-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.962471067905426, 0.08919679373502731, 0.0002494127256795764, 0.00045653892448171973, 0.2761683464050293 ]
{ "id": 0, "code_window": [ "\tconsole.log(\"Callback called!\");\n", "});\n", "bootbox.alert({\n", "\tsize: \"medium\",\n", "\tmessage: \"Are we ok with callback and custom button?\",\n", "\tcallback: function () {\n", "\t\tconsole.log(\"Callback called!\");\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tsize: \"small\",\n" ], "file_path": "bootbox/bootbox-tests.ts", "type": "replace", "edit_start_line_idx": 8 }
import CircularJSON = require('circular-json'); var replacer = (key: any, val: any) => { return val; } var replacerArray = ['a', 'x']; // implements JSON interface var json_obj: JSON = CircularJSON; CircularJSON.parse('{"a":"b"}'); CircularJSON.parse('{"a":"b"}', replacer); // just stringify a value CircularJSON.stringify({a: 'b'}); // do replacements for part of the object CircularJSON.stringify({a: 'b'}, replacer); CircularJSON.stringify({a: 'b'}, replacerArray); // add whitespace to the output CircularJSON.stringify({a: 'b'}, replacer, 5); CircularJSON.stringify({a: 'b'}, replacerArray, 5); // do not actually set up a re-parseable object CircularJSON.stringify({a: 'b'}, replacer, 5, true); CircularJSON.stringify({a: 'b'}, replacerArray, 5, true);
circular-json/circular-json-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.00017317272431682795, 0.00017153716180473566, 0.00017029129958245903, 0.00017134228255599737, 0.0000011375652775313938 ]
{ "id": 0, "code_window": [ "\tconsole.log(\"Callback called!\");\n", "});\n", "bootbox.alert({\n", "\tsize: \"medium\",\n", "\tmessage: \"Are we ok with callback and custom button?\",\n", "\tcallback: function () {\n", "\t\tconsole.log(\"Callback called!\");\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tsize: \"small\",\n" ], "file_path": "bootbox/bootbox-tests.ts", "type": "replace", "edit_start_line_idx": 8 }
import * as _ from "lodash"; declare const curry: typeof _.curry; export default curry;
lodash-es/curry/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.00017049307643901557, 0.00017049307643901557, 0.00017049307643901557, 0.00017049307643901557, 0 ]
{ "id": 0, "code_window": [ "\tconsole.log(\"Callback called!\");\n", "});\n", "bootbox.alert({\n", "\tsize: \"medium\",\n", "\tmessage: \"Are we ok with callback and custom button?\",\n", "\tcallback: function () {\n", "\t\tconsole.log(\"Callback called!\");\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tsize: \"small\",\n" ], "file_path": "bootbox/bootbox-tests.ts", "type": "replace", "edit_start_line_idx": 8 }
// Type definitions for i18n-node 0.5.0 // Project: https://github.com/mashpie/i18n-node // Definitions by: Maxime LUCE <https://github.com/SomaticIT> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace i18n { export interface ConfigurationOptions { /** Setup some locales - other locales default to en silently */ locales?: string[]; /** Alter a site wide default locale */ defaultLocale?: string; /** * Sets a custom cookie name to parse locale settings from * @default null */ cookie?: string; /** * Where to store json files, relative to modules directory * @default "./locales" */ directory?: string; /** * whether to write new locale information to disk * @default true */ updateFiles?: boolean; /** * What to use as the indentation unit * @default "\t" */ indent?: string; /** * Setting extension of json files (you might want to set this to '.js' according to webtranslateit) * @default ".json" */ extension?: string; /** * Enable object notation * @default false */ objectNotation?: boolean; /** * json files prefix */ prefix?: string; /** * object or [obj1, obj2] to bind the i18n api and current locale to - defaults to null */ register?: any; } export interface TranslateOptions { phrase: string; locale?: string; } export interface PluralOptions { singular: string; plural: string; count?: number; locale?: string; } export interface Replacements { [key: string]: string; } export interface LocaleCatalog { [key: string]: string; } export interface GlobalCatalog { [key: string]: LocaleCatalog; } /** * Configure current i18n instance * @param {ConfigurationOptions} options - configuration options for i18n */ function configure(options: ConfigurationOptions): void; /** * Initialize i18n middleware for express * @param {Express.Request} request - Current express request * @param {Express.Response} response - Current express response * @param {Function} next - Callback to continue process */ function init(request: Express.Request, response: Express.Response, next?: Function): void; //#region __() /** * Translate the given phrase using locale configuration * @param {string} phrase - The phrase to translate * @returns {string} The translated phrase */ function __(phrase: string, ...replace: string[]): string; /** * Translate the given phrase using locale configuration * @param {string} phrase - The phrase to translate * @param {Object} replacements - An object containing replacements * @returns {string} The translated phrase */ function __(phrase: string, replacements: Replacements): string; /** * Translate the given phrase using locale configuration * @param {TranslateOptions} options - Options for translation * @returns {string} The translated phrase */ function __(options: TranslateOptions): string; /** * Translate the given phrase using locale configuration * @param {TranslateOptions} options - Options for translation * @returns {string} The translated phrase */ function __(options: TranslateOptions, ...replace: string[]): string; /** * Translate the given phrase using locale configuration * @param {TranslateOptions} options - Options for translation * @param {Object} replacements - An object containing replacements * @returns {string} The translated phrase */ function __(options: TranslateOptions, replacements: Replacements): string; //#endregion //#region __n() /** * Translate with plural condition the given phrase and count using locale configuration * @param {PluralOptions} options - Options for plural translate * @returns {string} The translated phrase */ function __n(options: PluralOptions): string; /** * Translate with plural condition the given phrase and count using locale configuration * @param {PluralOptions} options - Options for plural translate * @param {number} count - The number which allow to select from plural to singular * @returns {string} The translated phrase */ function __n(options: PluralOptions, count: number): string; /** * Translate with plural condition the given phrase and count using locale configuration * @param {string} singular - The singular pharse to translate if count is <= 1 * @param {string} plural - The plural pharse to translate if count is > 1 * @param {number} count - The number which allow to select from plural to singular * @returns {string} The translated phrase */ function __n(singular: string, plural: string, count: number): string; /** * Translate with plural condition the given phrase and count using locale configuration * @param {string} singular - The singular pharse to translate if count is <= 1 * @param {string} plural - The plural pharse to translate if count is > 1 * @param {number} count - The number which allow to select from plural to singular * @returns {string} The translated phrase */ function __n(singular: string, plural: string, count: string): string; //#endregion //#region Locale /** * Change the current active locale * @param {string} locale - The locale to set as default */ function setLocale(locale: string): void; /** * Change the current active locale for specified request * @param {Express.Request} request - The request to change locale on * @param {string} locale - The locale to set as default */ function setLocale(request: Express.Request, locale: string): void; /** * Get the current active locale * @returns {string} The current locale in request */ function getLocale(): string; /** * Get the current active locale for specified request * @param {Express.Request} request - The request to get locale for * @returns {string} The current locale in request */ function getLocale(request: Express.Request): string; //#endregion //#region Catalog /** * Get the current global catalog * @returns {GlobalCatalog} The current global catalog */ function getCatalog(): GlobalCatalog; /** * Get the catalog for the given locale * @param {string} locale - The locale to get catalog for * @returns {LocaleCatalog} The specified locale catalog */ function getCatalog(locale: string): LocaleCatalog; /** * Get the current active locale catalog for specified request * @param {Express.Request} request - The request to get locale catalog for * @returns {LocaleCatalog} The current locale catalog for the specified request */ function getCatalog(request: Express.Request): LocaleCatalog; /** * Get the current locale catalog for specified request and specified locale * @param {Express.Request} request - The request to get locale catalog for * @param {string} locale - The locale to get catalog for * @returns {LocaleCatalog} The specified locale catalog */ function getCatalog(request: Express.Request, locale: string): LocaleCatalog; //#endregion /** * Override the current request locale by using the query param (?locale=en) * @param {Express.Request} [request] - The request to override locale for */ function overrideLocaleFromQuery(request?: Express.Request): void; /** * Get current i18n-node version * @member {string} */ var version: string; } interface i18nAPI { locale: string; //#region __() /** * Translate the given phrase using locale configuration * @param {string} phrase - The phrase to translate * @returns {string} The translated phrase */ __(phrase: string, ...replace: string[]): string; /** * Translate the given phrase using locale configuration * @param {string} phrase - The phrase to translate * @param {Object} replacements - An object containing replacements * @returns {string} The translated phrase */ __(phrase: string, replacements: i18n.Replacements): string; /** * Translate the given phrase using locale configuration * @param {TranslateOptions} options - Options for translation * @returns {string} The translated phrase */ __(options: i18n.TranslateOptions): string; /** * Translate the given phrase using locale configuration * @param {TranslateOptions} options - Options for translation * @returns {string} The translated phrase */ __(options: i18n.TranslateOptions, ...replace: string[]): string; /** * Translate the given phrase using locale configuration * @param {TranslateOptions} options - Options for translation * @param {Object} replacements - An object containing replacements * @returns {string} The translated phrase */ __(options: i18n.TranslateOptions, replacements: i18n.Replacements): string; //#endregion //#region __n() /** * Translate with plural condition the given phrase and count using locale configuration * @param {PluralOptions} options - Options for plural translate * @returns {string} The translated phrase */ __n(options: i18n.PluralOptions): string; /** * Translate with plural condition the given phrase and count using locale configuration * @param {PluralOptions} options - Options for plural translate * @param {number} count - The number which allow to select from plural to singular * @returns {string} The translated phrase */ __n(options: i18n.PluralOptions, count: number): string; /** * Translate with plural condition the given phrase and count using locale configuration * @param {string} singular - The singular pharse to translate if count is <= 1 * @param {string} plural - The plural pharse to translate if count is > 1 * @param {number} count - The number which allow to select from plural to singular * @returns {string} The translated phrase */ __n(singular: string, plural: string, count: number): string; /** * Translate with plural condition the given phrase and count using locale configuration * @param {string} singular - The singular pharse to translate if count is <= 1 * @param {string} plural - The plural pharse to translate if count is > 1 * @param {number} count - The number which allow to select from plural to singular * @returns {string} The translated phrase */ __n(singular: string, plural: string, count: string): string; //#endregion /** * Get the current active locale * @returns {string} The current locale in request */ getLocale(): string; /** * Change the current active locale * @param {string} locale - The locale to set as default */ setLocale(locale: string): void; /** * Get the current global catalog * @returns {GlobalCatalog} The current global catalog */ getCatalog(): i18n.GlobalCatalog; /** * Get the catalog for the given locale * @param {string} locale - The locale to get catalog for * @returns {LocaleCatalog} The specified locale catalog */ getCatalog(locale: string): i18n.LocaleCatalog; } declare module "i18n" { export = i18n; } declare namespace Express { export interface Request extends i18nAPI { languages: string[]; regions: string[]; language: string; region: string; } export interface Response extends i18nAPI { locals: i18nAPI } }
i18n/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.0001749557413859293, 0.0001710025389911607, 0.00016689242329448462, 0.00017116549133788794, 0.0000018885784811573103 ]
{ "id": 1, "code_window": [ "\tshow?: boolean;\n", "\tbackdrop?: boolean;\n", "\tcloseButton?: boolean;\n", "\tanimate?: boolean;\n", "\tclassName?: string;\n", "\tsize?: string;\n", "\tbuttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton\n", "}\n", "\n", "/** Bootbox options available for custom modals */\n", "interface BootboxDialogOptions extends BootboxBaseOptions {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t/** All other values result in medium */\n", "\tsize?: \"small\" | \"large\";\n" ], "file_path": "bootbox/index.d.ts", "type": "replace", "edit_start_line_idx": 17 }
// Type definitions for Bootbox 4.4.0 // Project: https://github.com/makeusabrew/bootbox // Definitions by: Vincent Bortone <https://github.com/vbortone/>, Kon Pik <https://github.com/konpikwastaken/>, Anup Kattel <https://github.com/kanup/>, Dominik Schroeter <https://github.com/icereed/>, Troy McKinnon <https://github.com/trodi/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="jquery" /> /** Bootbox options shared by all modal types */ interface BootboxBaseOptions { title?: string | Element; callback?: (result: boolean | string) => any; onEscape?: (() => any) | boolean; show?: boolean; backdrop?: boolean; closeButton?: boolean; animate?: boolean; className?: string; size?: string; buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton } /** Bootbox options available for custom modals */ interface BootboxDialogOptions extends BootboxBaseOptions { message: string | Element; } /** Bootbox options available for alert modals */ interface BootboxAlertOptions extends BootboxDialogOptions { callback?: () => any; buttons?: BootboxAlertButtonMap; } /** Bootbox options available for confirm modals */ interface BootboxConfirmOptions extends BootboxDialogOptions { callback: (result: boolean) => any; buttons?: BootboxConfirmPromptButtonMap; } /** Bootbox options available for prompt modals */ interface BootboxPromptOptions extends BootboxBaseOptions { title: string; value?: string; inputType?: string; callback: (result: string) => any; buttons?: BootboxConfirmPromptButtonMap; } /** Bootbox options available when setting defaults for modals */ interface BootboxDefaultOptions { locale?: string; show?: boolean; backdrop?: boolean; closeButton?: boolean; animate?: boolean; className?: string; } interface BootboxButton { label?: string; className?: string; callback?: () => any; } interface BootboxButtonMap { [key: string]: BootboxButton | Function; } /** ButtonMap options for alerts modals */ interface BootboxAlertButtonMap extends BootboxButtonMap { ok: BootboxButton | Function; } /** ButtonMap options for confirm and prompt modals */ interface BootboxConfirmPromptButtonMap extends BootboxButtonMap { confirm: BootboxButton | Function; cancel: BootboxButton | Function; } interface BootboxLocaleValues { OK: string; CANCEL: string; CONFIRM: string; } interface BootboxStatic { alert(message: string, callback?: () => void): JQuery; alert(options: BootboxAlertOptions): JQuery; confirm(message: string, callback: (result: boolean) => void): JQuery; confirm(options: BootboxConfirmOptions): JQuery; prompt(message: string, callback: (result: string) => void): JQuery; prompt(options: BootboxPromptOptions): JQuery; dialog(message: string, callback?: (result: string) => void): JQuery; dialog(options: BootboxDialogOptions): JQuery; setDefaults(options: BootboxDefaultOptions): void; hideAll(): void; addLocale(name: string, values: BootboxLocaleValues): void; removeLocale(name: string): void; setLocale(name: string): void; } declare var bootbox: BootboxStatic; declare module "bootbox" { export = bootbox; }
bootbox/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.9993628859519958, 0.5447565317153931, 0.001527390442788601, 0.9345991015434265, 0.48480838537216187 ]
{ "id": 1, "code_window": [ "\tshow?: boolean;\n", "\tbackdrop?: boolean;\n", "\tcloseButton?: boolean;\n", "\tanimate?: boolean;\n", "\tclassName?: string;\n", "\tsize?: string;\n", "\tbuttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton\n", "}\n", "\n", "/** Bootbox options available for custom modals */\n", "interface BootboxDialogOptions extends BootboxBaseOptions {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t/** All other values result in medium */\n", "\tsize?: \"small\" | \"large\";\n" ], "file_path": "bootbox/index.d.ts", "type": "replace", "edit_start_line_idx": 17 }
/// <reference types="yui" /> YUI.add('pad-iso97971-test', function (Y) { var C = CryptoJS; Y.Test.Runner.add(new Y.Test.Case({ name: 'Iso97971', testPad1: function () { var data = C.lib.WordArray.create([0xdddddd00], 3); C.pad.Iso97971.pad(data, 1); Y.Assert.areEqual(C.lib.WordArray.create([0xdddddd80]).toString(), data.toString()); }, testPad2: function () { var data = C.lib.WordArray.create([0xdddddd00], 3); C.pad.Iso97971.pad(data, 2); Y.Assert.areEqual(C.lib.WordArray.create([0xdddddd80, 0x00000000]).toString(), data.toString()); }, testPadClamp: function () { var data = C.lib.WordArray.create([0xdddddddd, 0xdddddddd], 3); C.pad.Iso97971.pad(data, 2); Y.Assert.areEqual(C.lib.WordArray.create([0xdddddd80, 0x00000000]).toString(), data.toString()); }, testUnpad: function () { var data = C.lib.WordArray.create([0xdddddd80, 0x00000000]); C.pad.Iso97971.unpad(data); Y.Assert.areEqual(C.lib.WordArray.create([0xdddddd00], 3).toString(), data.toString()); } })); }, '$Rev$');
cryptojs/test/pad-iso97971-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.0001750127994455397, 0.00017310729890596122, 0.00017114426009356976, 0.0001731360680423677, 0.0000013735751736021484 ]
{ "id": 1, "code_window": [ "\tshow?: boolean;\n", "\tbackdrop?: boolean;\n", "\tcloseButton?: boolean;\n", "\tanimate?: boolean;\n", "\tclassName?: string;\n", "\tsize?: string;\n", "\tbuttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton\n", "}\n", "\n", "/** Bootbox options available for custom modals */\n", "interface BootboxDialogOptions extends BootboxBaseOptions {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t/** All other values result in medium */\n", "\tsize?: \"small\" | \"large\";\n" ], "file_path": "bootbox/index.d.ts", "type": "replace", "edit_start_line_idx": 17 }
var obj:Object; var bool:boolean; var num:number; var str:string; var diff:string; var x:any = null; var arr:any[]; var exp:RegExp; var strArr:string[]; var numArr:string[]; var mod:typeof SemVerModule; var v1:string, v2:string; var version:string; var versions:string[]; var loose:boolean; str = mod.valid(str); str = mod.clean(str); str = mod.valid(str, loose); str = mod.clean(str, loose); str = mod.inc(str, str, loose); num = mod.major(str, loose); num = mod.minor(str, loose); num = mod.patch(str, loose); strArr = mod.prerelease(str, loose); // Comparison bool = mod.gt(v1, v2, loose); bool = mod.gte(v1, v2, loose); bool = mod.lt(v1, v2, loose); bool = mod.lte(v1, v2, loose); bool = mod.eq(v1, v2, loose); bool = mod.neq(v1, v2, loose); bool = mod.cmp(v1, x, v2, loose); num = mod.compare(v1, v2, loose); num = mod.rcompare(v1, v2, loose); diff = mod.diff(v1, v2, loose); // Ranges str = mod.validRange(str, loose); bool = mod.satisfies(version, str, loose); str = mod.maxSatisfying(versions, str, loose); str = mod.minSatisfying(versions, str, loose); bool = mod.gtr(version, str, loose); bool = mod.ltr(version, str, loose); bool = mod.outside(version, str, str, loose); var ver = new mod.SemVer(str, bool); str = ver.raw; bool = ver.loose; str = ver.format(); str = ver.inspect(); str = ver.toString(); num = ver.major; num = ver.minor; num = ver.patch; str = ver.version; strArr = ver.build; strArr = ver.prerelease; num = ver.compare(ver); num = ver.compareMain(ver); num = ver.comparePre(ver); ver = ver.inc(str); var comp = new SemVerModule.Comparator(str, bool); str = comp.raw; bool = comp.loose; str = comp.format(); str = comp.inspect(); str = comp.toString(); ver = comp.semver; str = comp.operator; bool = comp.value; comp.parse(str); bool = comp.test(ver); var range = new SemVerModule.Range(str, bool); str = range.raw; bool = range.loose; str = range.format(); str = range.inspect(); str = range.toString(); bool = range.test(ver); var sets:SemVerModule.Comparator[][]; sets = range.set; var lims:SemVerModule.Comparator[]; lims = range.parseRange(str); /** * Test Static version */ var semver: SemVerStatic = semver; var testString: string; var testNumber: number; var testBoolean: boolean; testString = semver.SEMVER_SPEC_VERSION; testString = semver.valid('v1.0.0'); testString = semver.clean(' =v1.0.0 '); testString = semver.valid('v1.0.0', true); testString = semver.clean(' =v1.0.0 ', true); testString = semver.inc('v1.0.0', 'major'); testString = semver.inc('v1.0.0', 'major', true); testNumber = semver.major('v1.0.0'); testNumber = semver.major('v1.0.0', true); testNumber = semver.minor('v1.0.0'); testNumber = semver.minor('v1.0.0', true); testNumber = semver.patch('v1.0.0'); testNumber = semver.patch('v1.0.0', true); testBoolean = semver.gt('v1.0.0', 'v2.0.0'); testBoolean = semver.gt('v1.0.0', 'v2.0.0', true); testBoolean = semver.gte('v1.0.0', 'v2.0.0'); testBoolean = semver.gte('v1.0.0', 'v2.0.0', true); testBoolean = semver.lt('v1.0.0', 'v2.0.0'); testBoolean = semver.lt('v1.0.0', 'v2.0.0', true); testBoolean = semver.lte('v1.0.0', 'v2.0.0'); testBoolean = semver.lte('v1.0.0', 'v2.0.0', true); testBoolean = semver.eq('v1.0.0', 'v2.0.0'); testBoolean = semver.eq('v1.0.0', 'v2.0.0', true); testBoolean = semver.neq('v1.0.0', 'v2.0.0'); testBoolean = semver.neq('v1.0.0', 'v2.0.0', true); testBoolean = semver.cmp('v1.0.0', '===', 'v2.0.0'); testBoolean = semver.cmp('v1.0.0', '!==', 'v2.0.0', true); testNumber = semver.compare('v1.0.0', 'v2.0.0'); testNumber = semver.compare('v1.0.0', 'v2.0.0', true); testNumber = semver.rcompare('v1.0.0', 'v2.0.0'); testNumber = semver.rcompare('v1.0.0', 'v2.0.0', true); testString = semver.diff('v1.0.0', 'v2.0.0'); testString = semver.diff('v1.0.0', 'v2.0.0', true); testString = semver.validRange('^1.0.0'); testString = semver.validRange('^1.0.0', true); testBoolean = semver.satisfies('v1.0.0', '^1.0.0'); testBoolean = semver.satisfies('v1.0.0', '^1.0.0', true); testString = semver.maxSatisfying(['v1.0.0', 'v2.0.0'], '^1.0.0'); testString = semver.maxSatisfying(['v1.0.0', 'v2.0.0'], '^1.0.0', true); testBoolean = semver.gtr('v1.0.0', '^1.0.0'); testBoolean = semver.gtr('v1.0.0', '^1.0.0', true); testBoolean = semver.ltr('v1.0.0', '^1.0.0'); testBoolean = semver.ltr('v1.0.0', '^1.0.0', true); testBoolean = semver.outside('v1.0.0', '^1.0.0', '<'); testBoolean = semver.outside('v1.0.0', '^1.0.0', '>', true);
semver/semver-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.0010657552629709244, 0.00024318648502230644, 0.00016063523071352392, 0.00017875406774692237, 0.00021784385899081826 ]
{ "id": 1, "code_window": [ "\tshow?: boolean;\n", "\tbackdrop?: boolean;\n", "\tcloseButton?: boolean;\n", "\tanimate?: boolean;\n", "\tclassName?: string;\n", "\tsize?: string;\n", "\tbuttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton\n", "}\n", "\n", "/** Bootbox options available for custom modals */\n", "interface BootboxDialogOptions extends BootboxBaseOptions {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t/** All other values result in medium */\n", "\tsize?: \"small\" | \"large\";\n" ], "file_path": "bootbox/index.d.ts", "type": "replace", "edit_start_line_idx": 17 }
import { Component, ClassAttributes, CSSProperties } from "react"; import { Color, ColorChangeHandler } from "react-color"; export interface EditableInputStyles { input?: CSSProperties; label?: CSSProperties; wrap?: CSSProperties; } export interface EditableInputProps extends ClassAttributes<EditableInput> { color?: Color; label?: string; onChange?: ColorChangeHandler; styles?: EditableInputStyles; value?: any; } export default class EditableInput extends Component<EditableInputProps, any> {}
react-color/lib/components/common/EditableInput.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.0001690975041128695, 0.00016821478493511677, 0.0001673320512054488, 0.00016821478493511677, 8.827264537103474e-7 ]
{ "id": 2, "code_window": [ "/** Bootbox options available for prompt modals */\n", "interface BootboxPromptOptions extends BootboxBaseOptions {\n", "\ttitle: string;\n", "\tvalue?: string;\n", "\tinputType?: string;\n", "\tcallback: (result: string) => any;\n", "\tbuttons?: BootboxConfirmPromptButtonMap;\n", "}\n", "\n", "/** Bootbox options available when setting defaults for modals */\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tinputType?: \"text\" | \"textarea\" | \"email\" | \"select\" | \"checkbox\" | \"date\" | \"time\" | \"number\" | \"password\";\n" ], "file_path": "bootbox/index.d.ts", "type": "replace", "edit_start_line_idx": 42 }
// Type definitions for Bootbox 4.4.0 // Project: https://github.com/makeusabrew/bootbox // Definitions by: Vincent Bortone <https://github.com/vbortone/>, Kon Pik <https://github.com/konpikwastaken/>, Anup Kattel <https://github.com/kanup/>, Dominik Schroeter <https://github.com/icereed/>, Troy McKinnon <https://github.com/trodi/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="jquery" /> /** Bootbox options shared by all modal types */ interface BootboxBaseOptions { title?: string | Element; callback?: (result: boolean | string) => any; onEscape?: (() => any) | boolean; show?: boolean; backdrop?: boolean; closeButton?: boolean; animate?: boolean; className?: string; size?: string; buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton } /** Bootbox options available for custom modals */ interface BootboxDialogOptions extends BootboxBaseOptions { message: string | Element; } /** Bootbox options available for alert modals */ interface BootboxAlertOptions extends BootboxDialogOptions { callback?: () => any; buttons?: BootboxAlertButtonMap; } /** Bootbox options available for confirm modals */ interface BootboxConfirmOptions extends BootboxDialogOptions { callback: (result: boolean) => any; buttons?: BootboxConfirmPromptButtonMap; } /** Bootbox options available for prompt modals */ interface BootboxPromptOptions extends BootboxBaseOptions { title: string; value?: string; inputType?: string; callback: (result: string) => any; buttons?: BootboxConfirmPromptButtonMap; } /** Bootbox options available when setting defaults for modals */ interface BootboxDefaultOptions { locale?: string; show?: boolean; backdrop?: boolean; closeButton?: boolean; animate?: boolean; className?: string; } interface BootboxButton { label?: string; className?: string; callback?: () => any; } interface BootboxButtonMap { [key: string]: BootboxButton | Function; } /** ButtonMap options for alerts modals */ interface BootboxAlertButtonMap extends BootboxButtonMap { ok: BootboxButton | Function; } /** ButtonMap options for confirm and prompt modals */ interface BootboxConfirmPromptButtonMap extends BootboxButtonMap { confirm: BootboxButton | Function; cancel: BootboxButton | Function; } interface BootboxLocaleValues { OK: string; CANCEL: string; CONFIRM: string; } interface BootboxStatic { alert(message: string, callback?: () => void): JQuery; alert(options: BootboxAlertOptions): JQuery; confirm(message: string, callback: (result: boolean) => void): JQuery; confirm(options: BootboxConfirmOptions): JQuery; prompt(message: string, callback: (result: string) => void): JQuery; prompt(options: BootboxPromptOptions): JQuery; dialog(message: string, callback?: (result: string) => void): JQuery; dialog(options: BootboxDialogOptions): JQuery; setDefaults(options: BootboxDefaultOptions): void; hideAll(): void; addLocale(name: string, values: BootboxLocaleValues): void; removeLocale(name: string): void; setLocale(name: string): void; } declare var bootbox: BootboxStatic; declare module "bootbox" { export = bootbox; }
bootbox/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.9989286065101624, 0.34059083461761475, 0.0014754630392417312, 0.012788358144462109, 0.4259776175022125 ]
{ "id": 2, "code_window": [ "/** Bootbox options available for prompt modals */\n", "interface BootboxPromptOptions extends BootboxBaseOptions {\n", "\ttitle: string;\n", "\tvalue?: string;\n", "\tinputType?: string;\n", "\tcallback: (result: string) => any;\n", "\tbuttons?: BootboxConfirmPromptButtonMap;\n", "}\n", "\n", "/** Bootbox options available when setting defaults for modals */\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tinputType?: \"text\" | \"textarea\" | \"email\" | \"select\" | \"checkbox\" | \"date\" | \"time\" | \"number\" | \"password\";\n" ], "file_path": "bootbox/index.d.ts", "type": "replace", "edit_start_line_idx": 42 }
import { ValueNode, //IntValueNode, //FloatValueNode, //StringValueNode, //BooleanValueNode, //EnumValueNode, //ListValueNode, //ObjectValueNode, } from '../language/ast'; import { GraphQLInputType } from '../type/definition'; /** * Produces a GraphQL Value AST given a JavaScript value. * * A GraphQL type must be provided, which will be used to interpret different * JavaScript values. * * | JSON Value | GraphQL Value | * | ------------- | -------------------- | * | Object | Input Object | * | Array | List | * | Boolean | Boolean | * | String | String / Enum Value | * | Number | Int / Float | * | Mixed | Enum Value | * */ // TODO: this should set overloads according to above the table export function astFromValue( value: any, type: GraphQLInputType ): ValueNode // Warning: there is a code in bottom: throw new TypeError
graphql/utilities/astFromValue.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.0001733098179101944, 0.0001703864400042221, 0.00016641219554003328, 0.00017091186600737274, 0.000002603303983050864 ]
{ "id": 2, "code_window": [ "/** Bootbox options available for prompt modals */\n", "interface BootboxPromptOptions extends BootboxBaseOptions {\n", "\ttitle: string;\n", "\tvalue?: string;\n", "\tinputType?: string;\n", "\tcallback: (result: string) => any;\n", "\tbuttons?: BootboxConfirmPromptButtonMap;\n", "}\n", "\n", "/** Bootbox options available when setting defaults for modals */\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tinputType?: \"text\" | \"textarea\" | \"email\" | \"select\" | \"checkbox\" | \"date\" | \"time\" | \"number\" | \"password\";\n" ], "file_path": "bootbox/index.d.ts", "type": "replace", "edit_start_line_idx": 42 }
// Type definitions for express session-file-store 1.0 // Project: https://github.com/valery-barysok/session-file-store // Definitions by: Gevik Babakhani <https://github.com/blendsdk> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="express-session" /> export = FileStore; declare namespace FileStore { /** * FileStore Options * * @interface Options */ interface Options { /** * The directory where the session files will be stored. Defaults to `./sessions` * * @type {string} * @memberOf Options */ path?: string; /** * Session time to live in seconds. Defaults to `3600` * * @type {number} * @memberOf Options */ ttl?: number; /** * The number of retries to get session data from a session file. Defaults to `5` * * @type {number} * @memberOf Options */ retries?: number; /** * The exponential factor to use for retry. Defaults to `1` * * @type {number} * @memberOf Options */ factor?: number; /** * The number of milliseconds before starting the first retry. Defaults to `50` * * @type {number} * @memberOf Options */ minTimeout?: number; /** * The maximum number of milliseconds between two retries. Defaults to `100` * * @type {number} * @memberOf Options */ maxTimeout?: number; /** * [OUT] Contains intervalObject if reap was scheduled * * @type {*} * @memberOf Options */ reapIntervalObject?: any; /** * Interval to clear expired sessions in seconds or -1 if do not need. Defaults to `1 hour` * * @type {number} * @memberOf Options */ reapInterval?: number; /** * Undocumented * * @type {number} * @memberOf Options */ reapMaxConcurrent?: number; /** * Use distinct worker process for removing stale sessions. Defaults to `false` * * @type {boolean} * @memberOf Options */ reapAsync?: boolean; /** * Reap stale sessions synchronously if can not do it asynchronously. Default to `false` * * @type {boolean} * @memberOf Options */ reapSyncFallback?: boolean; /** * Log messages. Defaults to `console.log` * * @type {Function} * @memberOf Options */ logFn?: (...args: any[]) => void; /** * Returns fallback session object after all failed retries. No defaults * * @type {Function} * @memberOf Options */ fallbackSessionFn?: (...args: any[]) => void; /** * Object-to-text text encoding. Can be null. Defaults to `'utf8'` * * @type {string} * @memberOf Options */ encoding?: string; /** * Encoding function. Takes object, returns encoded data. Defaults to `JSON.stringify` * * @type {Function} * @memberOf Options */ encoder?: (...args: any[]) => void; /** * Decoding function. Takes encoded data, returns object. Defaults to `JSON.parse` * * @type {Function} * @memberOf Options */ decoder?: (...args: any[]) => void; /** * If secret string is specified then enables encryption of the session before * writing the file and also decryption when reading it. * * @type {string} * @memberOf Options */ secret?: string; /** * Encryption output encoding. Defaults to `'hex'` * * @type {string} * @memberOf Options */ encryptEncoding?: string; /** * File extension of saved files. Defaults to `'.json'` * * @type {string} * @memberOf Options */ fileExtension?: string; /** * Undocumented * * @type {RegExp} * @memberOf Options */ filePattern?: RegExp; /** * Encryption key retrieval function. Takes secret andsession id, returns key. * Defaults to `function(secret, sessionId){return secret + sessionId;}` * * * @memberOf Options */ keyFunction?: (secret: string, sessionId: string) => string; } } /** * Session file store is a provision for storing session data in * the session file * * @class FileStore */ declare class FileStore { /** * Creates an instance of FileStore. * @param {FileStore.Options} options * * @memberOf FileStore */ constructor(options: FileStore.Options); /** * Attempts to fetch session from a session file by the given `sessionId` * * @param {string} sessionId * @param {(err: any, session: Express.Session) => void} callback * * @memberOf FileStore */ get(sessionId: string, callback: (err: any, session: Express.Session) => void): void; /** * Attempts to commit the given session associated with the given `sessionId` to a session file * * @param {string} sessionId * @param {Express.Session} session * @param {(err: any) => void} callback * * @memberOf FileStore */ set(sessionId: string, session: Express.Session, callback: (err: any) => void): void; /** * Touch the given session object associated with the given `sessionId` * * @param {string} sessionId * @param {Express.Session} session * @param {(err: any) => void} callback * * @memberOf FileStore */ touch(sessionId: string, session: Express.Session, callback: (err: any) => void): void; /** * Attempts to unlink a given session by its id * * @param {string} sessionId * @param {(err: any) => void} callback * * @memberOf FileStore */ destroy(sessionId: string, callback: (err: any) => void): void; /** * Attempts to fetch number of the session files * * @param {(err: any, length: number) => void} callback * * @memberOf FileStore */ length(callback: (err: any, length: number) => void): void; /** * Attempts to clear out all of the existing session files * * @param {(err: any) => void} callback * * @memberOf FileStore */ clear(callback: (err: any) => void): void; /** * * * @param {(err: any, files: Array<string>) => void} callback * * @memberOf FileStore */ list(callback: (err: any, files: string[]) => void): void; /** * Attempts to detect whether a session file is already expired or not * * @param {string} sessionId * @param {(errr: any, isExpired: boolean) => void} callback * * @memberOf FileStore */ expired(sessionId: string, callback: (errr: any, isExpired: boolean) => void): void; }
session-file-store/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.00032464994001202285, 0.00018168949463870376, 0.00016744903405196965, 0.00017008779104799032, 0.00003226640910725109 ]
{ "id": 2, "code_window": [ "/** Bootbox options available for prompt modals */\n", "interface BootboxPromptOptions extends BootboxBaseOptions {\n", "\ttitle: string;\n", "\tvalue?: string;\n", "\tinputType?: string;\n", "\tcallback: (result: string) => any;\n", "\tbuttons?: BootboxConfirmPromptButtonMap;\n", "}\n", "\n", "/** Bootbox options available when setting defaults for modals */\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tinputType?: \"text\" | \"textarea\" | \"email\" | \"select\" | \"checkbox\" | \"date\" | \"time\" | \"number\" | \"password\";\n" ], "file_path": "bootbox/index.d.ts", "type": "replace", "edit_start_line_idx": 42 }
// TypeScript Version: 2.1 import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class FaCompress extends React.Component<IconBaseProps, any> { }
react-icons/fa/compress.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/43b17712ece42a935deb1c6cc9b036366d88f7ae
[ 0.0001700107823126018, 0.0001700107823126018, 0.0001700107823126018, 0.0001700107823126018, 0 ]
{ "id": 0, "code_window": [ " * Assigns a style value to a style property for the given element.\n", " */\n", "export const setStyle: ApplyStylingFn =\n", " (renderer: Renderer3 | null, native: RElement, prop: string, value: string | null) => {\n", " if (renderer !== null) {\n", " if (value) {\n", " // opacity, z-index and flexbox all have number values\n", " // and these need to be converted into strings so that\n", " // they can be assigned properly.\n", " value = value.toString();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Use `isStylingValueDefined` to account for falsy values that should be bound like 0.\n", " if (isStylingValueDefined(value)) {\n" ], "file_path": "packages/core/src/render3/styling/bindings.ts", "type": "replace", "edit_start_line_idx": 728 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {SafeValue, unwrapSafeValue} from '../../sanitization/bypass'; import {StyleSanitizeFn, StyleSanitizeMode} from '../../sanitization/style_sanitizer'; import {ProceduralRenderer3, RElement, Renderer3, RendererStyleFlags3, isProceduralRenderer} from '../interfaces/renderer'; import {ApplyStylingFn, LStylingData, StylingMapArray, StylingMapArrayIndex, StylingMapsSyncMode, SyncStylingMapsFn, TStylingConfig, TStylingContext, TStylingContextIndex, TStylingContextPropConfigFlags} from '../interfaces/styling'; import {NO_CHANGE} from '../tokens'; import {DEFAULT_BINDING_INDEX, DEFAULT_BINDING_VALUE, DEFAULT_GUARD_MASK_VALUE, MAP_BASED_ENTRY_PROP_NAME, getBindingValue, getConfig, getDefaultValue, getGuardMask, getMapProp, getMapValue, getProp, getPropValuesStartPosition, getStylingMapArray, getTotalSources, getValue, getValuesCount, hasConfig, hasValueChanged, isContextLocked, isHostStylingActive, isSanitizationRequired, isStylingValueDefined, lockContext, patchConfig, setDefaultValue, setGuardMask, setMapAsDirty, setValue} from '../util/styling_utils'; import {getStylingState, resetStylingState} from './state'; /** * -------- * * This file contains the core logic for styling in Angular. * * All styling bindings (i.e. `[style]`, `[style.prop]`, `[class]` and `[class.name]`) * will have their values be applied through the logic in this file. * * When a binding is encountered (e.g. `<div [style.width]="w">`) then * the binding data will be populated into a `TStylingContext` data-structure. * There is only one `TStylingContext` per `TNode` and each element instance * will update its style/class binding values in concert with the styling * context. * * To learn more about the algorithm see `TStylingContext`. * * -------- */ /** * The guard/update mask bit index location for map-based bindings. * * All map-based bindings (i.e. `[style]` and `[class]` ) */ const STYLING_INDEX_FOR_MAP_BINDING = 0; /** * Visits a class-based binding and updates the new value (if changed). * * This function is called each time a class-based styling instruction * is executed. It's important that it's always called (even if the value * has not changed) so that the inner counter index value is incremented. * This way, each instruction is always guaranteed to get the same counter * state each time it's called (which then allows the `TStylingContext` * and the bit mask values to be in sync). */ export function updateClassViaContext( context: TStylingContext, data: LStylingData, element: RElement, directiveIndex: number, prop: string | null, bindingIndex: number, value: boolean | string | null | undefined | StylingMapArray | NO_CHANGE, forceUpdate?: boolean): boolean { const isMapBased = !prop; const state = getStylingState(element, directiveIndex); const countIndex = isMapBased ? STYLING_INDEX_FOR_MAP_BINDING : state.classesIndex++; if (value !== NO_CHANGE) { const updated = updateBindingData( context, data, countIndex, state.sourceIndex, prop, bindingIndex, value, forceUpdate, false); if (updated || forceUpdate) { // We flip the bit in the bitMask to reflect that the binding // at the `index` slot has changed. This identifies to the flushing // phase that the bindings for this particular CSS class need to be // applied again because on or more of the bindings for the CSS // class have changed. state.classesBitMask |= 1 << countIndex; return true; } } return false; } /** * Visits a style-based binding and updates the new value (if changed). * * This function is called each time a style-based styling instruction * is executed. It's important that it's always called (even if the value * has not changed) so that the inner counter index value is incremented. * This way, each instruction is always guaranteed to get the same counter * state each time it's called (which then allows the `TStylingContext` * and the bit mask values to be in sync). */ export function updateStyleViaContext( context: TStylingContext, data: LStylingData, element: RElement, directiveIndex: number, prop: string | null, bindingIndex: number, value: string | number | SafeValue | null | undefined | StylingMapArray | NO_CHANGE, sanitizer: StyleSanitizeFn | null, forceUpdate?: boolean): boolean { const isMapBased = !prop; const state = getStylingState(element, directiveIndex); const countIndex = isMapBased ? STYLING_INDEX_FOR_MAP_BINDING : state.stylesIndex++; if (value !== NO_CHANGE) { const sanitizationRequired = isMapBased ? true : (sanitizer ? sanitizer(prop !, null, StyleSanitizeMode.ValidateProperty) : false); const updated = updateBindingData( context, data, countIndex, state.sourceIndex, prop, bindingIndex, value, forceUpdate, sanitizationRequired); if (updated || forceUpdate) { // We flip the bit in the bitMask to reflect that the binding // at the `index` slot has changed. This identifies to the flushing // phase that the bindings for this particular property need to be // applied again because on or more of the bindings for the CSS // property have changed. state.stylesBitMask |= 1 << countIndex; return true; } } return false; } /** * Called each time a binding value has changed within the provided `TStylingContext`. * * This function is designed to be called from `updateStyleBinding` and `updateClassBinding`. * If called during the first update pass, the binding will be registered in the context. * * This function will also update binding slot in the provided `LStylingData` with the * new binding entry (if it has changed). * * @returns whether or not the binding value was updated in the `LStylingData`. */ function updateBindingData( context: TStylingContext, data: LStylingData, counterIndex: number, sourceIndex: number, prop: string | null, bindingIndex: number, value: string | SafeValue | number | boolean | null | undefined | StylingMapArray, forceUpdate?: boolean, sanitizationRequired?: boolean): boolean { const hostBindingsMode = isHostStylingActive(sourceIndex); if (!isContextLocked(context, hostBindingsMode)) { // this will only happen during the first update pass of the // context. The reason why we can't use `tNode.firstTemplatePass` // here is because its not guaranteed to be true when the first // update pass is executed (remember that all styling instructions // are run in the update phase, and, as a result, are no more // styling instructions that are run in the creation phase). registerBinding(context, counterIndex, sourceIndex, prop, bindingIndex, sanitizationRequired); patchConfig( context, hostBindingsMode ? TStylingConfig.HasHostBindings : TStylingConfig.HasTemplateBindings); patchConfig(context, prop ? TStylingConfig.HasPropBindings : TStylingConfig.HasMapBindings); } const changed = forceUpdate || hasValueChanged(data[bindingIndex], value); if (changed) { setValue(data, bindingIndex, value); const doSetValuesAsStale = (getConfig(context) & TStylingConfig.HasHostBindings) && !hostBindingsMode && (prop ? !value : true); if (doSetValuesAsStale) { renderHostBindingsAsStale(context, data, prop); } } return changed; } /** * Iterates over all host-binding values for the given `prop` value in the context and sets their * corresponding binding values to `null`. * * Whenever a template binding changes its value to `null`, all host-binding values should be * re-applied * to the element when the host bindings are evaluated. This may not always happen in the event * that none of the bindings changed within the host bindings code. For this reason this function * is expected to be called each time a template binding becomes falsy or when a map-based template * binding changes. */ function renderHostBindingsAsStale( context: TStylingContext, data: LStylingData, prop: string | null): void { const valuesCount = getValuesCount(context); if (prop !== null && hasConfig(context, TStylingConfig.HasPropBindings)) { const itemsPerRow = TStylingContextIndex.BindingsStartOffset + valuesCount; let i = TStylingContextIndex.ValuesStartPosition; let found = false; while (i < context.length) { if (getProp(context, i) === prop) { found = true; break; } i += itemsPerRow; } if (found) { const bindingsStart = i + TStylingContextIndex.BindingsStartOffset; const valuesStart = bindingsStart + 1; // the first column is template bindings const valuesEnd = bindingsStart + valuesCount - 1; for (let i = valuesStart; i < valuesEnd; i++) { const bindingIndex = context[i] as number; if (bindingIndex !== 0) { setValue(data, bindingIndex, null); } } } } if (hasConfig(context, TStylingConfig.HasMapBindings)) { const bindingsStart = TStylingContextIndex.ValuesStartPosition + TStylingContextIndex.BindingsStartOffset; const valuesStart = bindingsStart + 1; // the first column is template bindings const valuesEnd = bindingsStart + valuesCount - 1; for (let i = valuesStart; i < valuesEnd; i++) { const stylingMap = getValue<StylingMapArray>(data, context[i] as number); if (stylingMap) { setMapAsDirty(stylingMap); } } } } /** * Registers the provided binding (prop + bindingIndex) into the context. * * It is needed because it will either update or insert a styling property * into the context at the correct spot. * * When called, one of two things will happen: * * 1) If the property already exists in the context then it will just add * the provided `bindingValue` to the end of the binding sources region * for that particular property. * * - If the binding value is a number then it will be added as a new * binding index source next to the other binding sources for the property. * * - Otherwise, if the binding value is a string/boolean/null type then it will * replace the default value for the property if the default value is `null`. * * 2) If the property does not exist then it will be inserted into the context. * The styling context relies on all properties being stored in alphabetical * order, so it knows exactly where to store it. * * When inserted, a default `null` value is created for the property which exists * as the default value for the binding. If the bindingValue property is inserted * and it is either a string, number or null value then that will replace the default * value. * * Note that this function is also used for map-based styling bindings. They are treated * much the same as prop-based bindings, but, their property name value is set as `[MAP]`. */ export function registerBinding( context: TStylingContext, countId: number, sourceIndex: number, prop: string | null, bindingValue: number | null | string | boolean, sanitizationRequired?: boolean): void { let found = false; prop = prop || MAP_BASED_ENTRY_PROP_NAME; let totalSources = getTotalSources(context); // if a new source is detected then a new column needs to be allocated into // the styling context. The column is basically a new allocation of binding // sources that will be available to each property. while (totalSources <= sourceIndex) { addNewSourceColumn(context); totalSources++; } const isBindingIndexValue = typeof bindingValue === 'number'; const entriesPerRow = TStylingContextIndex.BindingsStartOffset + getValuesCount(context); let i = TStylingContextIndex.ValuesStartPosition; // all style/class bindings are sorted by property name while (i < context.length) { const p = getProp(context, i); if (prop <= p) { if (prop < p) { allocateNewContextEntry(context, i, prop, sanitizationRequired); } else if (isBindingIndexValue) { patchConfig(context, TStylingConfig.HasCollisions); } addBindingIntoContext(context, i, bindingValue, countId, sourceIndex); found = true; break; } i += entriesPerRow; } if (!found) { allocateNewContextEntry(context, context.length, prop, sanitizationRequired); addBindingIntoContext(context, i, bindingValue, countId, sourceIndex); } } /** * Inserts a new row into the provided `TStylingContext` and assigns the provided `prop` value as * the property entry. */ function allocateNewContextEntry( context: TStylingContext, index: number, prop: string, sanitizationRequired?: boolean): void { const config = sanitizationRequired ? TStylingContextPropConfigFlags.SanitizationRequired : TStylingContextPropConfigFlags.Default; context.splice( index, 0, config, // 1) config value DEFAULT_GUARD_MASK_VALUE, // 2) template bit mask DEFAULT_GUARD_MASK_VALUE, // 3) host bindings bit mask prop, // 4) prop value (e.g. `width`, `myClass`, etc...) ); index += 4; // the 4 values above // 5...) default binding index for the template value // depending on how many sources already exist in the context, // multiple default index entries may need to be inserted for // the new value in the context. const totalBindingsPerEntry = getTotalSources(context); for (let i = 0; i < totalBindingsPerEntry; i++) { context.splice(index, 0, DEFAULT_BINDING_INDEX); index++; } // 6) default binding value for the new entry context.splice(index, 0, DEFAULT_BINDING_VALUE); } /** * Inserts a new binding value into a styling property tuple in the `TStylingContext`. * * A bindingValue is inserted into a context during the first update pass * of a template or host bindings function. When this occurs, two things * happen: * * - If the bindingValue value is a number then it is treated as a bindingIndex * value (a index in the `LView`) and it will be inserted next to the other * binding index entries. * * - Otherwise the binding value will update the default value for the property * and this will only happen if the default value is `null`. */ function addBindingIntoContext( context: TStylingContext, index: number, bindingValue: number | string | boolean | null, bitIndex: number, sourceIndex: number) { if (typeof bindingValue === 'number') { const hostBindingsMode = isHostStylingActive(sourceIndex); const cellIndex = index + TStylingContextIndex.BindingsStartOffset + sourceIndex; context[cellIndex] = bindingValue; const updatedBitMask = getGuardMask(context, index, hostBindingsMode) | (1 << bitIndex); setGuardMask(context, index, updatedBitMask, hostBindingsMode); } else if (bindingValue !== null && getDefaultValue(context, index) === null) { setDefaultValue(context, index, bindingValue); } } /** * Registers a new column into the provided `TStylingContext`. * * If and when a new source is detected then a new column needs to * be allocated into the styling context. The column is basically * a new allocation of binding sources that will be available to each * property. * * Each column that exists in the styling context resembles a styling * source. A styling source an either be the template or one or more * components or directives all containing styling host bindings. */ function addNewSourceColumn(context: TStylingContext): void { // we use -1 here because we want to insert right before the last value (the default value) const insertOffset = TStylingContextIndex.BindingsStartOffset + getValuesCount(context) - 1; let index = TStylingContextIndex.ValuesStartPosition; while (index < context.length) { index += insertOffset; context.splice(index++, 0, DEFAULT_BINDING_INDEX); // the value was inserted just before the default value, but the // next entry in the context starts just after it. Therefore++. index++; } context[TStylingContextIndex.TotalSourcesPosition]++; } /** * Applies all pending style and class bindings to the provided element. * * This function will attempt to flush styling via the provided `classesContext` * and `stylesContext` context values. This function is designed to be run from * the internal `stylingApply` function (which is scheduled to run at the very * end of change detection for an element if one or more style/class bindings * were processed) and will rely on any state values that are set from when * any of the styling bindings executed. * * This function is designed to be called twice: one when change detection has * processed an element within the template bindings (i.e. just as `advance()` * is called) and when host bindings have been processed. In both cases the * styles and classes in both contexts will be applied to the element, but the * algorithm will selectively decide which bindings to run depending on the * columns in the context. The provided `directiveIndex` value will help the * algorithm determine which bindings to apply: either the template bindings or * the host bindings (see `applyStylingToElement` for more information). * * Note that once this function is called all temporary styling state data * (i.e. the `bitMask` and `counter` values for styles and classes will be cleared). */ export function flushStyling( renderer: Renderer3 | ProceduralRenderer3 | null, data: LStylingData, classesContext: TStylingContext | null, stylesContext: TStylingContext | null, element: RElement, directiveIndex: number, styleSanitizer: StyleSanitizeFn | null): void { ngDevMode && ngDevMode.flushStyling++; const state = getStylingState(element, directiveIndex); const hostBindingsMode = isHostStylingActive(state.sourceIndex); if (stylesContext) { if (!isContextLocked(stylesContext, hostBindingsMode)) { lockAndFinalizeContext(stylesContext, hostBindingsMode); } if (state.stylesBitMask !== 0) { applyStylingViaContext( stylesContext, renderer, element, data, state.stylesBitMask, setStyle, styleSanitizer, hostBindingsMode); } } if (classesContext) { if (!isContextLocked(classesContext, hostBindingsMode)) { lockAndFinalizeContext(classesContext, hostBindingsMode); } if (state.classesBitMask !== 0) { applyStylingViaContext( classesContext, renderer, element, data, state.classesBitMask, setClass, null, hostBindingsMode); } } resetStylingState(); } /** * Locks the context (so no more bindings can be added) and also copies over initial class/style * values into their binding areas. * * There are two main actions that take place in this function: * * - Locking the context: * Locking the context is required so that the style/class instructions know NOT to * register a binding again after the first update pass has run. If a locking bit was * not used then it would need to scan over the context each time an instruction is run * (which is expensive). * * - Patching initial values: * Directives and component host bindings may include static class/style values which are * bound to the host element. When this happens, the styling context will need to be informed * so it can use these static styling values as defaults when a matching binding is falsy. * These initial styling values are read from the initial styling values slot within the * provided `TStylingContext` (which is an instance of a `StylingMapArray`). This inner map will * be updated each time a host binding applies its static styling values (via `elementHostAttrs`) * so these values are only read at this point because this is the very last point before the * first style/class values are flushed to the element. * * Note that the `TStylingContext` styling context contains two locks: one for template bindings * and another for host bindings. Either one of these locks will be set when styling is applied * during the template binding flush and/or during the host bindings flush. */ function lockAndFinalizeContext(context: TStylingContext, hostBindingsMode: boolean): void { const initialValues = getStylingMapArray(context) !; updateInitialStylingOnContext(context, initialValues); lockContext(context, hostBindingsMode); } /** * Registers all initial styling entries into the provided context. * * This function will iterate over all entries in the provided `initialStyling` ar}ray and register * them as default (initial) values in the provided context. Initial styling values in a context are * the default values that are to be applied unless overwritten by a binding. * * The reason why this function exists and isn't a part of the context construction is because * host binding is evaluated at a later stage after the element is created. This means that * if a directive or component contains any initial styling code (i.e. `<div class="foo">`) * then that initial styling data can only be applied once the styling for that element * is first applied (at the end of the update phase). Once that happens then the context will * update itself with the complete initial styling for the element. */ function updateInitialStylingOnContext( context: TStylingContext, initialStyling: StylingMapArray): void { // `-1` is used here because all initial styling data is not a apart // of a binding (since it's static) const COUNT_ID_FOR_STYLING = -1; let hasInitialStyling = false; for (let i = StylingMapArrayIndex.ValuesStartPosition; i < initialStyling.length; i += StylingMapArrayIndex.TupleSize) { const value = getMapValue(initialStyling, i); if (value) { const prop = getMapProp(initialStyling, i); registerBinding(context, COUNT_ID_FOR_STYLING, 0, prop, value, false); hasInitialStyling = true; } } if (hasInitialStyling) { patchConfig(context, TStylingConfig.HasInitialStyling); } } /** * Runs through the provided styling context and applies each value to * the provided element (via the renderer) if one or more values are present. * * This function will iterate over all entries present in the provided * `TStylingContext` array (both prop-based and map-based bindings).- * * Each entry, within the `TStylingContext` array, is stored alphabetically * and this means that each prop/value entry will be applied in order * (so long as it is marked dirty in the provided `bitMask` value). * * If there are any map-based entries present (which are applied to the * element via the `[style]` and `[class]` bindings) then those entries * will be applied as well. However, the code for that is not a part of * this function. Instead, each time a property is visited, then the * code below will call an external function called `stylingMapsSyncFn` * and, if present, it will keep the application of styling values in * map-based bindings up to sync with the application of prop-based * bindings. * * Visit `styling/map_based_bindings.ts` to learn more about how the * algorithm works for map-based styling bindings. * * Note that this function is not designed to be called in isolation (use * the `flushStyling` function so that it can call this function for both * the styles and classes contexts). */ export function applyStylingViaContext( context: TStylingContext, renderer: Renderer3 | ProceduralRenderer3 | null, element: RElement, bindingData: LStylingData, bitMaskValue: number | boolean, applyStylingFn: ApplyStylingFn, sanitizer: StyleSanitizeFn | null, hostBindingsMode: boolean): void { const bitMask = normalizeBitMaskValue(bitMaskValue); let stylingMapsSyncFn: SyncStylingMapsFn|null = null; let applyAllValues = false; if (hasConfig(context, TStylingConfig.HasMapBindings)) { stylingMapsSyncFn = getStylingMapsSyncFn(); const mapsGuardMask = getGuardMask(context, TStylingContextIndex.ValuesStartPosition, hostBindingsMode); applyAllValues = (bitMask & mapsGuardMask) !== 0; } const valuesCount = getValuesCount(context); let totalBindingsToVisit = 1; let mapsMode = applyAllValues ? StylingMapsSyncMode.ApplyAllValues : StylingMapsSyncMode.TraverseValues; if (hostBindingsMode) { mapsMode |= StylingMapsSyncMode.RecurseInnerMaps; totalBindingsToVisit = valuesCount - 1; } let i = getPropValuesStartPosition(context); while (i < context.length) { const guardMask = getGuardMask(context, i, hostBindingsMode); if (bitMask & guardMask) { let valueApplied = false; const prop = getProp(context, i); const defaultValue = getDefaultValue(context, i); // Part 1: Visit the `[styling.prop]` value for (let j = 0; j < totalBindingsToVisit; j++) { const bindingIndex = getBindingValue(context, i, j) as number; if (!valueApplied && bindingIndex !== 0) { const value = getValue(bindingData, bindingIndex); if (isStylingValueDefined(value)) { const checkValueOnly = hostBindingsMode && j === 0; if (!checkValueOnly) { const finalValue = sanitizer && isSanitizationRequired(context, i) ? sanitizer(prop, value, StyleSanitizeMode.SanitizeOnly) : unwrapSafeValue(value); applyStylingFn(renderer, element, prop, finalValue, bindingIndex); } valueApplied = true; } } // Part 2: Visit the `[style]` or `[class]` map-based value if (stylingMapsSyncFn) { // determine whether or not to apply the target property or to skip it let mode = mapsMode | (valueApplied ? StylingMapsSyncMode.SkipTargetProp : StylingMapsSyncMode.ApplyTargetProp); // the first column in the context (when `j == 0`) is special-cased for // template bindings. If and when host bindings are being processed then // the first column will still be iterated over, but the values will only // be checked against (not applied). If and when this happens we need to // notify the map-based syncing code to know not to apply the values it // comes across in the very first map-based binding (which is also located // in column zero). if (hostBindingsMode && j === 0) { mode |= StylingMapsSyncMode.CheckValuesOnly; } const valueAppliedWithinMap = stylingMapsSyncFn( context, renderer, element, bindingData, j, applyStylingFn, sanitizer, mode, prop, defaultValue); valueApplied = valueApplied || valueAppliedWithinMap; } } // Part 3: apply the default value (e.g. `<div style="width:200">` => `200px` gets applied) // if the value has not yet been applied then a truthy value does not exist in the // prop-based or map-based bindings code. If and when this happens, just apply the // default value (even if the default value is `null`). if (!valueApplied) { applyStylingFn(renderer, element, prop, defaultValue); } } i += TStylingContextIndex.BindingsStartOffset + valuesCount; } // the map-based styling entries may have not applied all their // values. For this reason, one more call to the sync function // needs to be issued at the end. if (stylingMapsSyncFn) { if (hostBindingsMode) { mapsMode |= StylingMapsSyncMode.CheckValuesOnly; } stylingMapsSyncFn( context, renderer, element, bindingData, 0, applyStylingFn, sanitizer, mapsMode); } } /** * Applies the provided styling map to the element directly (without context resolution). * * This function is designed to be run from the styling instructions and will be called * automatically. This function is intended to be used for performance reasons in the * event that there is no need to apply styling via context resolution. * * See `allowDirectStylingApply`. * * @returns whether or not the styling map was applied to the element. */ export function applyStylingMapDirectly( renderer: any, context: TStylingContext, element: RElement, data: LStylingData, bindingIndex: number, map: StylingMapArray, applyFn: ApplyStylingFn, sanitizer?: StyleSanitizeFn | null, forceUpdate?: boolean): boolean { if (forceUpdate || hasValueChanged(data[bindingIndex], map)) { setValue(data, bindingIndex, map); for (let i = StylingMapArrayIndex.ValuesStartPosition; i < map.length; i += StylingMapArrayIndex.TupleSize) { const prop = getMapProp(map, i); const value = getMapValue(map, i); applyStylingValue(renderer, context, element, prop, value, applyFn, bindingIndex, sanitizer); } return true; } return false; } /** * Applies the provided styling prop/value to the element directly (without context resolution). * * This function is designed to be run from the styling instructions and will be called * automatically. This function is intended to be used for performance reasons in the * event that there is no need to apply styling via context resolution. * * See `allowDirectStylingApply`. * * @returns whether or not the prop/value styling was applied to the element. */ export function applyStylingValueDirectly( renderer: any, context: TStylingContext, element: RElement, data: LStylingData, bindingIndex: number, prop: string, value: any, applyFn: ApplyStylingFn, sanitizer?: StyleSanitizeFn | null): boolean { if (hasValueChanged(data[bindingIndex], value)) { setValue(data, bindingIndex, value); applyStylingValue(renderer, context, element, prop, value, applyFn, bindingIndex, sanitizer); return true; } return false; } function applyStylingValue( renderer: any, context: TStylingContext, element: RElement, prop: string, value: any, applyFn: ApplyStylingFn, bindingIndex: number, sanitizer?: StyleSanitizeFn | null) { let valueToApply: string|null = unwrapSafeValue(value); if (isStylingValueDefined(valueToApply)) { valueToApply = sanitizer ? sanitizer(prop, value, StyleSanitizeMode.SanitizeOnly) : valueToApply; } else if (hasConfig(context, TStylingConfig.HasInitialStyling)) { const initialStyles = getStylingMapArray(context); if (initialStyles) { valueToApply = findInitialStylingValue(initialStyles, prop); } } applyFn(renderer, element, prop, valueToApply, bindingIndex); } function findInitialStylingValue(map: StylingMapArray, prop: string): string|null { for (let i = StylingMapArrayIndex.ValuesStartPosition; i < map.length; i += StylingMapArrayIndex.TupleSize) { const p = getMapProp(map, i); if (p >= prop) { return p === prop ? getMapValue(map, i) : null; } } return null; } function normalizeBitMaskValue(value: number | boolean): number { // if pass => apply all values (-1 implies that all bits are flipped to true) if (value === true) return -1; // if pass => skip all values if (value === false) return 0; // return the bit mask value as is return value; } let _activeStylingMapApplyFn: SyncStylingMapsFn|null = null; export function getStylingMapsSyncFn() { return _activeStylingMapApplyFn; } export function setStylingMapsSyncFn(fn: SyncStylingMapsFn) { _activeStylingMapApplyFn = fn; } /** * Assigns a style value to a style property for the given element. */ export const setStyle: ApplyStylingFn = (renderer: Renderer3 | null, native: RElement, prop: string, value: string | null) => { if (renderer !== null) { if (value) { // opacity, z-index and flexbox all have number values // and these need to be converted into strings so that // they can be assigned properly. value = value.toString(); ngDevMode && ngDevMode.rendererSetStyle++; if (isProceduralRenderer(renderer)) { renderer.setStyle(native, prop, value, RendererStyleFlags3.DashCase); } else { // The reason why native style may be `null` is either because // it's a container element or it's a part of a test // environment that doesn't have styling. In either // case it's safe not to apply styling to the element. const nativeStyle = native.style; if (nativeStyle != null) { nativeStyle.setProperty(prop, value); } } } else { ngDevMode && ngDevMode.rendererRemoveStyle++; if (isProceduralRenderer(renderer)) { renderer.removeStyle(native, prop, RendererStyleFlags3.DashCase); } else { const nativeStyle = native.style; if (nativeStyle != null) { nativeStyle.removeProperty(prop); } } } } }; /** * Adds/removes the provided className value to the provided element. */ export const setClass: ApplyStylingFn = (renderer: Renderer3 | null, native: RElement, className: string, value: any) => { if (renderer !== null && className !== '') { if (value) { ngDevMode && ngDevMode.rendererAddClass++; if (isProceduralRenderer(renderer)) { renderer.addClass(native, className); } else { // the reason why classList may be `null` is either because // it's a container element or it's a part of a test // environment that doesn't have styling. In either // case it's safe not to apply styling to the element. const classList = native.classList; if (classList != null) { classList.add(className); } } } else { ngDevMode && ngDevMode.rendererRemoveClass++; if (isProceduralRenderer(renderer)) { renderer.removeClass(native, className); } else { const classList = native.classList; if (classList != null) { classList.remove(className); } } } } }; /** * Iterates over all provided styling entries and renders them on the element. * * This function is used alongside a `StylingMapArray` entry. This entry is not * the same as the `TStylingContext` and is only really used when an element contains * initial styling values (e.g. `<div style="width:200px">`), but no style/class bindings * are present. If and when that happens then this function will be called to render all * initial styling values on an element. */ export function renderStylingMap( renderer: Renderer3, element: RElement, stylingValues: TStylingContext | StylingMapArray | null, isClassBased: boolean): void { const stylingMapArr = getStylingMapArray(stylingValues); if (stylingMapArr) { for (let i = StylingMapArrayIndex.ValuesStartPosition; i < stylingMapArr.length; i += StylingMapArrayIndex.TupleSize) { const prop = getMapProp(stylingMapArr, i); const value = getMapValue(stylingMapArr, i); if (isClassBased) { setClass(renderer, element, prop, value, null); } else { setStyle(renderer, element, prop, value, null); } } } }
packages/core/src/render3/styling/bindings.ts
1
https://github.com/angular/angular/commit/3efb060127f6cd7c54590f5c1a6c2d3eaf9e2f04
[ 0.9983577132225037, 0.09607869386672974, 0.00015836161037441343, 0.0001913114101625979, 0.2697928845882416 ]
{ "id": 0, "code_window": [ " * Assigns a style value to a style property for the given element.\n", " */\n", "export const setStyle: ApplyStylingFn =\n", " (renderer: Renderer3 | null, native: RElement, prop: string, value: string | null) => {\n", " if (renderer !== null) {\n", " if (value) {\n", " // opacity, z-index and flexbox all have number values\n", " // and these need to be converted into strings so that\n", " // they can be assigned properly.\n", " value = value.toString();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Use `isStylingValueDefined` to account for falsy values that should be bound like 0.\n", " if (isStylingValueDefined(value)) {\n" ], "file_path": "packages/core/src/render3/styling/bindings.ts", "type": "replace", "edit_start_line_idx": 728 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['meia-noite', 'meio-dia', 'manhã', 'tarde', 'noite', 'madrugada'], ['meia-noite', 'meio-dia', 'da manhã', 'da tarde', 'da noite', 'da madrugada'], u ], [['meia-noite', 'meio-dia', 'manhã', 'tarde', 'noite', 'madrugada'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '19:00'], ['19:00', '24:00'], ['00:00', '06:00'] ] ];
packages/common/locales/extra/pt-GW.ts
0
https://github.com/angular/angular/commit/3efb060127f6cd7c54590f5c1a6c2d3eaf9e2f04
[ 0.00017397059127688408, 0.00017109203326981515, 0.00016730889910832047, 0.00017199659487232566, 0.0000027938285711570643 ]