svn session set up
--
 from
 http://svn.collab.net/repos/svn/trunk/subversion/bindings/swig/ruby/test/util.rb
++
778974
def svn_session(commit_msg = String.new) # :nodoc:
      ctx = Svn::Client::Context.new
    
      # Function for commit messages
      ctx.set_log_msg_func do |items|
        [true, commit_msg]
      end

      # don't fail on non CA signed ssl server
      ctx.add_ssl_server_trust_file_provider

      setup_auth_baton(ctx.auth_baton)
      ctx.add_username_provider
    
      # username and password
      ctx.add_simple_prompt_provider(0) do |cred, realm, username, may_save|
        cred.username = @svn_user
        cred.password = @svn_pass
        cred.may_save = false
      end

      return ctx unless block_given?

      begin
        yield ctx
      #ensure
      #  warning!?
      #  ctx.destroy
      end
    end
176703
def build_env(client, req)
      rack_env = DefaultRackEnv.dup
      req.fill_rack_env(rack_env)
      rack_env["SERVER_PORT"] ||= @port.to_s
      
      if (rack_env["rack.input"].respond_to? :set_encoding)
        rack_env["rack.input"].set_encoding "ASCII-8BIT"
      end
      
      rack_env["REMOTE_PORT"], rack_env["REMOTE_ADDR"] = Socket::unpack_sockaddr_in(client.getpeername)
      rack_env["REMOTE_PORT"] &&= rack_env["REMOTE_PORT"].to_s
      rack_env["SERVER_PROTOCOL"] = "HTTP/" << req.version.join('.')
      
      return rack_env      
    end
133830
def login
    connect! unless connected?    
    json = <<-EOF
      {
        "user_auth": {
          "user_name": "#{@user}",
           "password": "#{OpenSSL::Digest::MD5.new(@pass)}",
            "version": 2
        },
        "application": "sugarcrm_rubygem"
      }
    EOF
    json.gsub!(/^\s{6}/,'')
    response = send!(:login, json)
  end
799609
def run
      if PryNav.current_remote_server
        raise 'Already running a pry-remote session!'
      else
        PryNav.current_remote_server = self
      end

      setup
      Pry.start @object, {
        :input  => client.input_proxy,
        :output => client.output,
        :pry_remote => true
      }
    end
1225824
def connection_repo
      @options[:path] = API_REST + @options[:path]

      @options[:headers] = HEADERS.merge(AUTH_PREFIX => @final_hash[:creds]).merge(@options[:headers])

      text.msg('HTTP Request Data:')
      text.msg("> HTTP #{@options[:scheme]}://#{@options[:host]}")
      @options.each do |key, value|
        text.msg("> #{key}: #{value}")
      end
      text.msg('End HTTP Request Data.')
      if @options[:scheme] == 'https'
        @connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}", @options)
      else
        Excon.defaults[:ssl_verify_peer] = false
        @connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}:6001", @options)
      end
      @connection
      end
727035
def setup(working_dir, interactive=False):
    
    # set up our implementation
    log.debug("Working dir: {}".format(working_dir))
    if not os.path.exists( working_dir ):
        os.makedirs( working_dir, 0700 )

    node_config = load_configuration(working_dir)
    if node_config is None:
        sys.exit(1)

    log.debug("config\n{}".format(json.dumps(node_config, indent=4, sort_keys=True)))
    return node_config
192147
def call(env)
      return render(500) do |xml|
        xml.h2("#{@key} env is not initialized")
      end unless env[@key]

      request = ::Rack::Request.new(env)

      if action = dispatch_action(request)
        send(action, request)
      else
        @app.call(env)
      end
    end
212484
def propset(type, files, dir_path=self.svn_repo_working_copy)
      raise RepoAccessError, 'currently, "ignore" is the only supported propset' \
             unless type == 'ignore'

      svn_session() do |svn|
        files.each do |ef|
          begin
            svn.propset(Svn::Core::PROP_IGNORE, ef, dir_path)
          rescue Exception => e #Svn::Error::EntryNotFound => e
            raise RepoAccessError, "Propset (Ignore) Failed: #{e.message}"
          end
        end
      end
    end
489433
def do_add(self, subcmd, opts, *args):
        
        print "'svn %s' opts: %s" % (subcmd, opts)
        print "'svn %s' args: %s" % (subcmd, args)
1242893
def main(cls):
        
        log_level = logging.INFO
        log_fmt = '[%(asctime)s] %(message)s'
        if bool(os.getenv('DEBUG')):
            log_level = logging.DEBUG
            log_fmt = '%(levelname).1s %(name)s [%(asctime)s] %(message)s'
        logging.basicConfig(format=log_fmt, datefmt='%Y-%m-%d %H:%M:%S', level=log_level)
        logging.getLogger('requests').setLevel(logging.WARNING)

        obj, extract_args = cls.from_args()

        LOG.info('Identified task: %s', obj.task_url)
        LOG.info('> Task ID: %s', obj.task_id)
        LOG.info('> Rank: %s', obj.rank)
        LOG.info('> Changeset: %s', obj.changeset)
        LOG.info('> Build ID: %s', obj.build_id)

        if extract_args['dry_run']:
            return

        out = extract_args['out']
        os.mkdir(out)

        try:
            obj.extract_build(out, tests=extract_args['tests'], full_symbols=extract_args['full_symbols'])
            os.makedirs(os.path.join(out, 'download'))
            with open(os.path.join(out, 'download', 'firefox-temp.txt'), 'a') as dl_fd:
                dl_fd.write('buildID=' + obj.build_id + os.linesep)
        except:  # noqa
            if os.path.isdir(out):
                junction_path.rmtree(out)
            raise
549454
def get(self, *args, **kwargs):
        
        self.session.username = 'gmr'

        session = self.session.as_dict()
        if session['last_request_at']:
            session['last_request_at'] = str(date.fromtimestamp(
                                             session['last_request_at']))

        # Send a JSON string for our test
        self.write({'message': 'Hello World',
                    'request': {'method': self.request.method,
                                'protocol': self.request.protocol,
                                'path': self.request.path,
                                'query': self.request.query,
                                'remote_ip': self.request.remote_ip,
                                'version': self.request.version},
                    'session': session,
                    'tinman': {'version':  __version__}})
        self.finish()
567375
def initialize_variables!
      @root        = destination_root
      @project_dir = File.basename(@root)
      @name        = (options.name || @project_dir)

      @scm = if    File.directory?(File.join(@root,'.git')) then :git
             elsif File.directory?(File.join(@root,'.hg'))  then :hg
             elsif File.directory?(File.join(@root,'.svn')) then :svn
             elsif options.hg?                              then :hg
             elsif options.git?                             then :git
             end

      case @scm
      when :git
        @scm_user  = `git config user.name`.chomp
        @scm_email = `git config user.email`.chomp

        @github_user = `git config github.user`.chomp
      when :hg
        user_email = `hg showconfig ui.username`.chomp
        user_email.scan(/([^<]+)\s+<([^>]+)>/) do |(user,email)|
          @scm_user, @scm_email = user, email
        end
      end

      @modules      = modules_of(@name)
      @module_depth = @modules.length
      @module       = @modules.last

      @namespace      = options.namespace || namespace_of(@name)
      @namespace_dirs = namespace_dirs_of(@name)
      @namespace_path = namespace_path_of(@name)
      @namespace_dir  = @namespace_dirs.last

      @version     = options.version
      @summary     = options.summary
      @description = options.description

      @authors     = if options.author || options.author
                       [*options.author, *options.authors]
                     else
                       [@scm_user || ENV['USERNAME'] || ENV['USER'].capitalize]
                     end
      @author      = @authors.first

      @email       = (options.email || @scm_email)
      @safe_email  = @email.sub('@',' at ') if @email

      @homepage    = if options.homepage
                       options.homepage
                     elsif !(@github_user.nil? || @github_user.empty?)
                       "https://github.com/#{@github_user}/#{@name}#readme"
                     else
                       "https://rubygems.org/gems/#{@name}"
                     end
      @uri         = URI(@homepage)
      @bug_tracker = case @uri.host
                     when 'github.com'
                       "https://#{@uri.host}#{@uri.path}/issues"
                     end

      @markup = if    options.markdown? then :markdown
                elsif options.textile?  then :textile
                elsif options.markup?   then options.markup.to_sym
                end

      @markup_ext = Template::Markup::EXT.fetch(@markup) do
        say "Unknown markup: #{@markup}", :red
        exit -1
      end

      @date  = Date.today
      @year  = @date.year
      @month = @date.month
      @day   = @date.day

      @ignore                   = SortedSet[]
      @dependencies             = {}
      @development_dependencies = {}

      @templates.each do |template|
        @ignore.merge(template.ignore)

        @dependencies.merge!(template.dependencies)
        @development_dependencies.merge!(template.development_dependencies)

        template.variables.each do |name,value|
          instance_variable_set("@#{name}",value)
        end
      end

      @generated_dirs  = {}
      @generated_files = {}
    end
104177
function setupModule() {

    // Shims

    if(typeof self === 'undefined') {
      global.self = global;
    }

    if(!self.URL) {
      self.URL = self.webkitURL;
    }

    // Make sure are on https in browser,
    // otherwise crypto etc. wont work.

    if(isBrowser() &&
        self.location.protocol === 'http:' &&
        self.location.hostname !== 'localhost' &&
        !self.location.hostname.startsWith('192.168.')) {
      self.location.href = self.location.href.replace(/http/, 'https');
    }

    // Setup / export module

    da = self.direape || {};

    if(typeof module === 'undefined') {
      self.direape = da;
    } else {
      module.exports = da;
    }

    da.test = test;

    // Define name of testsuite

    testSuite('direape');
  }
1005227
def call(env)
      # Avoid modifying the session state, don't set cookies, etc
      env["rack.session.options"] ||= {}
      env["rack.session.options"].merge! :defer => true, :skip => true

      root = env["SCRIPT_NAME"]
      path = Rack::Utils.unescape(env["PATH_INFO"].to_s).sub(%r[^/], "")

      if path.include? ".."
        return [403, { "Content-Type" => "text/plain", "Content-Length" => "9" }, ["Forbidden"]]
      end

      # Pull out the md5sum if it's part of the given path
      # e.g. foo/bar-a95c53a7a0f5f492a74499e70578d150.js -> a95c53a7a0f5f492a74499e70578d150
      checksum_tag = bundle_name = nil
      matches = path.match /([^\/]+)-([\da-f]{32})\..+$/
      if matches && matches.size == 3
        bundle_name = matches[1]
        checksum_tag = matches[2]
        path.sub!("-#{checksum_tag}", "")
      end

      # First see if there is a bundle with this name
      asset = Bundle[bundle_name]
      if asset
        # If the checksum doesn't match the bundle, we want to return a 404.
        asset = nil unless asset.checksum == checksum_tag
      else
        # If there is no bundle with this name, find another type of Asset with the name instead.
        asset = Asset[path]
      end

      if asset
        # If the ETag matches, give a 304
        return [304, {}, []] if env["HTTP_IF_NONE_MATCH"] == %Q["#{asset.checksum}"]

        if Pinion.environment == "production"
          # In production, if there is a checksum, cache for a year (because if the asset changes with a
          # redeploy, the checksum will change). If there is no checksum, cache for 10 minutes (this way at
          # worst we only serve 10 minute stale assets, and caches in front of Pinion will be able to help
          # out).
          cache_policy = checksum_tag ? "max-age=31536000" : "max-age=600"
        else
          # Don't cache in dev.
          cache_policy = "must-revalidate"
        end
        headers = {
          "Content-Type" => asset.content_type,
          "Content-Length" => asset.length.to_s,
          "ETag" => %Q["#{asset.checksum}"],
          "Cache-Control" => "public, #{cache_policy}",
          "Last-Modified" => asset.mtime.httpdate,
        }
        body = env["REQUEST_METHOD"] == "HEAD" ? [] : asset
        [200, headers, body]
      else
        [404, { "Content-Type" => "text/plain", "Content-Length" => "9" }, ["Not found"]]
      end
    rescue Exception => e
      # TODO: logging
      STDERR.puts "Error compiling #{path}:"
      STDERR.puts "#{e.class.name}: #{e.message}"
      # TODO: render nice custom errors in the browser
      raise
    end
838740
def start(env=ENV, stdin=$stdin, stdout=$stdout)
      sock = WEBrick::CGI::Socket.new(@config, env, stdin, stdout)
      req = HTTPRequest.new(@config)
      res = HTTPResponse.new(@config)
      unless @config[:NPH] or defined?(MOD_RUBY)
        def res.setup_header
          unless @header["status"]
            phrase = HTTPStatus::reason_phrase(@status)
            @header["status"] = "#{@status} #{phrase}"
          end
          super
        end
        def res.status_line
          ""
        end
      end

      begin
        req.parse(sock)
        req.script_name = (env["SCRIPT_NAME"] || File.expand_path($0)).dup
        req.path_info = (env["PATH_INFO"] || "").dup
        req.query_string = env["QUERY_STRING"]
        req.user = env["REMOTE_USER"]
        res.request_method = req.request_method
        res.request_uri = req.request_uri
        res.request_http_version = req.http_version
        res.keep_alive = req.keep_alive?
        self.service(req, res)
      rescue HTTPStatus::Error => ex
        res.set_error(ex)
      rescue HTTPStatus::Status => ex
        res.status = ex.code
      rescue Exception => ex
        @logger.error(ex)
        res.set_error(ex, true)
      ensure
        req.fixup
        if defined?(MOD_RUBY)
          res.setup_header
          Apache.request.status_line = "#{res.status} #{res.reason_phrase}"
          Apache.request.status = res.status
          table = Apache.request.headers_out
          res.header.each{|key, val|
            case key
            when /^content-encoding$/i
              Apache::request.content_encoding = val
            when /^content-type$/i
              Apache::request.content_type = val
            else
              table[key] = val.to_s
            end
          }
          res.cookies.each{|cookie|
            table.add("Set-Cookie", cookie.to_s)
          }
          Apache.request.send_http_header
          res.send_body(sock)
        else
          res.send_response(sock)
        end
      end
    end
476769
def info(file=nil)
      wc_path = self.svn_repo_working_copy
      wc_path = file if file and file.class == String

      r_info = Hash.new
      type_info = %w(
                     last_changed_author last_changed_rev
                     last_changed_date conflict_old
                     repos_root_url repos_root_URL
                     copyfrom_rev copyfrom_url conflict_wrk 
                     conflict_new has_wc_info repos_UUID
                     checksum prop_time text_time prejfile
                     schedule taguri lock rev dup url URL
                    ) # changelist depth size tree_conflict working_size

      begin
        @ctx.info(wc_path) do |path, type|
          type_info.each do |t_info|
            r_info[:"#{t_info}"] = type.method(:"#{t_info}").call
          end
        end
      #rescue Svn::Error::WcNotDirectory => e
      #       #Svn::Error::RaIllegalUrl,
      #       #Svn::Error::EntryNotFound,
      #       #Svn::Error::RaIllegalUrl,
      #       #Svn::Error::WC_NOT_DIRECTORY
      #       #Svn::Error::WcNotDirectory => e
      rescue Exception => e
        raise RepoAccessError, "cant get info: #{e.message}"
      end
      r_info
     
    end
887756
def init_rvm(rootdir = Dir.pwd, gemset = '')
      rvm_files = {
        :version => File.join(rootdir, '.ruby-version'),
        :gemset  => File.join(rootdir, '.ruby-gemset')
      }
      unless File.exist?( (rvm_files[:version]).to_s)
        v = select_from(FalkorLib.config[:rvm][:rubies],
                        "Select RVM ruby to configure for this directory",
                        3)
        File.open( rvm_files[:version], 'w') do |f|
          f.puts v
        end
      end
      unless File.exist?( (rvm_files[:gemset]).to_s)
        g = (gemset.empty?) ? ask("Enter RVM gemset name for this directory", File.basename(rootdir)) : gemset
        File.open( rvm_files[:gemset], 'w') do |f|
          f.puts g
        end
      end
    end