Class: KnifeGithubRepoCreate::GithubRepoCreate

Inherits:
Chef::Knife
  • Object
show all
Defined in:
lib/chef/knife/github_repo_create.rb

Instance Method Summary collapse

Instance Method Details

#create_cookbook(name, type, tmp) ⇒ Object

Create the cookbook template for upload

Parameters:

  • name (String)

    cookbook name type [String] type of cookbook tmp [String] temp location



257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/chef/knife/github_repo_create.rb', line 257

def create_cookbook(name, type, tmp)
  target = File.join(tmp, name)
  template_org = locate_config_value("github_template_org")
  if template_org.nil? || template_org.empty?
    Chef::Log.fatal("Cannot find github_template_org within your configuration")  
  else

    github_url = @github_url.gsub('http://', 'git://') if @github_url =~ /^http:\/\/.*$/
    github_url = @github_url.gsub('https://', 'git://') if @github_url =~ /^https:\/\/.*$/
 
    template_path = File.join(github_url, template_org, "chef_template_#{type}.git") 
    shell_out!("git clone #{template_path} #{target}") # , :cwd => cookbook_path)
  end
end

#get_body_json(cookbook_name, description = "Please fill in the description.") ⇒ Object

Create the json body with repo config for POST information

Parameters:

  • name (String)

    cookbook name



274
275
276
277
278
279
280
281
282
283
# File 'lib/chef/knife/github_repo_create.rb', line 274

def get_body_json(cookbook_name, description="Please fill in the description.")
  body = {
    "name" => cookbook_name,
    "description" => description,
    "private" => false,
    "has_issues" => true,
    "has_wiki" => true,
    "has_downloads" => true
  }.to_json
end

#get_github_tokenObject

Get the OAuth authentication token from config or command line

Parameters:

  • nil


287
288
289
290
291
292
293
294
# File 'lib/chef/knife/github_repo_create.rb', line 287

def get_github_token()
  token = locate_config_value('github_token')
  if token.nil? || token.empty?
    Chef::Log.error("Please specify a github token")
    exit 1
  end
  token
end

#get_repo_descriptionstring

User selection on repo description

Returns:

  • (string)


145
146
147
148
149
150
151
152
153
154
# File 'lib/chef/knife/github_repo_create.rb', line 145

def get_repo_description
  question = "\nPlease enter a description for the repository: "

  desc = input question
  if desc.nil? || desc.empty?
    Chef::Log.error("Please enter a repository description")
    get_repo_description
  end
  desc
end

#get_repo_typestring

User selection on repo type

Returns:

  • (string)


158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/chef/knife/github_repo_create.rb', line 158

def get_repo_type
  question = "\nPlease select the repository type that you want to create.\n"
  question += "  1 - Empty\n"
  question += "  2 - Cookbook Application\n"
  question += "  3 - Cookbook Wrapper\n"
  question += "  4 - Cookbook Role\n"
  question += "Type: "

  type = input question
  case type
    when '1'
      return 'empty'
    when '2'
      return "application"
    when '3'
      return "wrapper"
    when '4'
      return "role"
    else
      Chef::Log.error("Please select 1-4 to continue.")
      get_repo_type
  end
end

#get_useremailObject

Get the email from passwd file or git config

Parameters:

  • nil


246
247
248
249
250
251
# File 'lib/chef/knife/github_repo_create.rb', line 246

def get_useremail()
  email = nil
  git_user_email = %x(git config user.email).strip
  email = git_user_email if git_user_email
  email
end

#get_usernameObject

Get the username from passwd file or git config

Parameters:

  • nil


235
236
237
238
239
240
241
242
# File 'lib/chef/knife/github_repo_create.rb', line 235

def get_username()
  username = ENV['USER']
  passwd_user = %x(getent passwd #{username} | cut -d ':' -f 5).chomp
  username = passwd_user if passwd_user
  git_user_name = %x(git config user.name).strip
  username = git_user_name if git_user_name
  username
end

#git_commit_and_push(cookbook_path, github_ssh_url) ⇒ Object

Set the username in README.md

Parameters:

  • cookbook_path (String)

    cookbook path github_ssh_url [String] github ssh url from repo



194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/chef/knife/github_repo_create.rb', line 194

def git_commit_and_push(cookbook_path, github_ssh_url)
  if File.exists?(File.join(cookbook_path, ".git"))
    shell_out("git remote rm origin", :cwd => cookbook_path)
  else  
    shell_out!("git init", :cwd => cookbook_path)
  end
  shell_out!("echo - $(date): Uploaded with knife github plugin. >> CHANGELOG.md ", :cwd => cookbook_path)
  shell_out!("git add .", :cwd => cookbook_path) 
  shell_out!("git commit -m 'creating initial cookbook structure from the knife-github plugin' ", :cwd => cookbook_path) 
  shell_out!("git remote add origin #{github_ssh_url} ", :cwd => cookbook_path) 
  shell_out!("git push -u origin master", :cwd => cookbook_path) 
end

#input(prompt = "", newline = true) ⇒ Object



186
187
188
189
# File 'lib/chef/knife/github_repo_create.rb', line 186

def input(prompt="", newline=true)
  prompt += "\n" if newline
  Readline.readline(prompt).squeeze(" ").strip
end

#post_request(url, body, token) ⇒ Object

Post Get the OAuth authentication token from config or command line

Parameters:

  • url (String)

    target url (organization or user) body [JSON] json data with repo configuration token [String] token sring



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/chef/knife/github_repo_create.rb', line 300

def post_request(url, body, token)

  if @github_ssl_verify_mode == "verify_none"
    config[:ssl_verify_mode] = :verify_none
  elsif @github_ssl_verify_mode == "verify_peer"
    config[:ssl_verify_mode] = :verify_peer
  end

  Chef::Log.debug("URL: " + url.to_s)

  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host,uri.port)
  if uri.scheme == "https"
    http.use_ssl = true
    if  @github_ssl_verify_mode == "verify_none"
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    else
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    end
  end
   
  req = Net::HTTP::Post.new(uri.path, initheader = {"Authorization" => "token #{token}"})
  req.body = body        
  response = http.request(req)
  
  unless response.code == "201" then
    puts "Error #{response.code}: #{response.message}"
    puts JSON.pretty_generate(JSON.parse(response.body))
    puts "URL: #{url}"
    exit 1
  end

  begin
    json = JSON.parse(response.body)
  rescue
    ui.warn "The result on the RESTRequest is not in json format"
    ui.warn "Output: " + response.body
    exit 1
  end
  json
end

#runObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/chef/knife/github_repo_create.rb', line 61

def run
  extend Chef::Mixin::ShellOut

  # validate base options from base module.
  validate_base_options      

  # Display information if debug mode is on.
  display_debug_info

  # Get the name_args from the command line
  name = name_args.first
  name_args.shift

  # Get the organization name from config
  org = locate_config_value('github_organizations').first

  if name.nil? || name.empty? 
    Chef::Log.error("Please specify a repository name")
    exit 1
  end 
   
  desc = get_repo_description
  type = get_repo_type

  if config[:github_user_repo]
    url = @github_url + "/api/" + @github_api_version + "/user/repos"
    Chef::Log.debug("Creating repository in user environment")
  else
    url = @github_url + "/api/" + @github_api_version + "/orgs/#{org}/repos"
    Chef::Log.debug("Creating repository in organization: #{org}")
  end

  @github_tmp = locate_config_value("github_tmp") || '/var/tmp/gitcreate'
  @github_tmp = "#{@github_tmp}#{Process.pid}"

  # Get token information
  token = get_github_token()

  # Get body data for post
  body = get_body_json(name, desc)

  # Creating the local repository or using existing one.
  cookbook_dir = get_cookbook_path(name) || ""

  if File.exists?(cookbook_dir)
    Chef::Log.debug("Using local repository from #{cookbook_dir}")

    # Creating the github repository
    Chef::Log.debug("Creating the github repository")
    repo = post_request(url, body, token)
    github_ssh_url = repo['ssh_url']

    Chef::Log.debug("Commit and push local repository")
    # Initialize the local git repo
    git_commit_and_push(cookbook_dir, github_ssh_url)

    puts "Finished creating #{name} and uploading #{cookbook_dir}"
  else
    Chef::Log.debug("Creating the repository based on #{type} template")
    create_cookbook(name, type, @github_tmp)
  
    cookbook_dir = File.join(@github_tmp, name)
  
    # Updateing template information if needed.
    update_template_files(name, cookbook_dir, desc)
  
    # Creating the github repository
    Chef::Log.debug("Creating the github repository")
    repo = post_request(url, body, token)
    github_ssh_url = repo['ssh_url']
  
    Chef::Log.debug("Commit and push local repository")      
    # Initialize the local git repo
    git_commit_and_push(cookbook_dir, github_ssh_url)
  
    Chef::Log.debug("Removing temp files")
    FileUtils.remove_entry(@github_tmp)
    puts "Finished creating and uploading #{name}"
  end
end

#update_template_files(name, cookbook_path, description) ⇒ Object

Update all template files with the right information

Parameters:

  • name (String)

    cookbook path



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/chef/knife/github_repo_create.rb', line 209

def update_template_files(name, cookbook_path, description)
  files = Dir.glob("#{cookbook_path}/**/*").select{ |e| File.file? e }
  user    = get_username || "Your Name" 
  email   = get_useremail || "Your Email"
  company = "Schuberg Philis"
  year    = Time.now.year
  date    = Time.now
  files.each do |file|
    contents = ""
    File.foreach(file) do |line|
      line.gsub!(/DESCRIPTION/, description)
      line.gsub!(/COOKBOOK/, name)
      line.gsub!(/COMPANY/, company)
      line.gsub!(/NAME/, user)
      line.gsub!(/EMAIL/, email)
      line.gsub!(/YEAR/, year.to_s)
      line.gsub!(/DATE/, date.to_s)
      contents += line
    end
    File.open(file, 'w') {|f| f.write(contents) }
  end
  return nil
end