(SOLVED) Why doesn't the Ruby Git gem see my variables? - ruby

I'm building a simple utility for cloning down git repositories of other ruby programs my company has built, then install and configure them.
So, I'm very new to Ruby, so I apologize if this is a super noob question.
But I have a class that handles creating the directories it needs and cloning the repo, but it's returning this error when I run the code, and I don't know why...
This is the error:
Cloning the requested Git Repository now!
-----------------------------------------
C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/git-1.12.0/lib/git/lib.rb:1125:in `command': git "-c" "core.quotePath=true"
"-c" "color.ui=false" clone "--" "" "{:path=>\\"\\", :bare=>true}" 2>&1:fatal: The empty string is not a valid path (Git::GitExecuteError)
from C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/git-1.12.0/lib/git/lib.rb:116:in `clone'
from C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/git-1.12.0/lib/git/base.rb:21:in `clone'
from C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/git-1.12.0/lib/git.rb:176:in `clone'
from C:/Users/conno/OneDrive/Desktop/Ruby Installer/Pixelated-Ruby-Installer/classes/Gitclone.rb:43:in `clone'
from ./starter.rb:48:in `<main>'
This is my code (again, remember I am very new. So literally any and all advice is helpful):
#!/bin/ruby
# class declaration
class Gitclone
require "fileutils"
require "git"
require "rubygems"
# attribute reader so other classes/methods can read the vars in this class
attr_reader :giturl, :destpa
# init class method to set instance variables for giturl and destination path
def initialize(giturl, destpa)
#giturl = giturl
#destpa = destpa
end
# class method to create directories and clone git repositories
def self.clone
# I don't think this needs to be here. It was added for the sake of seeing if it would fix the issue
giturl = #giturl
destpa = #destpa
# see last comment about the above 2 lines
puts "Creating directories!"
21.times {
print "-"
}
puts ""
sleep(2)
# right now, this is hardcoded. I should probably make it it's own method we can call...
# it creates new directories
FileUtils.mkdir_p "/etc/pixelated/ruby/bin"
puts "We have created the /etc/pixelated/ruby/bin directory!"
54.times {
print "-"
}
puts ""
sleep(2)
puts "Cloning the requested Git Repository now!"
41.times {
print "-"
}
puts ""
sleep(2)
# this bit here simply uses the Git gem to clone the repository URL stored in the 'giturl' instance variable to the path stored in the 'destpa' instance variable
git = Git.clone("#{giturl}", path: "#{destpa}", bare: true)
# notify the user if the repository was cloned successfuly
if Dir.exist?("/etc/pixelated/ruby/bin/$softtype")
then
puts "Successfully Cloned the Repo!"
puts ""
else
puts "ERROR! Repo was not cloned! Did you give us the right link?"
puts ""
end
end
end
I did declare the variables that I'm using, yet it apparently thinks they haven't?
I am almost certain that this is my noob brain using variable wrong...
Can someone offer me some guidance please?
EDIT: I may have answered my own question. I realized I'm booted into my Windows OS, not Arch Linux, and my code is using Linux paths, not Windows paths. Gonna put it up on one of my ubuntu servers and see if it works there.

Related

puts line breaking in_branch in git gem?

I'm automating a bit of git workflow and have found some curious behaviour when using the git gem's in_branch method and wondered if anyone could explain why or how this issue occurs? Here's some test code that should reproduce the issue:
#!/usr/bin/env ruby
require 'git'
# git details
repo_name = 'SOME_REPO'
working_dir = "#SOME_DIR/git_test_repo"
repo_owner = 'SOME_GIT_USER'
repo_host = 'SOME_GIT_HOST'
repo_dir = "#{working_dir}/#{repo_name}"
remote_repo = "git##{repo_host}:#{repo_owner}/#{repo_name}.git"
branch_name = 'testbranch'
commit_message = 'log line breaking in_branch test'
Dir.mkdir(working_dir) unless Dir.exist?(working_dir)
Dir.chdir(working_dir)
Git.clone(remote_repo, repo_name) unless Dir.exists?(repo_dir)
repo = Git.open(repo_dir)
repo.pull(remote = 'origin', branch = 'master')
repo.branch(branch_name).in_branch(message = commit_message) do
File.write(repo_dir + '/test.txt', Time.now)
repo.add('.')
# -----this line breaks it --------------
puts 'committing changes'
# ---------------------------------------
end
When this code runs, the last puts line before the end of the in_branch block, when actually run, somehow causes the changes in the branch to be reverted, but when it's commented out, all the code behaves as expected. I've tested output lines anywhere in the block, and they all behave fine. It seems to happen across many versions of ruby (custom installs, rvm installs) and different OS's (linuxes and mac).
Is there some arcane behaviour of ruby and its terminal output I need to be aware of here?
Not really "arcane behavior of ruby". But the result of the last line in a method is what the method returns. Putting a puts in that position will usually break the method.
Just testing and I see the same behavior using print (which does not add a newline).
This is not a newline issue, moving the (now print) line above the repo.add line and all works.
Anymore thoughts?

Running ruby code on cucumber

I'm new to cucumber and I just found out Before hooks.
I'm already doing this on minitest/spec.
I want to create a git repository before any scenario and destroy it after.
this is what I have:
Before do
require 'tmpdir'
#directory = Dir.mktmpdir('temp-repo')
#orig_directory = Dir.pwd
Dir.chdir(#directory)
`git init`
`touch dummy`
`git add .`
`git commit -m 'dummy commit'`
end
After do
Dir.chdir(#orig_directory)
FileUtils.rmtree(#directory)
end
But when i run cucumber it fails with this message:
Lexing error on line 6: ' #directory = Dir.mktmpdir('temp-repo')'
I already looked into the wiki and some other questions here but can't figure out how to get that working.
The hooks should be registered in the support files (for example features/support/env.rb) not in your features.
It's stated in the second sentence of the wiki.

How to get superuser privileges in Ruby?

So, I've been working on a Ruby script that blocks reddit during my school hours (useful stuff). Here's the code:
require 'fileutils'
puts "-----------------------------------"
puts "Welcome to the hosts file modifier!"
puts "-----------------------------------"
puts "Option A: Use modified hosts"
puts "Option B: Use original hosts"
puts "Option C: Do nothing"
puts "Please enter your choice: "
input = gets.chomp.downcase
t = Time.now
# Time.now is used is conjunction with function 'original', in option 'b'
def modified
# This function copies the modified (redditblocking) hosts file from Documents to /etc
puts "Moving original hosts file out of /etc"
FileUtils.mv('/etc/hosts', '/Users/(usernameobscured)/Documents/OriginalHosts/hosts')
puts "Done. Now copying modified hosts to /etc"
FileUtils.cp('/Users/(usernameobscured)/Documents/ModifiedHosts/hosts', '/etc/hosts')
puts "Done"
end
def original
# This function deletes the modified hosts file from /etc (since we have a copy in Documents)
# and then moves the original hosts file back to /etc
puts "Deleting modified hosts file from /etc"
FileUtils.rm_rf('etc/hosts')
puts "Done. Now copying original hosts to /etc"
FileUtils.mv('/Users/(usernameobscured)/Documents/OriginalHosts/hosts', '/etc/hosts')
puts "Done"
end
def nothing
# This does... nothing. Literally.
puts "Doing nothing"
end
if input == 'a'
modified
end
if input == 'b'
# Here's when using Time.now becomes helpful: if the hour of the day is less than 5PM,
# then the original hosts file can't be moved back (don't wanna be on reddit during school hours!)
if t.hour > 17
original
elsif t.hour < 17
puts "Too early to use original hosts file. Come back at 5PM"
end
end
if input == 'c'
# Nothing...
nothing
end
As you can see, it moves a modified hosts file from my Documents folder to /etc. The problem I'm having though, as per OS X/Unix security measures, is that I have to run the script via sudo or logged in as root. This is a minor nuisance, however, it's one that I believe can be fixed within the code. How can I get superuser privileges, OR write access to /etc temporarily, via my ruby script, so that I can simply run the script without sudo/root?
Per Unix security model, it is not possible to gain root access without some sort of external intervention (setuid set to the executable, running as root user). Otherwise we would have a gaping security hole.
I am not clear what is exactly your issue of using sudo or rvmsudo or against setting the script setuid (it is possible to configure sudo to not require password for narrowly defined set of commands).
I would just suggest making the various versions of host files group writable by a group that you are member of.
According to this site : http://ruby.about.com/od/rubyversionmanager/qt/Rvm-And-Sudo.htm
you can start executing the script using the rvmsudo command. In your terminal window or shell script:
rvmsudo ruby blockreddit.rb

Git pull multiple local repositories with script (ruby?)

I have ~30 git repositories cloned from github that I use for web/ruby/javascript development. Is it possible to bulk update all of them with a script?
I have everything pretty organized (folder structure):
- Workspace
- Android
- Chrome
- GitClones
- Bootstrap
~ etc...30 some repositories
- iPhone
- osx
- WebDev
I have a ruby script to clone repositories with octokit, but are there any suggestions on how to do git pull (overwriting/rebasing local) in all the repositories under GitClones?
Normally I would just do a pull whenever I was about to use that repo, but I am going to a place where internet connectivity is only going to be available sometimes. So I would like to update everything I can while I have internet.
Thanks! (Running osx 10.8.2)
If you must do it in Ruby, here's a quick and dirty script:
#!/usr/bin/env ruby
Dir.entries('./').select do |entry|
next if %w{. .. ,,}.include? entry
if File.directory? File.join('./', entry)
cmd = "cd #{entry} && git pull"
`#{cmd}`
end
end
Don't forget to chmod +x the file you copy this into and ensure it's in your GitClones directory.
Sure, but why use ruby when shell will suffice?
function update_all() {
for dir in GitClones/*; do
cd "$dir" && git pull
done
}
Change beginning of glob to taste. This does two useful things:
It only git pull when it contains .git subdir
It skips dot (.) dirs since no one has git repos which start with a dot.
Enjoy
# Assumes run from Workspace
Dir['GitClones/[^.]*'].select {|e| File.directory? e }.each do |e|
Dir.chdir(e) { `git pull` } if File.exist? File.join(e, '.git')
end
Revised to provider better output and be OS agnostic. This one cleans local changes, and updates code.
#!/usr/bin/env ruby
require 'pp'
# no stdout buffering
STDOUT.sync = true
# checks for windows/unix for chaining commands
OS_COMMAND_CHAIN = RUBY_PLATFORM =~ /mswin|mingw|cygwin/ ? "&" : ";"
Dir.entries('.').select do |entry|
next if %w{. .. ,,}.include? entry
if File.directory? File.join('.', entry)
if File.directory? File.join('.', entry, '.git')
full_path = "#{Dir.pwd}/#{entry}"
git_dir = "--git-dir=#{full_path}/.git --work-tree=#{full_path}"
puts "\nUPDATING '#{full_path}' \n\n"
puts `git #{git_dir} clean -f #{OS_COMMAND_CHAIN} git #{git_dir} checkout . #{OS_COMMAND_CHAIN} git #{git_dir} pull`
end
end
end

Check if a git branch exists in the local repository with ruby?

What would be the best way of checking if git branch exists in the local git repository with ruby? My ruby skills are not that good, so would like to know the best way of going about it :) Thanks.
There are ruby libraries for accessing git repositories, one being grit.
To install use [sudo] gem install grit.
$ irb
>> require 'grit'
=> true
>> repo = Grit::Repo.new('/path/to/your/repo/')
=> #<Grit::Repo "/path/to/your/repo/.git">
>> repo.branches
=> [#<Grit::Head "master">, #<Grit::Head "some-topic-branch">, ...]
I ended up coming up with this:
# Check if a Branch Exists
def branch_exists(branch)
branches = run("git branch",false)
regex = Regexp.new('[\\n\\s\\*]+' + Regexp.escape(branch.to_s) + '\\n')
result = ((branches =~ regex) ? true : false)
return result
end
Where run is a backtick expression. The reasoning is that the code is to be highly portable and is not allowed any other dependencies. Whereas git is installed in the environment.

Resources