github.com/google/osv-scalibr@v0.4.1/clients/internal/pypi/pypi.go (about)

     1  // Copyright 2025 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package pypi defines the structures to parse PyPI JSON API response.
    16  package pypi
    17  
    18  import (
    19  	"encoding/json"
    20  	"fmt"
    21  )
    22  
    23  // IndexResponse defines the response of Index API.
    24  // https://docs.pypi.org/api/index-api/
    25  type IndexResponse struct {
    26  	Name     string   `json:"name"`
    27  	Files    []File   `json:"files"`
    28  	Versions []string `json:"versions"`
    29  }
    30  
    31  // File holds the information of a file in index response.
    32  type File struct {
    33  	Name   string `json:"filename"`
    34  	URL    string `json:"url"`
    35  	Yanked Yanked `json:"yanked"`
    36  }
    37  
    38  // Yanked represents the yanked field in the index response.
    39  // This can either be false or a string representing the yanked reason.
    40  type Yanked struct {
    41  	Value bool
    42  }
    43  
    44  // UnmarshalJSON implements the json.Unmarshaler interface for BoolOrString
    45  func (y *Yanked) UnmarshalJSON(data []byte) error {
    46  	// Try unmarshalling as a boolean
    47  	var b bool
    48  	if err := json.Unmarshal(data, &b); err == nil {
    49  		y.Value = b
    50  		return nil
    51  	}
    52  
    53  	// If unmarshalling as a boolean fails, try unmarshalling as a string
    54  	var s string
    55  	if err := json.Unmarshal(data, &s); err == nil {
    56  		// We don't really need the yanked reason, just need to know it's yanked.
    57  		y.Value = true
    58  		return nil
    59  	}
    60  
    61  	// If both fail, return an error
    62  	return fmt.Errorf("could not unmarshal %s as yanked", string(data))
    63  }