Created
August 3, 2024 06:19
-
-
Save tk0miya/d5aa9ec0992ffaefe689b3df2208384d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# pbcopyd.rb - A pbcopy/pbpaste server | |
# | |
# Usage: | |
# ruby pbcopyd.rb [-d] [-h HOSTNAME] [-p PORT] | |
# | |
# pbcopy from remote: | |
# curl -X POST -d 'Hello, World!' http://host.docker.internal:12345 | |
# | |
# pbpaste to remote: | |
# curl -s http://host.docker.internal:12345 | |
require "optparse" | |
require "webrick" | |
DEFAULT_OPTIONS = { | |
daemon: false, | |
host: 'localhost', | |
port: 12345, | |
}.freeze | |
class PBCopyServlet < WEBrick::HTTPServlet::AbstractServlet | |
def do_GET(req, res) | |
res.body = pbpaste | |
res.status = 200 | |
end | |
def do_POST(req, res) | |
pbcopy(req.body) | |
res.status = 200 | |
end | |
def pbcopy(s) | |
IO.popen('pbcopy', 'w') { |stdin| stdin << s } | |
end | |
def pbpaste | |
IO.popen('pbpaste', 'r', &:read) | |
end | |
end | |
def parse_options(argv) | |
options = DEFAULT_OPTIONS.dup | |
OptionParser.new do |opt| | |
opt.on('-d', 'Daemonize') { |v| options[:daemon] = true } | |
opt.on('-h', '--host HOSTNAME', 'Hostname') { |v| options[:host] = v } | |
opt.on('-p', '--port PORT', 'Port number') { |v| options[:port] = v } | |
opt.parse!(argv) | |
end | |
options | |
end | |
def main | |
options = parse_options(ARGV) | |
Process.daemon if options[:daemon] | |
server = WEBrick::HTTPServer.new({ BindAddress: options[:host], Port: options[:port] }) | |
server.mount('/', PBCopyServlet) | |
trap('INT') { server.shutdown } | |
server.start | |
end | |
if __FILE__ == $0 | |
main | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment