github.com/google/osv-scalibr@v0.4.1/extractor/filesystem/language/swift/swiftutils/podfilelock.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 swiftutils provides utilities for parsing Swift podfiles.
    16  package swiftutils
    17  
    18  import (
    19  	"errors"
    20  	"fmt"
    21  	"io"
    22  	"strings"
    23  
    24  	"gopkg.in/yaml.v3"
    25  )
    26  
    27  // PodfileLock represents the structure of a Podfile.lock file.
    28  type podfileLock struct {
    29  	Pods []any `yaml:"PODS"`
    30  }
    31  
    32  // Package represents a single package parsed from Podfile.lock.
    33  type Package struct {
    34  	Name    string
    35  	Version string
    36  }
    37  
    38  // ParsePodfileLock parses the contents of a Podfile.lock and returns a list of packages.
    39  func ParsePodfileLock(reader io.Reader) ([]Package, error) {
    40  	bytes, err := io.ReadAll(reader)
    41  	if err != nil {
    42  		return nil, fmt.Errorf("unable to read file: %w", err)
    43  	}
    44  
    45  	// Check if the file is empty
    46  	if len(bytes) == 0 {
    47  		return nil, errors.New("file is empty")
    48  	}
    49  
    50  	var podfile podfileLock
    51  	if err = yaml.Unmarshal(bytes, &podfile); err != nil {
    52  		return nil, fmt.Errorf("unable to parse YAML: %w", err)
    53  	}
    54  
    55  	var pkgs []Package
    56  	for _, podInterface := range podfile.Pods {
    57  		var podBlob string
    58  		switch v := podInterface.(type) {
    59  		case map[string]any:
    60  			for k := range v {
    61  				podBlob = k
    62  			}
    63  		case string:
    64  			podBlob = v
    65  		default:
    66  			return nil, errors.New("malformed Podfile.lock")
    67  		}
    68  
    69  		splits := strings.Split(podBlob, " ")
    70  		if len(splits) < 2 {
    71  			return nil, fmt.Errorf("unexpected format in Pods: %s", podBlob)
    72  		}
    73  		podName := splits[0]
    74  		podVersion := strings.TrimSuffix(strings.TrimPrefix(splits[1], "("), ")")
    75  		pkgs = append(pkgs, Package{
    76  			Name:    podName,
    77  			Version: podVersion,
    78  		})
    79  	}
    80  
    81  	return pkgs, nil
    82  }