Class: NetRC

Inherits:
Object
  • Object
show all
Defined in:
lib/netrc.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeNetRC

Returns a new instance of NetRC.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/netrc.rb', line 4

def initialize
  @path = "#{ENV['HOME']}/.netrc"
  #Check if there is a .netrc file to read from
  if File.exists?(path)
    puts "Success? #{parseToken("#{ENV['HOME']}/.netrc")}"
  else
    #create the .netrc file in home directory
    puts "Creating a .netrc file for you in #{ENV['HOME']}"
    new_file = File.new("#{ENV['HOME']}/.netrc", "a")
    generateToken(new_file)
    new_file.close
  end

end

Instance Attribute Details

#pathObject

Returns the value of attribute path.



3
4
5
# File 'lib/netrc.rb', line 3

def path
  @path
end

#tokenObject

Returns the value of attribute token.



3
4
5
# File 'lib/netrc.rb', line 3

def token
  @token
end

#userObject

Returns the value of attribute user.



3
4
5
# File 'lib/netrc.rb', line 3

def user
  @user
end

Instance Method Details

#checkArg(pattern, string) ⇒ Object

Raises:

  • (ArgumentError)


51
52
53
54
55
# File 'lib/netrc.rb', line 51

def checkArg (pattern, string)
  values = string.scan(pattern).flatten.uniq
  raise ArgumentError, "Argument is invalid: #{string}" unless values.length==1
  return values.first
end

#generateToken(file) ⇒ Object

need to prompt for user



36
37
38
39
40
41
42
43
44
45
# File 'lib/netrc.rb', line 36

def generateToken (file)
  puts "Generating token..."
  puts "Please provide username:"
  @user = STDIN.gets.chomp

  puts "Need to generate token automatically"
  response = shell %Q[curl -i -u #{@user} -d '{"scopes": ["repo"],"note": "gitFlone"}' https://api.github.com/authorizations]
  @token = checkArg(%r[(?<="token": ")(.{40})(?=")],response)
  file.puts("machine github.com #{@user} #{@token}")
end

#has_token?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/netrc.rb', line 57

def has_token?
  return !@token.nil? && @token.length==40
end

#parseToken(path) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/netrc.rb', line 19

def parseToken (path)
  begin
    f = File.open("#{path}", "r")
    netRCPattern = %r[(machine github.com) (\S+) (\S+)]
    tokenPattern = %r[.{40}]
    githubLine = f.each_line.select{|line|line.match(netRCPattern)}
    values = githubLine.first.split(" ")
    @user = values[2]
    @token = values[3] if (values[3].index(tokenPattern))
    f.close
    true
  rescue
    false
  end
end

#shell(command) ⇒ Object



47
48
49
# File 'lib/netrc.rb', line 47

def shell (command)
  `#{command}`
end