Skip to content

Commit f980d8f

Browse files
committed
Add list-key-ids command
1 parent 7e41e37 commit f980d8f

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

lib/gitlab_keys.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ def exec
3939
rm_key
4040
when 'list-keys';
4141
list_keys
42+
when 'list-key-ids';
43+
list_key_ids
4244
when 'clear';
4345
clear
4446
when 'check-permissions';
@@ -75,6 +77,17 @@ def list_keys
7577
keys
7678
end
7779

80+
def list_key_ids
81+
$logger.info 'Listing all key IDs'
82+
open_auth_file('r') do |f|
83+
f.each_line do |line|
84+
matchd = line.match(/key-(\d+)/)
85+
next unless matchd
86+
puts matchd[1]
87+
end
88+
end
89+
end
90+
7891
def batch_add_keys
7992
lock(300) do # Allow 300 seconds (5 minutes) for batch_add_keys
8093
open_auth_file('a') do |file|

spec/gitlab_keys_spec.rb

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,23 @@
8080
end
8181
end
8282

83+
describe :list_key_ids do
84+
let(:gitlab_keys) { build_gitlab_keys('list-key-ids') }
85+
before do
86+
create_authorized_keys_fixture(
87+
existing_content:
88+
"key-1\tssh-dsa AAA\nkey-2\tssh-rsa BBB\nkey-3\tssh-rsa CCC\nkey-9000\tssh-rsa DDD\n"
89+
)
90+
end
91+
92+
it 'outputs the key IDs, separated by newlines' do
93+
output = capture_stdout do
94+
gitlab_keys.send(:list_key_ids)
95+
end
96+
output.should match "1\n2\n3\n9000"
97+
end
98+
end
99+
83100
describe :batch_add_keys do
84101
let(:gitlab_keys) { build_gitlab_keys('batch-add-keys') }
85102
let(:fake_stdin) { StringIO.new("key-12\tssh-dsa ASDFASGADG\nkey-123\tssh-rsa GFDGDFSGSDFG\n", 'r') }
@@ -288,9 +305,9 @@ def argv(*args)
288305
end
289306
end
290307

291-
def create_authorized_keys_fixture
308+
def create_authorized_keys_fixture(existing_content: 'existing content')
292309
FileUtils.mkdir_p(File.dirname(tmp_authorized_keys_path))
293-
open(tmp_authorized_keys_path, 'w') { |file| file.puts('existing content') }
310+
open(tmp_authorized_keys_path, 'w') { |file| file.puts(existing_content) }
294311
gitlab_keys.stub(auth_file: tmp_authorized_keys_path)
295312
end
296313

@@ -301,4 +318,13 @@ def tmp_authorized_keys_path
301318
def tmp_lock_file_path
302319
tmp_authorized_keys_path + '.lock'
303320
end
321+
322+
def capture_stdout(&blk)
323+
old = $stdout
324+
$stdout = fake = StringIO.new
325+
blk.call
326+
fake.string
327+
ensure
328+
$stdout = old
329+
end
304330
end

0 commit comments

Comments
 (0)