Class: Travis::CLI::Gh::Write

Inherits:
RepoCommand
  • Object
show all
Includes:
GitHub::Authenticated, GitHub::Error
Defined in:
lib/travis/cli/gh/write.rb

Direct Known Subclasses

Upload

Constant Summary collapse

USER_FORMAT =
/^(?<name>.+) <(?<email>.+@.+)>$/

Instance Method Summary collapse

Methods included from GitHub::Authenticated

#auth, #gh, #plugin_config

Methods included from GitHub::Error

#gh_error

Instance Method Details

#create(path, content) ⇒ Object



40
41
42
# File 'lib/travis/cli/gh/write.rb', line 40

def create(path, content)
  put(path, content, message: "Create #{path}")
end

#create?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/travis/cli/gh/write.rb', line 65

def create?
  @create.nil? ? @update.nil? : @create
end

#get(path) ⇒ Object



54
55
56
57
58
# File 'lib/travis/cli/gh/write.rb', line 54

def get(path)
  path = "repos/#{repository.slug}/contents/#{path}"
  path << "?ref=#{branch}" if branch
  gh[path]
end

#parse_user(field) ⇒ Object



60
61
62
63
# File 'lib/travis/cli/gh/write.rb', line 60

def parse_user(field)
  error "wrong format for #{field}, should be NAME <EMAIL>." unless match = USER_FORMAT.match(send(field).to_s)
  { name: match[:name], email: match[:email] }
end

#put(path, content = "", encoded_content: Base64.encode64(content), **options) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/travis/cli/gh/write.rb', line 44

def put(path, content = "", encoded_content: Base64.encode64(content), **options)
  options[:message]   = message if message
  options[:branch]    = branch  if branch
  options[:content]   = encoded_content.gsub("\n", "")
  options[:path]      = path
  options[:committer] = parse_user(:committer) if committer
  options[:author]    = parse_user(:author)    if author
  gh.put("/repos/#{repository.slug}/contents/#{path}", options)
end

#run(path) ⇒ Object



18
19
20
21
22
# File 'lib/travis/cli/gh/write.rb', line 18

def run(path)
  write(path, input.read)
rescue GH::Error => e
  gh_error(e)
end

#update(path, content, current = get(path)) ⇒ Object



34
35
36
37
38
# File 'lib/travis/cli/gh/write.rb', line 34

def update(path, content, current = get(path))
  error "#{path} is not a file" unless current.respond_to?(:to_hash) and current['type'] == 'file'
  content = Base64.decode64(current['content']) + content if append?
  put(path, content, message: "Update #{path}", sha: current['sha'])
end

#update?Boolean

Returns:

  • (Boolean)


69
70
71
# File 'lib/travis/cli/gh/write.rb', line 69

def update?
  @update.nil? ? @create.nil? : @update
end

#write(path, content) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/travis/cli/gh/write.rb', line 24

def write(path, content)
  current = get(path)
  error "file already exists" unless update?
  update(path, content, current)
rescue GH::Error => e
  gh_error(e) unless e.info[:response_status] == 404
  error "file does not exist" unless create?
  create(path, content)
end