InitClient creates and configures a new client with authentication, telemetry, and version checks.
(inv *serpent.Invocation)
| 672 | // InitClient creates and configures a new client with authentication, telemetry, |
| 673 | // and version checks. |
| 674 | func (r *RootCmd) InitClient(inv *serpent.Invocation) (*codersdk.Client, error) { |
| 675 | if err := r.ensureClientURL(); err != nil { |
| 676 | return nil, err |
| 677 | } |
| 678 | if r.token == "" { |
| 679 | tok, err := r.ensureTokenBackend().Read(r.clientURL) |
| 680 | // Even if there isn't a token, we don't care. |
| 681 | // Some API routes can be unauthenticated. |
| 682 | if err != nil && !xerrors.Is(err, os.ErrNotExist) { |
| 683 | if xerrors.Is(err, sessionstore.ErrNotImplemented) { |
| 684 | return nil, errKeyringNotSupported |
| 685 | } |
| 686 | return nil, err |
| 687 | } |
| 688 | if tok != "" { |
| 689 | r.token = tok |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | // Load TLS config from files if specified |
| 694 | if err := r.ensureTLSConfig(); err != nil { |
| 695 | return nil, err |
| 696 | } |
| 697 | |
| 698 | // Configure HTTP client with transport wrappers |
| 699 | httpClient, err := r.createHTTPClient(inv.Context(), r.clientURL, inv) |
| 700 | if err != nil { |
| 701 | return nil, err |
| 702 | } |
| 703 | |
| 704 | clientOpts := []codersdk.ClientOption{ |
| 705 | codersdk.WithSessionToken(r.token), |
| 706 | codersdk.WithHTTPClient(httpClient), |
| 707 | } |
| 708 | |
| 709 | if r.disableDirect { |
| 710 | clientOpts = append(clientOpts, codersdk.WithDisableDirectConnections()) |
| 711 | } |
| 712 | |
| 713 | if r.tlsConfig != nil { |
| 714 | clientOpts = append(clientOpts, codersdk.WithDERPTLSConfig(r.tlsConfig)) |
| 715 | } |
| 716 | |
| 717 | if r.debugHTTP { |
| 718 | clientOpts = append(clientOpts, |
| 719 | codersdk.WithPlainLogger(os.Stderr), |
| 720 | codersdk.WithLogBodies(), |
| 721 | ) |
| 722 | } |
| 723 | |
| 724 | return codersdk.New(r.clientURL, clientOpts...), nil |
| 725 | } |
| 726 | |
| 727 | // TryInitClient is similar to InitClient but doesn't error when credentials are missing. |
| 728 | // This allows commands to run without requiring authentication, but still use auth if available. |
no test coverage detected