Multi Package Wrap Errors (#414)

This commit is contained in:
Lars Lehtonen 2023-09-18 05:53:49 -07:00 committed by GitHub
parent f9e4bd0211
commit b65a5fd7a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 172 additions and 172 deletions

View File

@ -161,9 +161,9 @@ func Retry(ctx context.Context, f func() error) error {
// Check if we have a context error to check if we're interrupted or timeout
switch ctx.Err() {
case context.Canceled:
return fmt.Errorf("interrupted - last error: %v", lastErr)
return fmt.Errorf("interrupted - last error: %w", lastErr)
case context.DeadlineExceeded:
return fmt.Errorf("timeout - last error: %v", lastErr)
return fmt.Errorf("timeout - last error: %w", lastErr)
}
if lastErr != nil {

View File

@ -447,7 +447,7 @@ func (c *Communicator) UploadScript(path string, input io.Reader) error {
reader := bufio.NewReader(input)
prefix, err := reader.Peek(2)
if err != nil {
return fmt.Errorf("Error reading script: %s", err)
return fmt.Errorf("Error reading script: %w", err)
}
var script bytes.Buffer
@ -634,7 +634,7 @@ func checkSCPStatus(r *bufio.Reader) error {
// Treat any non-zero (really 1 and 2) as fatal errors
message, _, err := r.ReadLine()
if err != nil {
return fmt.Errorf("Error reading error message: %s", err)
return fmt.Errorf("Error reading error message: %w", err)
}
return errors.New(string(message))
@ -655,7 +655,7 @@ func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, size
// so that we can determine the length, since SCP is length-prefixed.
tf, err := os.CreateTemp("", "terraform-upload")
if err != nil {
return fmt.Errorf("Error creating temporary file for upload: %s", err)
return fmt.Errorf("Error creating temporary file for upload: %w", err)
}
defer os.Remove(tf.Name())
defer tf.Close()
@ -668,17 +668,17 @@ func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, size
// Sync the file so that the contents are definitely on disk, then
// read the length of it.
if err := tf.Sync(); err != nil {
return fmt.Errorf("Error creating temporary file for upload: %s", err)
return fmt.Errorf("Error creating temporary file for upload: %w", err)
}
// Seek the file to the beginning so we can re-read all of it
if _, err := tf.Seek(0, 0); err != nil {
return fmt.Errorf("Error creating temporary file for upload: %s", err)
return fmt.Errorf("Error creating temporary file for upload: %w", err)
}
fi, err := tf.Stat()
if err != nil {
return fmt.Errorf("Error creating temporary file for upload: %s", err)
return fmt.Errorf("Error creating temporary file for upload: %w", err)
}
src = tf
@ -842,13 +842,13 @@ func BastionConnectFunc(
pConn, err = newHttpProxyConn(p, bAddr)
if err != nil {
return nil, fmt.Errorf("Error connecting to proxy: %s", err)
return nil, fmt.Errorf("Error connecting to proxy: %w", err)
}
bConn, bChans, bReq, err = ssh.NewClientConn(pConn, bAddr, bConf)
if err != nil {
return nil, fmt.Errorf("Error creating new client connection via proxy: %s", err)
return nil, fmt.Errorf("Error creating new client connection via proxy: %w", err)
}
bastion = ssh.NewClient(bConn, bChans, bReq)
@ -857,7 +857,7 @@ func BastionConnectFunc(
}
if err != nil {
return nil, fmt.Errorf("Error connecting to bastion: %s", err)
return nil, fmt.Errorf("Error connecting to bastion: %w", err)
}
log.Printf("[DEBUG] Connecting via bastion (%s) to host: %s", bAddr, addr)

View File

@ -335,7 +335,7 @@ func buildSSHClientConfig(opts sshClientConfigOpts) (*ssh.ClientConfig, error) {
// file to create the HostKeyCallback.
tf, err := os.CreateTemp("", "tf-known_hosts")
if err != nil {
return nil, fmt.Errorf("failed to create temp known_hosts file: %s", err)
return nil, fmt.Errorf("failed to create temp known_hosts file: %w", err)
}
defer tf.Close()
defer os.RemoveAll(tf.Name())
@ -344,7 +344,7 @@ func buildSSHClientConfig(opts sshClientConfigOpts) (*ssh.ClientConfig, error) {
// use it as a direct match if the remote host doesn't return a
// certificate.
if _, err := tf.WriteString(fmt.Sprintf("@cert-authority %s %s\n", opts.host, opts.hostKey)); err != nil {
return nil, fmt.Errorf("failed to write temp known_hosts file: %s", err)
return nil, fmt.Errorf("failed to write temp known_hosts file: %w", err)
}
tf.Sync()
@ -396,22 +396,22 @@ func buildSSHClientConfig(opts sshClientConfigOpts) (*ssh.ClientConfig, error) {
func signCertWithPrivateKey(pk string, certificate string) (ssh.AuthMethod, error) {
rawPk, err := ssh.ParseRawPrivateKey([]byte(pk))
if err != nil {
return nil, fmt.Errorf("failed to parse private key %q: %s", pk, err)
return nil, fmt.Errorf("failed to parse private key %q: %w", pk, err)
}
pcert, _, _, _, err := ssh.ParseAuthorizedKey([]byte(certificate))
if err != nil {
return nil, fmt.Errorf("failed to parse certificate %q: %s", certificate, err)
return nil, fmt.Errorf("failed to parse certificate %q: %w", certificate, err)
}
usigner, err := ssh.NewSignerFromKey(rawPk)
if err != nil {
return nil, fmt.Errorf("failed to create signer from raw private key %q: %s", rawPk, err)
return nil, fmt.Errorf("failed to create signer from raw private key %q: %w", rawPk, err)
}
ucertSigner, err := ssh.NewCertSigner(pcert.(*ssh.Certificate), usigner)
if err != nil {
return nil, fmt.Errorf("failed to create cert signer %q: %s", usigner, err)
return nil, fmt.Errorf("failed to create cert signer %q: %w", usigner, err)
}
return ssh.PublicKeys(ucertSigner), nil
@ -432,7 +432,7 @@ func readPrivateKey(pk string) (ssh.AuthMethod, error) {
signer, err := ssh.ParsePrivateKey([]byte(pk))
if err != nil {
return nil, fmt.Errorf("Failed to parse ssh private key: %s", err)
return nil, fmt.Errorf("Failed to parse ssh private key: %w", err)
}
return ssh.PublicKeys(signer), nil

View File

@ -68,7 +68,7 @@ func NewLoader(config *Config) (*Loader, error) {
err := ret.modules.readModuleManifestSnapshot()
if err != nil {
return nil, fmt.Errorf("failed to read module manifest: %s", err)
return nil, fmt.Errorf("failed to read module manifest: %w", err)
}
return ret, nil

View File

@ -197,7 +197,7 @@ func hcl2ValueFromFlatmapPrimitive(m map[string]string, key string, ty cty.Type)
if err != nil {
// This should never happen for _valid_ input, but flatmap data might
// be tampered with by the user and become invalid.
return cty.DynamicVal, fmt.Errorf("invalid value for %q in state: %s", key, err)
return cty.DynamicVal, fmt.Errorf("invalid value for %q in state: %w", key, err)
}
return val, nil
@ -234,7 +234,7 @@ func hcl2ValueFromFlatmapTuple(m map[string]string, prefix string, etys []cty.Ty
count, err := strconv.Atoi(countStr)
if err != nil {
return cty.DynamicVal, fmt.Errorf("invalid count value for %q in state: %s", prefix, err)
return cty.DynamicVal, fmt.Errorf("invalid count value for %q in state: %w", prefix, err)
}
if count != len(etys) {
return cty.DynamicVal, fmt.Errorf("wrong number of values for %q in state: got %d, but need %d", prefix, count, len(etys))
@ -319,7 +319,7 @@ func hcl2ValueFromFlatmapList(m map[string]string, prefix string, ty cty.Type) (
count, err := strconv.Atoi(countStr)
if err != nil {
return cty.DynamicVal, fmt.Errorf("invalid count value for %q in state: %s", prefix, err)
return cty.DynamicVal, fmt.Errorf("invalid count value for %q in state: %w", prefix, err)
}
ety := ty.ElementType()

View File

@ -90,7 +90,7 @@ func requiresReplacePath(k string, ty cty.Type) (cty.Path, error) {
path, err := pathFromFlatmapKeyObject(k, ty.AttributeTypes())
if err != nil {
return path, fmt.Errorf("[%s] %s", k, err)
return path, fmt.Errorf("[%s] %w", k, err)
}
return path, nil
}

View File

@ -192,7 +192,7 @@ func (b *binary) StateFromFile(filename string) (*states.State, error) {
stateFile, err := statefile.Read(f)
if err != nil {
return nil, fmt.Errorf("Error reading statefile: %s", err)
return nil, fmt.Errorf("Error reading statefile: %w", err)
}
return stateFile.State, nil
}
@ -220,7 +220,7 @@ func (b *binary) SetLocalState(state *states.State) error {
path := b.Path("terraform.tfstate")
f, err := os.OpenFile(path, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to create temporary state file %s: %s", path, err)
return fmt.Errorf("failed to create temporary state file %s: %w", path, err)
}
defer f.Close()

View File

@ -131,11 +131,11 @@ func (g reusingGetter) getWithGoGetter(ctx context.Context, instPath, packageAdd
log.Printf("[TRACE] getmodules: copying previous install of %q from %s to %s", packageAddr, prevDir, instPath)
err := os.Mkdir(instPath, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to create directory %s: %s", instPath, err)
return fmt.Errorf("failed to create directory %s: %w", instPath, err)
}
err = copy.CopyDir(instPath, prevDir)
if err != nil {
return fmt.Errorf("failed to copy from %s to %s: %s", prevDir, instPath, err)
return fmt.Errorf("failed to copy from %s to %s: %w", prevDir, instPath, err)
}
} else {
log.Printf("[TRACE] getmodules: fetching %q to %q", packageAddr, instPath)

View File

@ -47,7 +47,7 @@ func SearchLocalDirectory(baseDir string) (map[addrs.Provider]PackageMetaList, e
err := filepath.Walk(baseDir, func(fullPath string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("cannot search %s: %s", fullPath, err)
return fmt.Errorf("cannot search %s: %w", fullPath, err)
}
// There are two valid directory structures that we support here...

View File

@ -124,7 +124,7 @@ func (s *HTTPMirrorSource) AvailableVersions(ctx context.Context, provider addrs
dec := json.NewDecoder(body)
if err := dec.Decode(&bodyContent); err != nil {
return nil, nil, s.errQueryFailed(provider, fmt.Errorf("invalid response content from mirror server: %s", err))
return nil, nil, s.errQueryFailed(provider, fmt.Errorf("invalid response content from mirror server: %w", err))
}
if len(bodyContent.Versions) == 0 {
@ -192,7 +192,7 @@ func (s *HTTPMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provi
dec := json.NewDecoder(body)
if err := dec.Decode(&bodyContent); err != nil {
return PackageMeta{}, s.errQueryFailed(provider, fmt.Errorf("invalid response content from mirror server: %s", err))
return PackageMeta{}, s.errQueryFailed(provider, fmt.Errorf("invalid response content from mirror server: %w", err))
}
archiveMeta, ok := bodyContent.Archives[target.String()]
@ -209,7 +209,7 @@ func (s *HTTPMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provi
if err != nil {
return PackageMeta{}, s.errQueryFailed(
provider,
fmt.Errorf("provider mirror returned invalid URL %q: %s", archiveMeta.RelativeURL, err),
fmt.Errorf("provider mirror returned invalid URL %q: %w", archiveMeta.RelativeURL, err),
)
}
absURL := finalURL.ResolveReference(relURL)
@ -231,7 +231,7 @@ func (s *HTTPMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provi
if err != nil {
return PackageMeta{}, s.errQueryFailed(
provider,
fmt.Errorf("provider mirror returned invalid provider hash %q: %s", hashStr, err),
fmt.Errorf("provider mirror returned invalid provider hash %q: %w", hashStr, err),
)
}
hashes = append(hashes, hash)
@ -267,7 +267,7 @@ func (s *HTTPMirrorSource) mirrorHost() (svchost.Hostname, error) {
func (s *HTTPMirrorSource) mirrorHostCredentials() (svcauth.HostCredentials, error) {
hostname, err := s.mirrorHost()
if err != nil {
return nil, fmt.Errorf("invalid provider mirror base URL %s: %s", s.baseURL.String(), err)
return nil, fmt.Errorf("invalid provider mirror base URL %s: %w", s.baseURL.String(), err)
}
if s.creds == nil {
@ -304,7 +304,7 @@ func (s *HTTPMirrorSource) get(ctx context.Context, relativePath string) (status
req.Request.Header.Set(terraformVersionHeader, version.String())
creds, err := s.mirrorHostCredentials()
if err != nil {
return 0, nil, endpointURL, fmt.Errorf("failed to determine request credentials: %s", err)
return 0, nil, endpointURL, fmt.Errorf("failed to determine request credentials: %w", err)
}
if creds != nil {
// Note that if the initial requests gets redirected elsewhere
@ -340,7 +340,7 @@ func (s *HTTPMirrorSource) get(ctx context.Context, relativePath string) (status
ct := resp.Header.Get("Content-Type")
mt, params, err := mime.ParseMediaType(ct)
if err != nil {
return 0, nil, finalURL, fmt.Errorf("response has invalid Content-Type: %s", err)
return 0, nil, finalURL, fmt.Errorf("response has invalid Content-Type: %w", err)
}
if mt != "application/json" {
return 0, nil, finalURL, fmt.Errorf("response has invalid Content-Type: must be application/json")

View File

@ -158,7 +158,7 @@ func ParseMultiSourceMatchingPatterns(strs []string) (MultiSourceMatchingPattern
} else {
normalHost, err := svchost.ForComparison(givenHost)
if err != nil {
return nil, fmt.Errorf("invalid hostname in provider matching pattern %q: %s", str, err)
return nil, fmt.Errorf("invalid hostname in provider matching pattern %q: %w", str, err)
}
// The remaining code below deals only with the namespace/type portions.

View File

@ -227,7 +227,7 @@ func (a packageHashAuthentication) AuthenticatePackage(localLocation PackageLoca
matches, err := PackageMatchesAnyHash(localLocation, a.RequiredHashes)
if err != nil {
return nil, fmt.Errorf("failed to verify provider package checksums: %s", err)
return nil, fmt.Errorf("failed to verify provider package checksums: %w", err)
}
if matches {
@ -286,7 +286,7 @@ func (a archiveHashAuthentication) AuthenticatePackage(localLocation PackageLoca
gotHash, err := PackageHashLegacyZipSHA(archiveLocation)
if err != nil {
return nil, fmt.Errorf("failed to compute checksum for %s: %s", archiveLocation, err)
return nil, fmt.Errorf("failed to compute checksum for %s: %w", archiveLocation, err)
}
wantHash := HashLegacyZipSHAFromSHA(a.WantSHA256Sum)
if gotHash != wantHash {
@ -342,7 +342,7 @@ func (m matchingChecksumAuthentication) AuthenticatePackage(location PackageLoca
// Decode the ASCII checksum into a byte array for comparison.
var gotSHA256Sum [sha256.Size]byte
if _, err := hex.Decode(gotSHA256Sum[:], checksum); err != nil {
return nil, fmt.Errorf("checksum list has invalid SHA256 hash %q: %s", string(checksum), err)
return nil, fmt.Errorf("checksum list has invalid SHA256 hash %q: %w", string(checksum), err)
}
// If the checksums don't match, authentication fails.
@ -406,7 +406,7 @@ func (s signatureAuthentication) shouldEnforceGPGValidation() (bool, error) {
func (s signatureAuthentication) AuthenticatePackage(location PackageLocation) (*PackageAuthenticationResult, error) {
shouldValidate, err := s.shouldEnforceGPGValidation()
if err != nil {
return nil, fmt.Errorf("error determining if GPG validation should be enforced for pacakage %s: %s", location.String(), err.Error())
return nil, fmt.Errorf("error determining if GPG validation should be enforced for pacakage %s: %w", location.String(), err)
}
if !shouldValidate {
@ -488,7 +488,7 @@ func (s signatureAuthentication) findSigningKey() (*SigningKey, string, error) {
for _, key := range s.Keys {
keyring, err := openpgp.ReadArmoredKeyRing(strings.NewReader(key.ASCIIArmor))
if err != nil {
return nil, "", fmt.Errorf("error decoding signing key: %s", err)
return nil, "", fmt.Errorf("error decoding signing key: %w", err)
}
entity, err := openpgp.CheckDetachedSignature(keyring, bytes.NewReader(s.Document), bytes.NewReader(s.Signature), openpgpConfig)
@ -501,7 +501,7 @@ func (s signatureAuthentication) findSigningKey() (*SigningKey, string, error) {
// Any other signature error is terminal.
if err != nil {
return nil, "", fmt.Errorf("error checking signature: %s", err)
return nil, "", fmt.Errorf("error checking signature: %w", err)
}
keyID := "n/a"

View File

@ -243,7 +243,7 @@ func (c *registryClient) PackageMeta(ctx context.Context, provider addrs.Provide
if err != nil {
return PackageMeta{}, c.errQueryFailed(
provider,
fmt.Errorf("registry response includes invalid version string %q: %s", versionStr, err),
fmt.Errorf("registry response includes invalid version string %q: %w", versionStr, err),
)
}
protoVersions = append(protoVersions, v)
@ -282,7 +282,7 @@ func (c *registryClient) PackageMeta(ctx context.Context, provider addrs.Provide
downloadURL, err := url.Parse(body.DownloadURL)
if err != nil {
return PackageMeta{}, fmt.Errorf("registry response includes invalid download URL: %s", err)
return PackageMeta{}, fmt.Errorf("registry response includes invalid download URL: %w", err)
}
downloadURL = resp.Request.URL.ResolveReference(downloadURL)
if downloadURL.Scheme != "http" && downloadURL.Scheme != "https" {
@ -305,7 +305,7 @@ func (c *registryClient) PackageMeta(ctx context.Context, provider addrs.Provide
if len(body.SHA256Sum) != sha256.Size*2 { // *2 because it's hex-encoded
return PackageMeta{}, c.errQueryFailed(
provider,
fmt.Errorf("registry response includes invalid SHA256 hash %q: %s", body.SHA256Sum, err),
fmt.Errorf("registry response includes invalid SHA256 hash %q: %w", body.SHA256Sum, err),
)
}
@ -314,13 +314,13 @@ func (c *registryClient) PackageMeta(ctx context.Context, provider addrs.Provide
if err != nil {
return PackageMeta{}, c.errQueryFailed(
provider,
fmt.Errorf("registry response includes invalid SHA256 hash %q: %s", body.SHA256Sum, err),
fmt.Errorf("registry response includes invalid SHA256 hash %q: %w", body.SHA256Sum, err),
)
}
shasumsURL, err := url.Parse(body.SHA256SumsURL)
if err != nil {
return PackageMeta{}, fmt.Errorf("registry response includes invalid SHASUMS URL: %s", err)
return PackageMeta{}, fmt.Errorf("registry response includes invalid SHASUMS URL: %w", err)
}
shasumsURL = resp.Request.URL.ResolveReference(shasumsURL)
if shasumsURL.Scheme != "http" && shasumsURL.Scheme != "https" {
@ -330,12 +330,12 @@ func (c *registryClient) PackageMeta(ctx context.Context, provider addrs.Provide
if err != nil {
return PackageMeta{}, c.errQueryFailed(
provider,
fmt.Errorf("failed to retrieve authentication checksums for provider: %s", err),
fmt.Errorf("failed to retrieve authentication checksums for provider: %w", err),
)
}
signatureURL, err := url.Parse(body.SHA256SumsSignatureURL)
if err != nil {
return PackageMeta{}, fmt.Errorf("registry response includes invalid SHASUMS signature URL: %s", err)
return PackageMeta{}, fmt.Errorf("registry response includes invalid SHASUMS signature URL: %w", err)
}
signatureURL = resp.Request.URL.ResolveReference(signatureURL)
if signatureURL.Scheme != "http" && signatureURL.Scheme != "https" {
@ -345,7 +345,7 @@ func (c *registryClient) PackageMeta(ctx context.Context, provider addrs.Provide
if err != nil {
return PackageMeta{}, c.errQueryFailed(
provider,
fmt.Errorf("failed to retrieve cryptographic signature for provider: %s", err),
fmt.Errorf("failed to retrieve cryptographic signature for provider: %w", err),
)
}
@ -378,7 +378,7 @@ func (c *registryClient) findClosestProtocolCompatibleVersion(ctx context.Contex
if err != nil {
return UnspecifiedVersion, ErrQueryFailed{
Provider: provider,
Wrapped: fmt.Errorf("registry response includes invalid version string %q: %s", versionStr, err),
Wrapped: fmt.Errorf("registry response includes invalid version string %q: %w", versionStr, err),
}
}
versionList = append(versionList, v)
@ -394,7 +394,7 @@ FindMatch:
if err != nil {
return UnspecifiedVersion, ErrQueryFailed{
Provider: provider,
Wrapped: fmt.Errorf("registry response includes invalid protocol string %q: %s", protoStr, err),
Wrapped: fmt.Errorf("registry response includes invalid protocol string %q: %w", protoStr, err),
}
}
if protoVersions.Has(p) {

View File

@ -70,7 +70,7 @@ func (s *RegistrySource) AvailableVersions(ctx context.Context, provider addrs.P
if err != nil {
return nil, nil, ErrQueryFailed{
Provider: provider,
Wrapped: fmt.Errorf("registry response includes invalid version string %q: %s", str, err),
Wrapped: fmt.Errorf("registry response includes invalid version string %q: %w", str, err),
}
}
ret = append(ret, v)
@ -142,7 +142,7 @@ func (s *RegistrySource) registryClient(hostname svchost.Hostname) (*registryCli
// This indicates that a credentials helper failed, which means we
// can't do anything better than just pass through the helper's
// own error message.
return nil, fmt.Errorf("failed to retrieve credentials for %s: %s", hostname, err)
return nil, fmt.Errorf("failed to retrieve credentials for %s: %w", hostname, err)
}
return newRegistryClient(url, creds), nil

View File

@ -84,14 +84,14 @@ func ReadManifestSnapshot(r io.Reader) (Manifest, error) {
var read manifestSnapshotFile
err = json.Unmarshal(src, &read)
if err != nil {
return nil, fmt.Errorf("error unmarshalling snapshot: %v", err)
return nil, fmt.Errorf("error unmarshalling snapshot: %w", err)
}
new := make(Manifest)
for _, record := range read.Records {
if record.VersionStr != "" {
record.Version, err = version.NewVersion(record.VersionStr)
if err != nil {
return nil, fmt.Errorf("invalid version %q for %s: %s", record.VersionStr, record.Key, err)
return nil, fmt.Errorf("invalid version %q for %s: %w", record.VersionStr, record.Key, err)
}
}

View File

@ -79,13 +79,13 @@ func (cp *contextPlugins) ProviderSchema(addr addrs.Provider) (providers.Provide
provider, err := cp.NewProviderInstance(addr)
if err != nil {
return schemas, fmt.Errorf("failed to instantiate provider %q to obtain schema: %s", addr, err)
return schemas, fmt.Errorf("failed to instantiate provider %q to obtain schema: %w", addr, err)
}
defer provider.Close()
resp := provider.GetProviderSchema()
if resp.Diagnostics.HasErrors() {
return resp, fmt.Errorf("failed to retrieve schema from provider %q: %s", addr, resp.Diagnostics.Err())
return resp, fmt.Errorf("failed to retrieve schema from provider %q: %w", addr, resp.Diagnostics.Err())
}
if resp.Provider.Version < 0 {
@ -96,7 +96,7 @@ func (cp *contextPlugins) ProviderSchema(addr addrs.Provider) (providers.Provide
for t, r := range resp.ResourceTypes {
if err := r.Block.InternalValidate(); err != nil {
return resp, fmt.Errorf("provider %s has invalid schema for managed resource type %q, which is a bug in the provider: %q", addr, t, err)
return resp, fmt.Errorf("provider %s has invalid schema for managed resource type %q, which is a bug in the provider: %w", addr, t, err)
}
if r.Version < 0 {
return resp, fmt.Errorf("provider %s has invalid negative schema version for managed resource type %q, which is a bug in the provider", addr, t)
@ -105,7 +105,7 @@ func (cp *contextPlugins) ProviderSchema(addr addrs.Provider) (providers.Provide
for t, d := range resp.DataSources {
if err := d.Block.InternalValidate(); err != nil {
return resp, fmt.Errorf("provider %s has invalid schema for data resource type %q, which is a bug in the provider: %q", addr, t, err)
return resp, fmt.Errorf("provider %s has invalid schema for data resource type %q, which is a bug in the provider: %w", addr, t, err)
}
if d.Version < 0 {
// We're not using the version numbers here yet, but we'll check
@ -161,13 +161,13 @@ func (cp *contextPlugins) ProvisionerSchema(typ string) (*configschema.Block, er
log.Printf("[TRACE] terraform.contextPlugins: Initializing provisioner %q to read its schema", typ)
provisioner, err := cp.NewProvisionerInstance(typ)
if err != nil {
return nil, fmt.Errorf("failed to instantiate provisioner %q to obtain schema: %s", typ, err)
return nil, fmt.Errorf("failed to instantiate provisioner %q to obtain schema: %w", typ, err)
}
defer provisioner.Close()
resp := provisioner.GetSchema()
if resp.Diagnostics.HasErrors() {
return nil, fmt.Errorf("failed to retrieve schema from provisioner %q: %s", typ, resp.Diagnostics.Err())
return nil, fmt.Errorf("failed to retrieve schema from provisioner %q: %w", typ, resp.Diagnostics.Err())
}
return resp.Provisioner, nil

View File

@ -267,7 +267,7 @@ func (ctx *BuiltinEvalContext) CloseProvisioners() error {
for name, prov := range ctx.ProvisionerCache {
err := prov.Close()
if err != nil {
diags = diags.Append(fmt.Errorf("provisioner.Close %s: %s", name, err))
diags = diags.Append(fmt.Errorf("provisioner.Close %s: %w", name, err))
}
}

View File

@ -459,7 +459,7 @@ func (d *evaluationStateData) GetModule(addr addrs.ModuleCall, rng tfdiags.Sourc
if err != nil {
// This should happen only if someone has tampered with a plan
// file, so we won't bother with a pretty error for it.
diags = diags.Append(fmt.Errorf("planned change for %s could not be decoded: %s", addr, err))
diags = diags.Append(fmt.Errorf("planned change for %s could not be decoded: %w", addr, err))
instance[cfg.Name] = cty.DynamicVal
continue
}

View File

@ -156,7 +156,7 @@ func (n *NodeAbstractResourceInstance) readDiff(ctx EvalContext, providerSchema
change, err := csrc.Decode(schema.ImpliedType())
if err != nil {
return nil, fmt.Errorf("failed to decode planned changes for %s: %s", n.Addr, err)
return nil, fmt.Errorf("failed to decode planned changes for %s: %w", n.Addr, err)
}
log.Printf("[TRACE] readDiff: Read %s change from plan for %s", change.Action, n.Addr)
@ -339,7 +339,7 @@ func (n *NodeAbstractResourceInstance) writeResourceInstanceStateImpl(ctx EvalCo
src, err := obj.Encode(schema.ImpliedType(), currentVersion)
if err != nil {
return fmt.Errorf("failed to encode %s in state: %s", absAddr, err)
return fmt.Errorf("failed to encode %s in state: %w", absAddr, err)
}
write(src)
@ -496,7 +496,7 @@ func (n *NodeAbstractResourceInstance) writeChange(ctx EvalContext, change *plan
csrc, err := change.Encode(schema.ImpliedType())
if err != nil {
return fmt.Errorf("failed to encode planned changes for %s: %s", n.Addr, err)
return fmt.Errorf("failed to encode planned changes for %s: %w", n.Addr, err)
}
changes.AppendResourceInstanceChange(csrc)

View File

@ -324,7 +324,7 @@ func (n *NodeDestroyDeposedResourceInstanceObject) writeResourceInstanceState(ct
}
src, err := obj.Encode(schema.ImpliedType(), currentVersion)
if err != nil {
return fmt.Errorf("failed to encode %s in state: %s", absAddr, err)
return fmt.Errorf("failed to encode %s in state: %w", absAddr, err)
}
log.Printf("[TRACE] writeResourceInstanceStateDeposed: writing state object for %s deposed %s", absAddr, key)

View File

@ -89,7 +89,7 @@ func (n *NodeValidatableResource) validateProvisioner(ctx EvalContext, p *config
}
provisionerSchema, err := ctx.ProvisionerSchema(p.Type)
if err != nil {
return diags.Append(fmt.Errorf("failed to read schema for provisioner %s: %s", p.Type, err))
return diags.Append(fmt.Errorf("failed to read schema for provisioner %s: %w", p.Type, err))
}
if provisionerSchema == nil {
return diags.Append(fmt.Errorf("provisioner %s has no schema", p.Type))

View File

@ -67,7 +67,7 @@ func (t *AttachSchemaTransformer) Transform(g *Graph) error {
schema, version, err := t.Plugins.ResourceTypeSchema(providerFqn, mode, typeName)
if err != nil {
return fmt.Errorf("failed to read schema for %s in %s: %s", addr, providerFqn, err)
return fmt.Errorf("failed to read schema for %s in %s: %w", addr, providerFqn, err)
}
if schema == nil {
log.Printf("[ERROR] AttachSchemaTransformer: No resource schema available for %s", addr)
@ -81,7 +81,7 @@ func (t *AttachSchemaTransformer) Transform(g *Graph) error {
providerAddr := tv.ProviderAddr()
schema, err := t.Plugins.ProviderConfigSchema(providerAddr.Provider)
if err != nil {
return fmt.Errorf("failed to read provider configuration schema for %s: %s", providerAddr.Provider, err)
return fmt.Errorf("failed to read provider configuration schema for %s: %w", providerAddr.Provider, err)
}
if schema == nil {
log.Printf("[ERROR] AttachSchemaTransformer: No provider config schema available for %s", providerAddr)
@ -96,7 +96,7 @@ func (t *AttachSchemaTransformer) Transform(g *Graph) error {
for _, name := range names {
schema, err := t.Plugins.ProvisionerSchema(name)
if err != nil {
return fmt.Errorf("failed to read provisioner configuration schema for %q: %s", name, err)
return fmt.Errorf("failed to read provisioner configuration schema for %q: %w", name, err)
}
if schema == nil {
log.Printf("[ERROR] AttachSchemaTransformer: No schema available for provisioner %q on %q", name, dag.VertexName(v))

View File

@ -61,7 +61,7 @@ func (t *ForcedCBDTransformer) Transform(g *Graph) error {
return fmt.Errorf(
"%s: must have create before destroy enabled because "+
"a dependent resource has CBD enabled. However, when "+
"attempting to automatically do this, an error occurred: %s",
"attempting to automatically do this, an error occurred: %w",
dag.VertexName(v), err)
}
} else {

View File

@ -241,13 +241,13 @@ func (cs *ChangeSrc) Decode(ty cty.Type) (*Change, error) {
if len(cs.Before) > 0 {
before, err = cs.Before.Decode(ty)
if err != nil {
return nil, fmt.Errorf("error decoding 'before' value: %s", err)
return nil, fmt.Errorf("error decoding 'before' value: %w", err)
}
}
if len(cs.After) > 0 {
after, err = cs.After.Decode(ty)
if err != nil {
return nil, fmt.Errorf("error decoding 'after' value: %s", err)
return nil, fmt.Errorf("error decoding 'after' value: %w", err)
}
}

View File

@ -75,11 +75,11 @@ func readConfigSnapshot(z *zip.Reader) (*configload.Snapshot, error) {
r, err := file.Open()
if err != nil {
return nil, fmt.Errorf("failed to open snapshot of %s from module %q: %s", fileName, moduleKey, err)
return nil, fmt.Errorf("failed to open snapshot of %s from module %q: %w", fileName, moduleKey, err)
}
fileSrc, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("failed to read snapshot of %s from module %q: %s", fileName, moduleKey, err)
return nil, fmt.Errorf("failed to read snapshot of %s from module %q: %w", fileName, moduleKey, err)
}
if _, exists := snap.Modules[moduleKey]; !exists {
@ -100,7 +100,7 @@ func readConfigSnapshot(z *zip.Reader) (*configload.Snapshot, error) {
var manifest configSnapshotModuleManifest
err := json.Unmarshal(manifestSrc, &manifest)
if err != nil {
return nil, fmt.Errorf("invalid module manifest: %s", err)
return nil, fmt.Errorf("invalid module manifest: %w", err)
}
for _, record := range manifest {
@ -187,11 +187,11 @@ func writeConfigSnapshot(snap *configload.Snapshot, z *zip.Writer) error {
}
w, err := z.CreateHeader(zh)
if err != nil {
return fmt.Errorf("failed to create snapshot of %s from module %q: %s", zh.Name, k, err)
return fmt.Errorf("failed to create snapshot of %s from module %q: %w", zh.Name, k, err)
}
_, err = w.Write(src)
if err != nil {
return fmt.Errorf("failed to write snapshot of %s from module %q: %s", zh.Name, k, err)
return fmt.Errorf("failed to write snapshot of %s from module %q: %w", zh.Name, k, err)
}
}
}
@ -205,15 +205,15 @@ func writeConfigSnapshot(snap *configload.Snapshot, z *zip.Writer) error {
}
src, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
return fmt.Errorf("failed to serialize module manifest: %s", err)
return fmt.Errorf("failed to serialize module manifest: %w", err)
}
w, err := z.CreateHeader(zh)
if err != nil {
return fmt.Errorf("failed to create module manifest: %s", err)
return fmt.Errorf("failed to create module manifest: %w", err)
}
_, err = w.Write(src)
if err != nil {
return fmt.Errorf("failed to write module manifest: %s", err)
return fmt.Errorf("failed to write module manifest: %w", err)
}
}

View File

@ -111,7 +111,7 @@ func (r *Reader) ReadPlan() (*plans.Plan, error) {
pr, err := planFile.Open()
if err != nil {
return nil, errUnusable(fmt.Errorf("failed to retrieve plan from plan file: %s", err))
return nil, errUnusable(fmt.Errorf("failed to retrieve plan from plan file: %w", err))
}
defer pr.Close()
@ -133,11 +133,11 @@ func (r *Reader) ReadPlan() (*plans.Plan, error) {
prevRunStateFile, err := r.ReadPrevStateFile()
if err != nil {
return nil, errUnusable(fmt.Errorf("failed to read previous run state from plan file: %s", err))
return nil, errUnusable(fmt.Errorf("failed to read previous run state from plan file: %w", err))
}
priorStateFile, err := r.ReadStateFile()
if err != nil {
return nil, errUnusable(fmt.Errorf("failed to read prior state from plan file: %s", err))
return nil, errUnusable(fmt.Errorf("failed to read prior state from plan file: %w", err))
}
ret.PrevRunState = prevRunStateFile.State
@ -156,7 +156,7 @@ func (r *Reader) ReadStateFile() (*statefile.File, error) {
if file.Name == tfstateFilename {
r, err := file.Open()
if err != nil {
return nil, errUnusable(fmt.Errorf("failed to extract state from plan file: %s", err))
return nil, errUnusable(fmt.Errorf("failed to extract state from plan file: %w", err))
}
return statefile.Read(r)
}
@ -174,7 +174,7 @@ func (r *Reader) ReadPrevStateFile() (*statefile.File, error) {
if file.Name == tfstatePreviousFilename {
r, err := file.Open()
if err != nil {
return nil, errUnusable(fmt.Errorf("failed to extract previous state from plan file: %s", err))
return nil, errUnusable(fmt.Errorf("failed to extract previous state from plan file: %w", err))
}
return statefile.Read(r)
}

View File

@ -44,7 +44,7 @@ func readTfplan(r io.Reader) (*plans.Plan, error) {
var rawPlan planproto.Plan
err = proto.Unmarshal(src, &rawPlan)
if err != nil {
return nil, fmt.Errorf("parse error: %s", err)
return nil, fmt.Errorf("parse error: %w", err)
}
if rawPlan.Version != tfplanFormatVersion {
@ -82,7 +82,7 @@ func readTfplan(r io.Reader) (*plans.Plan, error) {
name := rawOC.Name
change, err := changeFromTfplan(rawOC.Change)
if err != nil {
return nil, fmt.Errorf("invalid plan for output %q: %s", name, err)
return nil, fmt.Errorf("invalid plan for output %q: %w", name, err)
}
plan.Changes.Outputs = append(plan.Changes.Outputs, &plans.OutputChangeSrc{
@ -216,7 +216,7 @@ func readTfplan(r io.Reader) (*plans.Plan, error) {
for _, rawTargetAddr := range rawPlan.TargetAddrs {
target, diags := addrs.ParseTargetStr(rawTargetAddr)
if diags.HasErrors() {
return nil, fmt.Errorf("plan contains invalid target address %q: %s", target, diags.Err())
return nil, fmt.Errorf("plan contains invalid target address %q: %w", target, diags.Err())
}
plan.TargetAddrs = append(plan.TargetAddrs, target.Subject)
}
@ -224,7 +224,7 @@ func readTfplan(r io.Reader) (*plans.Plan, error) {
for _, rawReplaceAddr := range rawPlan.ForceReplaceAddrs {
addr, diags := addrs.ParseAbsResourceInstanceStr(rawReplaceAddr)
if diags.HasErrors() {
return nil, fmt.Errorf("plan contains invalid force-replace address %q: %s", addr, diags.Err())
return nil, fmt.Errorf("plan contains invalid force-replace address %q: %w", addr, diags.Err())
}
plan.ForceReplaceAddrs = append(plan.ForceReplaceAddrs, addr)
}
@ -232,7 +232,7 @@ func readTfplan(r io.Reader) (*plans.Plan, error) {
for name, rawVal := range rawPlan.Variables {
val, err := valueFromTfplan(rawVal)
if err != nil {
return nil, fmt.Errorf("invalid value for input variable %q: %s", name, err)
return nil, fmt.Errorf("invalid value for input variable %q: %w", name, err)
}
plan.VariableValues[name] = val
}
@ -242,7 +242,7 @@ func readTfplan(r io.Reader) (*plans.Plan, error) {
} else {
config, err := valueFromTfplan(rawBackend.Config)
if err != nil {
return nil, fmt.Errorf("plan file has invalid backend configuration: %s", err)
return nil, fmt.Errorf("plan file has invalid backend configuration: %w", err)
}
plan.Backend = plans.Backend{
Type: rawBackend.Type,
@ -252,7 +252,7 @@ func readTfplan(r io.Reader) (*plans.Plan, error) {
}
if plan.Timestamp, err = time.Parse(time.RFC3339, rawPlan.Timestamp); err != nil {
return nil, fmt.Errorf("invalid value for timestamp %s: %s", rawPlan.Timestamp, err)
return nil, fmt.Errorf("invalid value for timestamp %s: %w", rawPlan.Timestamp, err)
}
return plan, nil
@ -307,14 +307,14 @@ func resourceChangeFromTfplan(rawChange *planproto.ResourceInstanceChange) (*pla
for _, p := range rawChange.RequiredReplace {
path, err := pathFromTfplan(p)
if err != nil {
return nil, fmt.Errorf("invalid path in required replace: %s", err)
return nil, fmt.Errorf("invalid path in required replace: %w", err)
}
ret.RequiredReplace.Add(path)
}
change, err := changeFromTfplan(rawChange.Change)
if err != nil {
return nil, fmt.Errorf("invalid plan for resource %s: %s", ret.Addr, err)
return nil, fmt.Errorf("invalid plan for resource %s: %w", ret.Addr, err)
}
ret.ChangeSrc = *change
@ -408,10 +408,10 @@ func changeFromTfplan(rawChange *planproto.Change) (*plans.ChangeSrc, error) {
var err error
ret.Before, err = valueFromTfplan(rawChange.Values[beforeIdx])
if err != nil {
return nil, fmt.Errorf("invalid \"before\" value: %s", err)
return nil, fmt.Errorf("invalid \"before\" value: %w", err)
}
if ret.Before == nil {
return nil, fmt.Errorf("missing \"before\" value: %s", err)
return nil, fmt.Errorf("missing \"before\" value: %w", err)
}
}
if afterIdx != -1 {
@ -421,10 +421,10 @@ func changeFromTfplan(rawChange *planproto.Change) (*plans.ChangeSrc, error) {
var err error
ret.After, err = valueFromTfplan(rawChange.Values[afterIdx])
if err != nil {
return nil, fmt.Errorf("invalid \"after\" value: %s", err)
return nil, fmt.Errorf("invalid \"after\" value: %w", err)
}
if ret.After == nil {
return nil, fmt.Errorf("missing \"after\" value: %s", err)
return nil, fmt.Errorf("missing \"after\" value: %w", err)
}
}
@ -438,11 +438,11 @@ func changeFromTfplan(rawChange *planproto.Change) (*plans.ChangeSrc, error) {
sensitive := cty.NewValueMarks(marks.Sensitive)
beforeValMarks, err := pathValueMarksFromTfplan(rawChange.BeforeSensitivePaths, sensitive)
if err != nil {
return nil, fmt.Errorf("failed to decode before sensitive paths: %s", err)
return nil, fmt.Errorf("failed to decode before sensitive paths: %w", err)
}
afterValMarks, err := pathValueMarksFromTfplan(rawChange.AfterSensitivePaths, sensitive)
if err != nil {
return nil, fmt.Errorf("failed to decode after sensitive paths: %s", err)
return nil, fmt.Errorf("failed to decode after sensitive paths: %w", err)
}
if len(beforeValMarks) > 0 {
ret.BeforeValMarks = beforeValMarks
@ -511,7 +511,7 @@ func writeTfplan(plan *plans.Plan, w io.Writer) error {
// original type when we read the values back in readTFPlan.
protoChange, err := changeToTfplan(&oc.ChangeSrc)
if err != nil {
return fmt.Errorf("cannot write output value %q: %s", name, err)
return fmt.Errorf("cannot write output value %q: %w", name, err)
}
rawPlan.OutputChanges = append(rawPlan.OutputChanges, &planproto.OutputChange{
@ -630,12 +630,12 @@ func writeTfplan(plan *plans.Plan, w io.Writer) error {
src, err := proto.Marshal(rawPlan)
if err != nil {
return fmt.Errorf("serialization error: %s", err)
return fmt.Errorf("serialization error: %w", err)
}
_, err = w.Write(src)
if err != nil {
return fmt.Errorf("failed to write plan to plan file: %s", err)
return fmt.Errorf("failed to write plan to plan file: %w", err)
}
return nil
@ -667,7 +667,7 @@ func resourceAttrFromTfplan(ra *planproto.PlanResourceAttr) (globalref.ResourceA
res.Resource = instAddr
path, err := pathFromTfplan(ra.Attr)
if err != nil {
return res, fmt.Errorf("invalid path in %q relevant attribute: %s", res.Resource, err)
return res, fmt.Errorf("invalid path in %q relevant attribute: %w", res.Resource, err)
}
res.Attr = path
@ -701,14 +701,14 @@ func resourceChangeToTfplan(change *plans.ResourceInstanceChangeSrc) (*planproto
for _, p := range requiredReplace {
path, err := pathToTfplan(p)
if err != nil {
return nil, fmt.Errorf("invalid path in required replace: %s", err)
return nil, fmt.Errorf("invalid path in required replace: %w", err)
}
ret.RequiredReplace = append(ret.RequiredReplace, path)
}
valChange, err := changeToTfplan(&change.ChangeSrc)
if err != nil {
return nil, fmt.Errorf("failed to serialize resource %s change: %s", change.Addr, err)
return nil, fmt.Errorf("failed to serialize resource %s change: %w", change.Addr, err)
}
ret.Change = valChange
@ -851,15 +851,15 @@ func pathFromTfplan(path *planproto.Path) (cty.Path, error) {
case *planproto.Path_Step_ElementKey:
dynamicVal, err := valueFromTfplan(s.ElementKey)
if err != nil {
return nil, fmt.Errorf("error decoding path index step: %s", err)
return nil, fmt.Errorf("error decoding path index step: %w", err)
}
ty, err := dynamicVal.ImpliedType()
if err != nil {
return nil, fmt.Errorf("error determining path index type: %s", err)
return nil, fmt.Errorf("error determining path index type: %w", err)
}
val, err := dynamicVal.Decode(ty)
if err != nil {
return nil, fmt.Errorf("error decoding path index value: %s", err)
return nil, fmt.Errorf("error decoding path index value: %w", err)
}
ret = append(ret, cty.IndexStep{Key: val})
case *planproto.Path_Step_AttributeName:
@ -878,7 +878,7 @@ func pathToTfplan(path cty.Path) (*planproto.Path, error) {
case cty.IndexStep:
value, err := plans.NewDynamicValue(s.Key, s.Key.Type())
if err != nil {
return nil, fmt.Errorf("Error encoding path step: %s", err)
return nil, fmt.Errorf("Error encoding path step: %w", err)
}
steps = append(steps, &planproto.Path_Step{
Selector: &planproto.Path_Step_ElementKey{

View File

@ -69,11 +69,11 @@ func Create(filename string, args CreateArgs) error {
Modified: time.Now(),
})
if err != nil {
return fmt.Errorf("failed to create tfplan file: %s", err)
return fmt.Errorf("failed to create tfplan file: %w", err)
}
err = writeTfplan(args.Plan, w)
if err != nil {
return fmt.Errorf("failed to write plan: %s", err)
return fmt.Errorf("failed to write plan: %w", err)
}
}
@ -85,11 +85,11 @@ func Create(filename string, args CreateArgs) error {
Modified: time.Now(),
})
if err != nil {
return fmt.Errorf("failed to create embedded tfstate file: %s", err)
return fmt.Errorf("failed to create embedded tfstate file: %w", err)
}
err = statefile.Write(args.StateFile, w)
if err != nil {
return fmt.Errorf("failed to write state snapshot: %s", err)
return fmt.Errorf("failed to write state snapshot: %w", err)
}
}
@ -101,11 +101,11 @@ func Create(filename string, args CreateArgs) error {
Modified: time.Now(),
})
if err != nil {
return fmt.Errorf("failed to create embedded tfstate-prev file: %s", err)
return fmt.Errorf("failed to create embedded tfstate-prev file: %w", err)
}
err = statefile.Write(args.PreviousRunStateFile, w)
if err != nil {
return fmt.Errorf("failed to write previous state snapshot: %s", err)
return fmt.Errorf("failed to write previous state snapshot: %w", err)
}
}
@ -113,7 +113,7 @@ func Create(filename string, args CreateArgs) error {
{
err := writeConfigSnapshot(args.ConfigSnapshot, zw)
if err != nil {
return fmt.Errorf("failed to write config snapshot: %s", err)
return fmt.Errorf("failed to write config snapshot: %w", err)
}
}
@ -121,7 +121,7 @@ func Create(filename string, args CreateArgs) error {
if args.DependencyLocks != nil { // (this was a later addition, so not all callers set it, but main callers should)
src, diags := depsfile.SaveLocksToBytes(args.DependencyLocks)
if diags.HasErrors() {
return fmt.Errorf("failed to write embedded dependency lock file: %s", diags.Err().Error())
return fmt.Errorf("failed to write embedded dependency lock file: %w", diags.Err())
}
w, err := zw.CreateHeader(&zip.FileHeader{
@ -130,11 +130,11 @@ func Create(filename string, args CreateArgs) error {
Modified: time.Now(),
})
if err != nil {
return fmt.Errorf("failed to create embedded dependency lock file: %s", err)
return fmt.Errorf("failed to create embedded dependency lock file: %w", err)
}
_, err = w.Write(src)
if err != nil {
return fmt.Errorf("failed to write embedded dependency lock file: %s", err)
return fmt.Errorf("failed to write embedded dependency lock file: %w", err)
}
}

View File

@ -108,7 +108,7 @@ func (cp *CachedProvider) ExecutableFile() (string, error) {
if err != nil {
// If the directory itself doesn't exist or isn't readable then we
// can't access an executable in it.
return "", fmt.Errorf("could not read package directory: %s", err)
return "", fmt.Errorf("could not read package directory: %w", err)
}
// For a provider named e.g. tf.example.com/awesomecorp/happycloud, we

View File

@ -65,7 +65,7 @@ func (d *Dir) LinkFromOtherCache(entry *CachedProvider, allowedHashes []getprovi
if len(allowedHashes) > 0 {
if matches, err := entry.MatchesAnyHash(allowedHashes); err != nil {
return fmt.Errorf(
"failed to calculate checksum for cached copy of %s %s in %s: %s",
"failed to calculate checksum for cached copy of %s %s in %s: %w",
entry.Provider, entry.Version, d.baseDir, err,
)
} else if !matches {

View File

@ -444,7 +444,7 @@ NeedProvider:
cb(provider, version, i.globalCacheDir.baseDir)
}
if _, err := cached.ExecutableFile(); err != nil {
err := fmt.Errorf("provider binary not found: %s", err)
err := fmt.Errorf("provider binary not found: %w", err)
errs[provider] = err
if cb := evts.LinkFromCacheFailure; cb != nil {
cb(provider, version, err)
@ -506,7 +506,7 @@ NeedProvider:
}
newHash, err := cached.Hash()
if err != nil {
err := fmt.Errorf("after linking %s from provider cache at %s, failed to compute a checksum for it: %s", provider, i.globalCacheDir.baseDir, err)
err := fmt.Errorf("after linking %s from provider cache at %s, failed to compute a checksum for it: %w", provider, i.globalCacheDir.baseDir, err)
errs[provider] = err
if cb := evts.LinkFromCacheFailure; cb != nil {
cb(provider, version, err)
@ -593,7 +593,7 @@ NeedProvider:
continue
}
if _, err := new.ExecutableFile(); err != nil {
err := fmt.Errorf("provider binary not found: %s", err)
err := fmt.Errorf("provider binary not found: %w", err)
errs[provider] = err
if cb := evts.FetchPackageFailure; cb != nil {
cb(provider, version, err)
@ -630,7 +630,7 @@ NeedProvider:
continue
}
if _, err := new.ExecutableFile(); err != nil {
err := fmt.Errorf("provider binary not found: %s", err)
err := fmt.Errorf("provider binary not found: %w", err)
errs[provider] = err
if cb := evts.FetchPackageFailure; cb != nil {
cb(provider, version, err)
@ -666,7 +666,7 @@ NeedProvider:
}
newHash, err := new.Hash()
if err != nil {
err := fmt.Errorf("after installing %s, failed to compute a checksum for it: %s", provider, err)
err := fmt.Errorf("after installing %s, failed to compute a checksum for it: %w", provider, err)
errs[provider] = err
if cb := evts.FetchPackageFailure; cb != nil {
cb(provider, version, err)

View File

@ -38,7 +38,7 @@ func installFromHTTPURL(ctx context.Context, meta getproviders.PackageMeta, targ
httpClient := httpclient.New()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("invalid provider download request: %s", err)
return nil, fmt.Errorf("invalid provider download request: %w", err)
}
resp, err := httpClient.Do(req)
if err != nil {
@ -114,7 +114,7 @@ func installFromLocalArchive(ctx context.Context, meta getproviders.PackageMeta,
if len(allowedHashes) > 0 {
if matches, err := meta.MatchesAnyHash(allowedHashes); err != nil {
return authResult, fmt.Errorf(
"failed to calculate checksum for %s %s package at %s: %s",
"failed to calculate checksum for %s %s package at %s: %w",
meta.Provider, meta.Version, meta.Location, err,
)
} else if !matches {
@ -152,11 +152,11 @@ func installFromLocalDir(ctx context.Context, meta getproviders.PackageMeta, tar
absNew, err := filepath.Abs(targetDir)
if err != nil {
return nil, fmt.Errorf("failed to make target path %s absolute: %s", targetDir, err)
return nil, fmt.Errorf("failed to make target path %s absolute: %w", targetDir, err)
}
absCurrent, err := filepath.Abs(sourceDir)
if err != nil {
return nil, fmt.Errorf("failed to make source path %s absolute: %s", sourceDir, err)
return nil, fmt.Errorf("failed to make source path %s absolute: %w", sourceDir, err)
}
// Before we do anything else, we'll do a quick check to make sure that
@ -166,7 +166,7 @@ func installFromLocalDir(ctx context.Context, meta getproviders.PackageMeta, tar
if same, err := copy.SameFile(absNew, absCurrent); same {
return nil, fmt.Errorf("cannot install existing provider directory %s to itself", targetDir)
} else if err != nil {
return nil, fmt.Errorf("failed to determine if %s and %s are the same: %s", sourceDir, targetDir, err)
return nil, fmt.Errorf("failed to determine if %s and %s are the same: %w", sourceDir, targetDir, err)
}
var authResult *getproviders.PackageAuthenticationResult
@ -204,7 +204,7 @@ func installFromLocalDir(ctx context.Context, meta getproviders.PackageMeta, tar
if suitableHashCount > 0 {
if matches, err := meta.MatchesAnyHash(allowedHashes); err != nil {
return authResult, fmt.Errorf(
"failed to calculate checksum for %s %s package at %s: %s",
"failed to calculate checksum for %s %s package at %s: %w",
meta.Provider, meta.Version, meta.Location, err,
)
} else if !matches {
@ -218,7 +218,7 @@ func installFromLocalDir(ctx context.Context, meta getproviders.PackageMeta, tar
// Delete anything that's already present at this path first.
err = os.RemoveAll(targetDir)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to remove existing %s before linking it to %s: %s", sourceDir, targetDir, err)
return nil, fmt.Errorf("failed to remove existing %s before linking it to %s: %w", sourceDir, targetDir, err)
}
// We'll prefer to create a symlink if possible, but we'll fall back to
@ -237,7 +237,7 @@ func installFromLocalDir(ctx context.Context, meta getproviders.PackageMeta, tar
parentDir := filepath.Dir(absNew)
err = os.MkdirAll(parentDir, 0755)
if err != nil {
return nil, fmt.Errorf("failed to create parent directories leading to %s: %s", targetDir, err)
return nil, fmt.Errorf("failed to create parent directories leading to %s: %w", targetDir, err)
}
err = os.Symlink(linkTarget, absNew)
@ -251,11 +251,11 @@ func installFromLocalDir(ctx context.Context, meta getproviders.PackageMeta, tar
// which would otherwise be a symlink.
err = os.Mkdir(absNew, 0755)
if err != nil && os.IsExist(err) {
return nil, fmt.Errorf("failed to create directory %s: %s", absNew, err)
return nil, fmt.Errorf("failed to create directory %s: %w", absNew, err)
}
err = copy.CopyDir(absNew, absCurrent)
if err != nil {
return nil, fmt.Errorf("failed to either symlink or copy %s to %s: %s", absCurrent, absNew, err)
return nil, fmt.Errorf("failed to either symlink or copy %s to %s: %w", absCurrent, absNew, err)
}
// If we got here then apparently our copy succeeded, so we're done.

View File

@ -230,7 +230,7 @@ func (c *Client) ModuleLocation(ctx context.Context, module *regsrc.Module, vers
// there should be no body, but save it for logging
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error reading response body from registry: %s", err)
return "", fmt.Errorf("error reading response body from registry: %w", err)
}
switch resp.StatusCode {
@ -263,7 +263,7 @@ func (c *Client) ModuleLocation(ctx context.Context, module *regsrc.Module, vers
if strings.HasPrefix(location, "/") || strings.HasPrefix(location, "./") || strings.HasPrefix(location, "../") {
locationURL, err := url.Parse(location)
if err != nil {
return "", fmt.Errorf("invalid relative URL for %q: %s", module, err)
return "", fmt.Errorf("invalid relative URL for %q: %w", module, err)
}
locationURL = download.ResolveReference(locationURL)
location = locationURL.String()

View File

@ -37,7 +37,7 @@ func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error {
}
f, err := os.CreateTemp(dir, file) // alongside target file and with a similar name
if err != nil {
return fmt.Errorf("cannot create temporary file to update %s: %s", filename, err)
return fmt.Errorf("cannot create temporary file to update %s: %w", filename, err)
}
tmpName := f.Name()
moved := false
@ -54,7 +54,7 @@ func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error {
// not be effective on all platforms, but should at least work on
// Unix-like targets and should be harmless elsewhere.
if err := os.Chmod(tmpName, perm); err != nil {
return fmt.Errorf("cannot set mode for temporary file %s: %s", tmpName, err)
return fmt.Errorf("cannot set mode for temporary file %s: %w", tmpName, err)
}
// Write the credentials to the temporary file, then immediately close
@ -63,7 +63,7 @@ func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error {
_, err = f.Write(data)
f.Close()
if err != nil {
return fmt.Errorf("cannot write to temporary file %s: %s", tmpName, err)
return fmt.Errorf("cannot write to temporary file %s: %w", tmpName, err)
}
// Temporary file now replaces the original file, as atomically as
@ -71,7 +71,7 @@ func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error {
// containing only a partial JSON object.)
err = AtomicRename(tmpName, filename)
if err != nil {
return fmt.Errorf("failed to replace %s with temporary file %s: %s", filename, tmpName, err)
return fmt.Errorf("failed to replace %s with temporary file %s: %w", filename, tmpName, err)
}
moved = true

View File

@ -62,7 +62,7 @@ func (s *State) State() *states.State {
func (s *State) GetRootOutputValues() (map[string]*states.OutputValue, error) {
if err := s.RefreshState(); err != nil {
return nil, fmt.Errorf("Failed to load state: %s", err)
return nil, fmt.Errorf("Failed to load state: %w", err)
}
state := s.State()
@ -188,14 +188,14 @@ func (s *State) PersistState(schemas *opentf.Schemas) error {
// that we ought to be updating.
err := s.refreshState()
if err != nil {
return fmt.Errorf("failed checking for existing remote state: %s", err)
return fmt.Errorf("failed checking for existing remote state: %w", err)
}
log.Printf("[DEBUG] states/remote: after refresh, state read serial is: %d; serial is: %d", s.readSerial, s.serial)
log.Printf("[DEBUG] states/remote: after refresh, state read lineage is: %s; lineage is: %s", s.readLineage, s.lineage)
if s.lineage == "" { // indicates that no state snapshot is present yet
lineage, err := uuid.GenerateUUID()
if err != nil {
return fmt.Errorf("failed to generate initial lineage: %v", err)
return fmt.Errorf("failed to generate initial lineage: %w", err)
}
s.lineage = lineage
s.serial++

View File

@ -20,14 +20,14 @@ func upgradeStateV1ToV2(old *stateV1) (*stateV2, error) {
remote, err := old.Remote.upgradeToV2()
if err != nil {
return nil, fmt.Errorf("Error upgrading State V1: %v", err)
return nil, fmt.Errorf("Error upgrading State V1: %w", err)
}
modules := make([]*moduleStateV2, len(old.Modules))
for i, module := range old.Modules {
upgraded, err := module.upgradeToV2()
if err != nil {
return nil, fmt.Errorf("Error upgrading State V1: %v", err)
return nil, fmt.Errorf("Error upgrading State V1: %w", err)
}
modules[i] = upgraded
}
@ -52,7 +52,7 @@ func (old *remoteStateV1) upgradeToV2() (*remoteStateV2, error) {
config, err := copystructure.Copy(old.Config)
if err != nil {
return nil, fmt.Errorf("Error upgrading RemoteState V1: %v", err)
return nil, fmt.Errorf("Error upgrading RemoteState V1: %w", err)
}
return &remoteStateV2{
@ -68,7 +68,7 @@ func (old *moduleStateV1) upgradeToV2() (*moduleStateV2, error) {
pathRaw, err := copystructure.Copy(old.Path)
if err != nil {
return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err)
return nil, fmt.Errorf("Error upgrading ModuleState V1: %w", err)
}
path, ok := pathRaw.([]string)
if !ok {
@ -93,14 +93,14 @@ func (old *moduleStateV1) upgradeToV2() (*moduleStateV2, error) {
for key, oldResource := range old.Resources {
upgraded, err := oldResource.upgradeToV2()
if err != nil {
return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err)
return nil, fmt.Errorf("Error upgrading ModuleState V1: %w", err)
}
resources[key] = upgraded
}
dependencies, err := copystructure.Copy(old.Dependencies)
if err != nil {
return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err)
return nil, fmt.Errorf("Error upgrading ModuleState V1: %w", err)
}
return &moduleStateV2{
@ -118,19 +118,19 @@ func (old *resourceStateV1) upgradeToV2() (*resourceStateV2, error) {
dependencies, err := copystructure.Copy(old.Dependencies)
if err != nil {
return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err)
return nil, fmt.Errorf("Error upgrading ResourceState V1: %w", err)
}
primary, err := old.Primary.upgradeToV2()
if err != nil {
return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err)
return nil, fmt.Errorf("Error upgrading ResourceState V1: %w", err)
}
deposed := make([]*instanceStateV2, len(old.Deposed))
for i, v := range old.Deposed {
upgraded, err := v.upgradeToV2()
if err != nil {
return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err)
return nil, fmt.Errorf("Error upgrading ResourceState V1: %w", err)
}
deposed[i] = upgraded
}
@ -154,12 +154,12 @@ func (old *instanceStateV1) upgradeToV2() (*instanceStateV2, error) {
attributes, err := copystructure.Copy(old.Attributes)
if err != nil {
return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err)
return nil, fmt.Errorf("Error upgrading InstanceState V1: %w", err)
}
meta, err := copystructure.Copy(old.Meta)
if err != nil {
return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err)
return nil, fmt.Errorf("Error upgrading InstanceState V1: %w", err)
}
newMeta := make(map[string]interface{})

View File

@ -129,7 +129,7 @@ func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) {
// update this message to mention OpenTF instead.
return nil, fmt.Errorf("invalid provider config reference %q for %s: this alias seems to contain a template interpolation sequence, which was not supported but also not error-checked in Terraform 0.11. To proceed, rename the associated provider alias to a valid identifier and apply the change with Terraform 0.11 before upgrading to Terraform 0.12", oldProviderAddr, instAddr)
}
return nil, fmt.Errorf("invalid provider config reference %q for %s: %s", oldProviderAddr, instAddr, diags.Err())
return nil, fmt.Errorf("invalid provider config reference %q for %s: %w", oldProviderAddr, instAddr, diags.Err())
}
} else {
// Smells like an old-style module-local provider address,
@ -153,7 +153,7 @@ func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) {
// update this message to mention OpenTF instead.
return nil, fmt.Errorf("invalid legacy provider config reference %q for %s: this alias seems to contain a template interpolation sequence, which was not supported but also not error-checked in Terraform 0.11. To proceed, rename the associated provider alias to a valid identifier and apply the change with Terraform 0.11 before upgrading to Terraform 0.12", oldProviderAddr, instAddr)
}
return nil, fmt.Errorf("invalid legacy provider config reference %q for %s: %s", oldProviderAddr, instAddr, diags.Err())
return nil, fmt.Errorf("invalid legacy provider config reference %q for %s: %w", oldProviderAddr, instAddr, diags.Err())
}
providerAddr = addrs.AbsProviderConfig{
Module: moduleAddr.Module(),
@ -192,7 +192,7 @@ func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) {
if isOld := rsOld.Primary; isOld != nil {
isNew, err := upgradeInstanceObjectV3ToV4(rsOld, isOld, instKey, states.NotDeposed)
if err != nil {
return nil, fmt.Errorf("failed to migrate primary generation of %s: %s", instAddr, err)
return nil, fmt.Errorf("failed to migrate primary generation of %s: %w", instAddr, err)
}
rs.Instances = append(rs.Instances, *isNew)
}
@ -205,7 +205,7 @@ func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) {
deposedKey := states.DeposedKey(fmt.Sprintf("%08x", i+1))
isNew, err := upgradeInstanceObjectV3ToV4(rsOld, isOld, instKey, deposedKey)
if err != nil {
return nil, fmt.Errorf("failed to migrate deposed generation index %d of %s: %s", i, instAddr, err)
return nil, fmt.Errorf("failed to migrate deposed generation index %d of %s: %w", i, instAddr, err)
}
rs.Instances = append(rs.Instances, *isNew)
}
@ -231,7 +231,7 @@ func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) {
if err != nil {
// Should never happen, because this value came from JSON
// in the first place and so we're just round-tripping here.
return nil, fmt.Errorf("failed to serialize output %q value as JSON: %s", name, err)
return nil, fmt.Errorf("failed to serialize output %q value as JSON: %w", name, err)
}
// The "type" field in state V2 wasn't really that useful
@ -243,7 +243,7 @@ func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) {
if err != nil {
// REALLY should never happen, because we literally just
// encoded this as JSON above!
return nil, fmt.Errorf("failed to parse output %q value from JSON: %s", name, err)
return nil, fmt.Errorf("failed to parse output %q value from JSON: %w", name, err)
}
// ImpliedType tends to produce structural types, but since older
@ -254,7 +254,7 @@ func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) {
tySrc, err := ctyjson.MarshalType(ty)
if err != nil {
return nil, fmt.Errorf("failed to serialize output %q type as JSON: %s", name, err)
return nil, fmt.Errorf("failed to serialize output %q type as JSON: %w", name, err)
}
newOS.ValueRaw = json.RawMessage(valSrc)
@ -312,7 +312,7 @@ func upgradeInstanceObjectV3ToV4(rsOld *resourceStateV2, isOld *instanceStateV2,
if err != nil {
// This shouldn't happen, because the Meta values all came from JSON
// originally anyway.
return nil, fmt.Errorf("cannot serialize private instance object data: %s", err)
return nil, fmt.Errorf("cannot serialize private instance object data: %w", err)
}
}
@ -399,7 +399,7 @@ func parseLegacyResourceAddress(s string) (addrs.ResourceInstance, error) {
if len(parts) > 2 {
idx, err := strconv.ParseInt(parts[2], 0, 0)
if err != nil {
return ret, fmt.Errorf("error parsing resource address %q: %s", s, err)
return ret, fmt.Errorf("error parsing resource address %q: %w", s, err)
}
ret.Key = addrs.IntKey(idx)

View File

@ -17,7 +17,7 @@ import (
func NewLineage() string {
lineage, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Errorf("Failed to generate lineage: %v", err))
panic(fmt.Errorf("Failed to generate lineage: %w", err))
}
return lineage
}

View File

@ -37,7 +37,7 @@ func configureOutputHandle(f *os.File) (*OutputStream, error) {
// the console is just ambiently associated with our process.
err := SetConsoleOutputCP(CP_UTF8)
if err != nil {
return nil, fmt.Errorf("failed to set the console to UTF-8 mode; you may need to use a newer version of Windows: %s", err)
return nil, fmt.Errorf("failed to set the console to UTF-8 mode; you may need to use a newer version of Windows: %w", err)
}
// If the console also allows us to turn on
@ -95,7 +95,7 @@ func configureInputHandle(f *os.File) (*InputStream, error) {
// the console is just ambiently associated with our process.
err := SetConsoleCP(CP_UTF8)
if err != nil {
return nil, fmt.Errorf("failed to set the console to UTF-8 mode; you may need to use a newer version of Windows: %s", err)
return nil, fmt.Errorf("failed to set the console to UTF-8 mode; you may need to use a newer version of Windows: %w", err)
}
ret.isTerminal = staticTrue
return ret, nil