lib/raykit/git/repositories.rb



require_relative('./directory.rb')

module Raykit
    module Git
        # Functionality to manage a remote git repository

        class Repositories < Array
            attr_accessor :filename

            def initialize(filename)
                @filename=filename
                open(@filename)
            end

            def open(filename)
                if(File.exist?(filename))
                    JSON.parse(File.read(filename)).each{|url|
                        insert(-1,url)
                    }
                else
                    puts "filename #{filename} does not exist"
                end
            end

            def save(filename)
                File.open(@filename,'w'){|f|
                    #json = JSON.pretty_generate(self)

                    f.write(JSON.pretty_generate(self))
                    #f.write(self.to_json)

                }
            end

            def work_dir
                Environment::get_dev_dir('work')
            end

            def is_remote_url pattern
                return true if(pattern.include?('http://'))
                return true if(pattern.include?('https://'))
                false
            end

            def remove url
                if(include?(url))
                    self.delete(url)
                    save(@filename)
                end
            end

            def import(pattern)
                imported=Array.new
                if(is_remote_url(pattern))
                    remote=pattern
                    if(!include?(remote))
                        insert(-1,remote)
                        imported.insert(-1,remote)
                    end
                else
                    git_dirs = Array.new
                    Dir.chdir(work_dir) do
                        Dir.glob('**/.git'){|git_dir|
                            dir = File.expand_path('..',git_dir)
                            if(dir.length > 0)
                                git_dirs.insert(0,dir)
                            end
                        }
                    end

                    git_dirs.each{|git_dir|
                        dir=Raykit::Git::Directory.new(git_dir)
                        remote=dir.remote
                        if(remote.include?(pattern) && !include?(remote))
                            insert(-1,remote)
                            imported.insert(-1,remote)
                        end
                    }
                end
                save(@filename)
                imported
            end

            def matches(pattern)
                matches = Array.new
                REPOSITORIES.each{|url|
                    if(url.include?(pattern))
                        matches << url
                    end
                }
                matches
            end
        end
    end
end