diff --git a/lib/gpgme/key.rb b/lib/gpgme/key.rb index dbd00e4..010e9b8 100644 --- a/lib/gpgme/key.rb +++ b/lib/gpgme/key.rb @@ -63,6 +63,26 @@ def find(secret, keys_or_names = nil, purposes = []) keys end + # Works similar as {.find}, however it restricts the way the keys are looked up. + # GPG has the issue that finding a key for bar@example.com, also returns a key + # for foobar@example.com. + # This can be restricted by adding <> around the address: . + # Hence {.find_exact} simply wraps <> around each email you passed to the method and delegates + # the rest to {.find} + # + # @example + # GPGME::Key.find_exact(:public, "bar@example.com") + # # => return the public key of bar@example.com, but not for + # # foobar@example.com + def find_exact(secret, keys_or_names = nil, purposes = []) + keys_or_names = [""] if keys_or_names.nil? || (keys_or_names.is_a?(Array) && keys_or_names.empty?) + find( + secret, + [keys_or_names].flatten.collect{|k| if k =~ /.*@.*/ && !(k =~ /<.*@.*>/) then "<#{k}>" else k end }, + purposes + ) + end + def get(fingerprint) Ctx.new do |ctx| ctx.get_key(fingerprint) diff --git a/test/key_test.rb b/test/key_test.rb index 5128b28..cc8bfeb 100644 --- a/test/key_test.rb +++ b/test/key_test.rb @@ -53,6 +53,28 @@ assert keys.empty? end end + + describe :find_exact do + it "wraps an email address with angle brackets" do + GPGME::Key.expects(:find).with(:public,[''],[]) + GPGME::Key.find_exact(:public,'bar@example.com') + end + + it "wraps multiple email addresses with angle brackets" do + GPGME::Key.expects(:find).with(:public,['',''],[]) + GPGME::Key.find_exact(:public,['bar@example.com','foo@example.com']) + end + + it "does not touch other strings than email addresses" do + GPGME::Key.expects(:find).with(:public,['Bar Example'],[]) + GPGME::Key.find_exact(:public,'Bar Example') + end + + it "does the same in mixed mode" do + GPGME::Key.expects(:find).with(:public,['','Foo Example'],[]) + GPGME::Key.find_exact(:public,['bar@example.com','Foo Example']) + end + end describe :export do # Testing the lazy way with expectations. I think tests in