<commit_before>module FastlaneCore
  # This class checks if a specific certificate is installed on the current mac
  class CertChecker
    def self.installed?(path)
      raise "Could not find file '#{path}'".red unless File.exist?(path)

      ids = installed_identies
      finger_print = sha1_fingerprint(path)

      return ids.include? finger_print
    end

    # Legacy Method, use `installed?` instead
    def self.is_installed?(path)
      installed?(path)
    end

    def self.installed_identies
      install_wwdr_certificate unless wwdr_certificate_installed?

      available = list_available_identities
      # Match for this text against word boundaries to avoid edge cases around multiples of 10 identities!
      if /\b0 valid identities found\b/ =~ available
        UI.error([
          "There are no local code signing identities found.",
          "You can run `security find-identity -v -p codesigning` to get this output.",
          "This Stack Overflow thread has more information: http://stackoverflow.com/q/35390072/774.",
          "(Check in Keychain Access for an expired WWDR certificate: http://stackoverflow.com/a/35409835/774 has more info.)"
        ].join(' '))
      end

      ids = []
      available.split("\n").each do |current|
        next if current.include? "REVOKED"
        begin
          (ids << current.match(/.*\) (.*) \".*/)[1])
        rescue
          # the last line does not match
        end
      end

      return ids
    end

    def self.list_available_identities
      `security find-identity -v -p codesigning`
    end

    def self.wwdr_certificate_installed?
      certificate_name = "Apple Worldwide Developer Relations Certification Authority"
      response = Helper.backticks("security find-certificate -c '#{certificate_name}'", print: $verbose)
      return response.include?("attributes:")
    end

    def self.install_wwdr_certificate
      Dir.chdir('/tmp') do
        url = 'https://developer.apple.com/certificationauthority/AppleWWDRCA.cer'
        filename = File.basename(url)
        `curl -O #{url} && security import #{filename} -k login.keychain`
        UI.user_error!("Could not install WWDR certificate") unless $?.success?
      end
    end

    def self.sha1_fingerprint(path)
      result = `openssl x509 -in "#{path}" -inform der -noout -sha1 -fingerprint`
      begin
        result = result.match(/SHA1 Fingerprint=(.*)/)[1]
        result.delete!(':')
        return result
      rescue
        Helper.log.info result
        raise "Error parsing certificate '#{path}'"
      end
    end
  end
end<commit_msg>Search keychain when installing WWDR certificate<commit_after>module FastlaneCore
  # This class checks if a specific certificate is installed on the current mac
  class CertChecker
    def self.installed?(path)
      raise "Could not find file '#{path}'".red unless File.exist?(path)

      ids = installed_identies
      finger_print = sha1_fingerprint(path)

      return ids.include? finger_print
    end

    # Legacy Method, use `installed?` instead
    def self.is_installed?(path)
      installed?(path)
    end

    def self.installed_identies
      install_wwdr_certificate unless wwdr_certificate_installed?

      available = list_available_identities
      # Match for this text against word boundaries to avoid edge cases around multiples of 10 identities!
      if /\b0 valid identities found\b/ =~ available
        UI.error([
          "There are no local code signing identities found.",
          "You can run `security find-identity -v -p codesigning` to get this output.",
          "This Stack Overflow thread has more information: http://stackoverflow.com/q/35390072/774.",
          "(Check in Keychain Access for an expired WWDR certificate: http://stackoverflow.com/a/35409835/774 has more info.)"
        ].join(' '))
      end

      ids = []
      available.split("\n").each do |current|
        next if current.include? "REVOKED"
        begin
          (ids << current.match(/.*\) (.*) \".*/)[1])
        rescue
          # the last line does not match
        end
      end

      return ids
    end

    def self.list_available_identities
      `security find-identity -v -p codesigning`
    end

    def self.wwdr_certificate_installed?
      certificate_name = "Apple Worldwide Developer Relations Certification Authority"
      keychain = wwdr_keychain
      response = Helper.backticks("security find-certificate -c '#{certificate_name}' #{keychain}", print: $verbose)
      return response.include?("attributes:")
    end

    def self.install_wwdr_certificate
      Dir.chdir('/tmp') do
        url = 'https://developer.apple.com/certificationauthority/AppleWWDRCA.cer'
        filename = File.basename(url)
        keychain = wwdr_keychain
        keychain.prepend("-k ") unless keychain.empty?
        `curl -O #{url} && security import #{filename} #{keychain}`
        UI.user_error!("Could not install WWDR certificate") unless $?.success?
      end
    end

    def self.wwdr_keychain
      priority = [
        "security list-keychains -d user",
        "security default-keychain -d user"
      ]
      priority.each do |command|
        keychains = Helper.backticks(command, print: $verbose).split("\n")
        unless keychains.empty?
          # Select first keychain name from returned keychains list
          return keychains[0].strip.tr('"', '').split(File::SEPARATOR)[-1]
        end
      end
      return ""
    end

    def self.sha1_fingerprint(path)
      result = `openssl x509 -in "#{path}" -inform der -noout -sha1 -fingerprint`
      begin
        result = result.match(/SHA1 Fingerprint=(.*)/)[1]
        result.delete!(':')
        return result
      rescue
        Helper.log.info result
        raise "Error parsing certificate '#{path}'"
      end
    end
  end
end
{'fraction_non_alphanumeric': 0.1010793215692993, 'fraction_numerical': 0.011992461881103306, 'mean_word_length': 2.5532562385879487, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4661685', 'n_tokens_mistral': 1735, 'n_tokens_neox': 1630, 'n_words': 494}