Class: Squared::Workspace::Project::Docker
- Defined in:
- lib/squared/workspace/project/docker.rb
Constant Summary collapse
- DIR_DOCKER =
(COMPOSEFILE + BAKEFILE + ['Dockerfile']).freeze
Constants included from Common
Instance Attribute Summary collapse
-
#context ⇒ Object
readonly
Returns the value of attribute context.
-
#tag ⇒ Object
Returns the value of attribute tag.
Attributes inherited from Base
#children, #dependfile, #exception, #group, #name, #parent, #path, #pipe, #project, #theme, #verbose, #workspace
Class Method Summary collapse
Instance Method Summary collapse
- #bake?(file = dockerfile) ⇒ Boolean
- #build? ⇒ Boolean
- #buildx(flag, opts = [], tag: nil, context: nil, from: nil) ⇒ Object
- #clean(sync: invoked_sync?('clean')) ⇒ Object
- #clean? ⇒ Boolean
- #compose(opts, flags = nil, script: false, args: nil, from: :run) ⇒ Object
- #compose!(flag, opts = [], id: nil, service: nil, multiple: false) ⇒ Object
- #compose?(file = dockerfile) ⇒ Boolean
- #container(flag, opts = [], id: nil) ⇒ Object
- #dockerfile(val = nil) ⇒ Object
- #image(flag, opts = [], sync: true, id: nil, registry: nil, filter: nil) ⇒ Object
-
#initialize(mounts: [], **kwargs) ⇒ Docker
constructor
A new instance of Docker.
- #network(flag, opts = [], target: nil) ⇒ Object
- #populate ⇒ Object
- #ref ⇒ Object
Methods inherited from Base
#<=>, #==, #add, aliasargs, #allref, #archive, #archive?, #as, #asdf, bannerargs, #basepath, #basepath!, batchargs, #build, #chain, #copy, #copy?, #depend, #depend?, #dependname, #dependtype, #dev?, #doc, #doc?, #empty?, #enabled?, #error, #event, #exclude?, #exist?, #first, #generate, #global, #global=, #global_set, #graph, #graph?, #has?, #inject, #inspect, #last, #lint, #lint?, #localname, #log, options, populate, #prereqs, #prereqs?, #prod?, ref, #ref?, #rootpath, #run, #scope, #script?, #scriptdata, #scriptname, #series, subtasks, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #unpack, #variable_set, #version, #version=, #with
Methods included from Common::Format
emphasize, #enable_aixterm, #enable_drawing, message, raise_error
Constructor Details
#initialize(mounts: [], **kwargs) ⇒ Docker
Returns a new instance of Docker.
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/squared/workspace/project/docker.rb', line 126 def initialize(*, mounts: [], **kwargs) super self.global = nil return unless dockerfile(kwargs[:file]).exist? @tag = kwargs[:tag] || tagname("#{@project}:#{@version || 'latest'}") @context = kwargs[:context] @mounts = mounts @secrets = kwargs[:secrets] @registry = tagjoin kwargs[:registry], kwargs[:username] @oci = tagjoin kwargs[:oci], kwargs[:username] initialize_ref Docker.ref initialize_logger kwargs[:log] initialize_env(**kwargs) @output[4] = merge_opts(kwargs[:args], @output[4]) if kwargs[:args] end |
Instance Attribute Details
#context ⇒ Object (readonly)
Returns the value of attribute context.
123 124 125 |
# File 'lib/squared/workspace/project/docker.rb', line 123 def context @context end |
#tag ⇒ Object
Returns the value of attribute tag.
124 125 126 |
# File 'lib/squared/workspace/project/docker.rb', line 124 def tag @tag end |
Class Method Details
.config?(val) ⇒ Boolean
105 106 107 108 109 |
# File 'lib/squared/workspace/project/docker.rb', line 105 def config?(val) return false unless (val = as_path(val)) DIR_DOCKER.any? { |file| val.join(file).exist? } end |
.tasks ⇒ Object
101 102 103 |
# File 'lib/squared/workspace/project/docker.rb', line 101 def tasks [].freeze end |
Instance Method Details
#bake?(file = dockerfile) ⇒ Boolean
675 676 677 678 679 |
# File 'lib/squared/workspace/project/docker.rb', line 675 def bake?(file = dockerfile) return file == 1 || file == 2 if file.is_a?(Numeric) BAKEFILE.include?(File.basename(file)) end |
#build? ⇒ Boolean
661 662 663 |
# File 'lib/squared/workspace/project/docker.rb', line 661 def build? @output[0] != false && dockerfile.exist? end |
#buildx(flag, opts = [], tag: nil, context: nil, from: nil) ⇒ Object
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 |
# File 'lib/squared/workspace/project/docker.rb', line 401 def buildx(flag, opts = [], tag: nil, context: nil, from: nil) if flag == :bake && context&.match?(%r{^["']?(https?|git)://}i) shared = data[:shared].dup.push('f|file=q') shared.delete('f|file=p') end cmd, opts = docker_session('buildx', opts: opts) data = OPT_DOCKER[:buildx] op = OptionPartition.new(opts, data[:common], cmd, project: self, strict: strict?) op.append(flag, quote: false) .parse(data[flag == :bake ? :bake : :build] + (shared || data[:shared])) case flag when :build, :context append_tag(tag || option('tag', ignore: false) || self.tag) if shared op.add_quote(context, preserve: false) else append_context context end when :bake append_file(0, index: 3) unless from || op.arg?('f', 'file') || !anypath?(*COMPOSEFILE) unless op.empty? context = op.pop if Dir.exist?(op.last) && projectpath?(op.last) op.append(escape: true, strip: /^:/, clear: true) contextdir context if context end end op.clear(pass: false) run(from: from || symjoin('buildx', flag)) end |
#clean(sync: invoked_sync?('clean')) ⇒ Object
336 337 338 339 340 341 342 |
# File 'lib/squared/workspace/project/docker.rb', line 336 def clean(*, sync: invoked_sync?('clean'), **) if runnable?(@clean) super elsif sync || option('y', prefix: 'docker') image :rm end end |
#clean? ⇒ Boolean
665 666 667 |
# File 'lib/squared/workspace/project/docker.rb', line 665 def clean? super || dockerfile.exist? end |
#compose(opts, flags = nil, script: false, args: nil, from: :run) ⇒ Object
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
# File 'lib/squared/workspace/project/docker.rb', line 344 def compose(opts, flags = nil, script: false, args: nil, from: :run, **) return opts unless script if from == :run if bake?(n = filetype) ret = docker_session 'buildx bake' append_file n from = :bake elsif compose?(n) ret = docker_session 'compose build' append_file n from = :compose else ret = docker_session 'build' end else ret = docker_session from end case opts when String ret << opts when Hash ret.merge(append_hash(opts, target: [], build: true)) when Enumerable ret.merge(opts.to_a) end [args, flags].each_with_index do |item, i| next unless item && (data = append_any(item, target: [])) ret.merge(data.map { |arg| i == 0 ? fill_option(arg) : quote_option('build-arg', arg) }) end case from when :run case @secrets when String ret << quote_option('secret', @secrets, double: true) when Hash append = lambda do |key| ret.merge(Array(@secrets[key]).map { |arg| quote_option('secret', "type=#{key},#{arg}", double: true) }) end append.call(:file) append.call(:env) else ret.merge(Array(@secrets).map { |arg| quote_option('secret', arg) }) end if (val = option('tag', ignore: false)) append_tag val elsif !session_arg?('t', 'tag') append_tag tag end append_context when :bake, :compose option(from == :bake ? 'target' : 'service', ignore: false) { |val| ret.merge(split_escape(val).quote!) } end ret end |
#compose!(flag, opts = [], id: nil, service: nil, multiple: false) ⇒ Object
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 |
# File 'lib/squared/workspace/project/docker.rb', line 431 def compose!(flag, opts = [], id: nil, service: nil, multiple: false) from = symjoin 'compose', flag if flag == :service command = opts.first if service == true cmd, status = filter_ps command, from lines = IO.popen(cmd.temp('--services')).map(&:strip).reject(&:empty?) return list_empty(hint: status) if lines.empty? service = choice_index('Choose a service', lines, multiple: true, attempts: 1) end docker_session('compose', command, '--', *service) else cmd, opts = docker_session('compose', opts: opts) op = OptionPartition.new(opts, OPT_DOCKER[:compose][:common], cmd, project: self, strict: strict?) append_file(filetype, force: flag == :publish) unless op.arg?('f', 'file') op << flag op.parse(OPT_DOCKER[:compose].fetch(flag, [])) if flag == :publish id ||= option('tag', ignore: false) || op.shift || tagmain registry ||= option('registry') || op.shift || @oci emptyargs op, flag op << shell_quote(tagjoin(registry, id)) return unless confirm_command(op.to_s, title: from, target: id) else if op.remove(':') || service == ':' keys = Set.new read_composefile('services', target: op.values_of('f', 'file')) { |data| keys.merge(data.keys) } service = unless keys.empty? choice_index('Add services', keys, multiple: multiple, force: !multiple, attempts: multiple ? 1 : 3) end end if multiple op.concat(service) if service op.append(delim: true, escape: true, strip: /^:/) else raise_error ArgumentError, 'no service was selected', hint: flag unless service append_command(flag, service, op.extras, prompt: '::') end end end run(from: from) end |
#compose?(file = dockerfile) ⇒ Boolean
669 670 671 672 673 |
# File 'lib/squared/workspace/project/docker.rb', line 669 def compose?(file = dockerfile) return file == 3 || file == 4 if file.is_a?(Numeric) COMPOSEFILE.include?(File.basename(file)) end |
#container(flag, opts = [], id: nil) ⇒ Object
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/squared/workspace/project/docker.rb', line 476 def container(flag, opts = [], id: nil) cmd, opts = docker_session('container', flag, opts: opts) data = OPT_DOCKER[:container] list = data.fetch(flag, []) list += data[:create] if (rc = flag == :run) list += data[:update] if rc ||= flag == :create op = OptionPartition.new(opts, list, cmd, project: self, strict: strict?, args: rc || flag == :exec) from = symjoin 'container', flag case flag when :run, :create, :exec if rc && !op.arg?('mount') all = collect_hash VAL_DOCKER[:run] delim = Regexp.new(",\\s*(?=#{all.join('|')})") Array(@mounts).each do |val| type = nil args = val.split(delim).each_with_object([]) do |opt, out| k, v, q = OptionPartition.parse_option(opt) if k == 'type' case v when 'bind', 'volume', 'image', 'tmpfs' type = v else raise_error TypeError, "unknown: #{v || "''"}", hint: flag end elsif all.include?(k) unless type VAL_DOCKER[:run].each_pair do |key, items| next unless items.include?(k) type = key.to_s unless key == :common break end end case k when 'readonly', 'ro' out << k next when 'source', 'src', 'destination', 'dst', 'target', 'volume-subpath', 'image-path' raise_error ArgumentError, "#{k}: no path value", hint: flag unless v v = basepath v v = shell_quote(v, option: false, force: false) if q == '' end out << "#{k}=#{q}#{v}#{q}" elsif !silent? ('unrecognized option', subject: from, hint: k) end end raise_error TypeError, 'none specified', hint: flag unless type cmd << "--mount type=#{type},#{args.join(',')}" end end append_command(flag, id || tagmain, op.extras) when :update raise_error ArgumentError, 'missing container', hint: flag if op.empty? op.append(escape: true, strip: /^:/) when :commit latest = op.shift || tagmain cmd << id << latest raise_error ArgumentError, "unrecognized args: #{op.join(', ')}", hint: flag unless op.empty? return unless confirm_command(cmd.to_s, title: from, target: id, as: latest) registry = option('registry') || @registry run(from: from, exception: registry.nil? ? exception? : true) return unless registry opts = [] append_option('platform', target: opts, equals: true) opts << case option('disable-content-trust', ignore: false) when '0', 'false' '--disable-content-trust=false' else '--disable-content-trust' end opts << '--quiet' if silent? return image(:push, opts, id: latest, registry: registry) else if op.empty? ps, status, no = filter_ps flag, from cmd << '--no-stream' if flag == :stats list_image(flag, ps, no: no, hint: status, from: from) { |img| run(cmd.temp(img), from: from) } return end op.append(escape: true, strip: /^:/) end run(from: from) end |
#dockerfile(val = nil) ⇒ Object
681 682 683 684 685 686 687 688 689 690 691 692 693 |
# File 'lib/squared/workspace/project/docker.rb', line 681 def dockerfile(val = nil) if val @file = if val.is_a?(Array) val = val.select { |file| exist?(file) } val.size > 1 ? val : val.first elsif val == true DIR_DOCKER.find { |file| exist?(file) } elsif val != 'Dockerfile' val end end basepath((@file.is_a?(Array) ? @file.first : @file) || 'Dockerfile') end |
#image(flag, opts = [], sync: true, id: nil, registry: nil, filter: nil) ⇒ Object
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 |
# File 'lib/squared/workspace/project/docker.rb', line 563 def image(flag, opts = [], sync: true, id: nil, registry: nil, filter: nil) cmd, opts = docker_session('image', flag, opts: opts) op = OptionPartition.new(opts, OPT_DOCKER[:image].fetch(flag, []), cmd, project: self, strict: strict?) exception = exception? = true from = symjoin 'image', flag case flag when :ls if opts.size == op.size index = 0 name = nil opts.reverse_each do |val| next unless (arg = OptionPartition.parse_arg!('name', val)) name = arg[1] opts.delete(val) break end list_image(:run, filter: filter, from: from) do |val| container(:run, if name opts.dup << "name=#{index == 0 ? name : "#{name}-#{index}"}" else opts end, id: val) index += 1 end return end op.clear when :rm unless id if op.empty? list_image(:rm, filter: filter, from: from) { |val| image(:rm, opts, sync: sync, id: val) } else op.each { |val| run(cmd.temp(val), sync: sync, from: from) } end return end op << id if option('y') exception = false = false end when :tag, :save found = false list_image(flag, filter: filter, from: from) do |val| op << val found = true if flag == :tag op << tagname("#{project}:#{op.first}") break end end raise_error ArgumentError, 'target not specified', hint: flag unless found when :pull if !id id = tagmain elsif !op.arg?('a', 'all-tags') && !id.include?(':') id = "#{project}:#{id}" end unless registry registry = op.shift registry ||= option('registry') || @registry unless id.include?('/') end cmd << shell_quote(tagjoin(registry, id)) when :push id ||= option('tag', ignore: false) || op.shift || tagmain registry ||= option('registry') || op.shift || @registry emptyargs op, flag raise_error ArgumentError, 'username/registry not specified', hint: flag unless registry uri = shell_quote tagjoin(registry, id) op << uri img = docker_output 'image', 'tag', id, uri return unless confirm_command(img.to_s, cmd.to_s, target: id, as: registry, title: from) @session = img sync = false exception ||= true = false end success?(run(sync: sync, exception: exception, banner: , from: from), flag == :tag || flag == :save) end |
#network(flag, opts = [], target: nil) ⇒ Object
646 647 648 649 650 651 652 653 654 655 656 657 658 659 |
# File 'lib/squared/workspace/project/docker.rb', line 646 def network(flag, opts = [], target: nil) cmd, opts = docker_session('network', flag, opts: opts) op = OptionPartition.new(opts, OPT_DOCKER[:network].fetch(flag, []), cmd, project: self, strict: strict?) .clear from = symjoin 'network', flag if flag == :create op.add_quote(target) run(from: from) else list_image(flag, docker_output('ps -a'), from: from) do |id| success?(run(cmd.temp(target, id), from: from)) end end end |
#populate ⇒ Object
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/squared/workspace/project/docker.rb', line 147 def populate(*, **) super return unless ref?(Docker.ref) || @only namespace name do Docker.subtasks do |action, flags| next if task_pass?(action) if flags.nil? case action when 'ls' format_desc(action, nil, VAL_DOCKER[:ls].keys, after: 'a/ll?,s/tandard?,range*', arg: nil) task action, [:command] do |_, args| command = param_guard(action, 'command', args: args, key: :command) args = args.extras cmd = docker_output command, case command when 'image', 'container', 'network' 'ls' when 'compose' 'ps' else raise_error ArgumentError, 'unrecognized command', hint: command end cmd << '-a' if has_value!(args, 'a', 'all') && command != 'network' data = VAL_DOCKER[:ls][command.to_sym] if has_value!(args, 's', 'standard') cols = data.first(data.index('CreatedAt')) else cols = args.each_with_object([]) do |val, out| if val =~ /^(\d+)$/ out << data[$1.to_i.pred] elsif val =~ /^(\d+)(-|\.{2,3})(\d+)$/ j = $1.to_i.pred k = $3.to_i - ($2 == '..' ? 2 : 1) out.concat(data[j..k]) if k > j end end cols = choice_index('Select a column', data, multiple: true, attempts: 1) if cols.empty? end cmd << quote_option('format', "table #{cols.map { |val| "{{.#{val}}}" }.join("\t")}") run(cmd, banner: false, from: :ls) end end else namespace action do flags.each do |flag| case action when 'build' format_desc(action, flag, 'opts*', before: flag == :tag ? 'name' : 'dir') task flag, [flag] do |_, args| param = param_guard(action, flag, args: args, key: flag) buildx(:build, args.extras, "#{flag}": param) end when 'bake' break unless bake? case flag when :build, :compose format_desc action, flag, 'opts*,target*,context?|:' task flag do |_, args| args = args.to_a if args.first == ':' choice_command :bake else buildx(:bake, args, from: (:'buildx:bake' if flag == :compose)) end end when :check format_desc action, flag, 'target' task flag, [:target] do |_, args| target = param_guard(action, flag, args: args, key: :target) buildx :bake, ['allow=fs.read=*', 'call=check', target] end end when 'compose' break unless compose? case flag when :exec, :run format_desc action, flag, "service/:,command#{'?' unless flag == :exec}/::,args*,opts*" task flag, [:service] do |_, args| service = param_guard(action, flag, args: args, key: :service) compose!(flag, args.extras, service: service) end when :service cmds = %w[down kill pause restart rm start stop top unpause watch].freeze format_desc(action, flag, cmds, arg: nil, after: 'name+|:') task flag, [:command] do |_, args| command = param_guard(action, flag, args: args, key: :command) raise_error ArgumentError, 'unrecognized command', hint: command unless cmds.include?(command) service = args.extras if service.first == ':' choice_command flag, command else compose!(flag, [command], service: service.empty? || service) end end when :publish next unless @oci format_desc action, flag, 'tag?,repository?,opts*' task flag, [:tag] do |_, args| compose! flag, args.to_a end else format_desc action, flag, 'opts*,service*|:' task flag do |_, args| compose!(flag, args.to_a, multiple: true) end end when 'container' case flag when :exec, :commit format_desc(action, flag, flag == :exec ? 'id/name,opts*,args+|:' : 'id/name,tag?,opts*') task flag, [:id] do |_, args| if flag == :exec && !args.id choice_command flag else id = param_guard(action, flag, args: args, key: :id) container(flag, args.extras, id: id) end end when :run, :create format_desc action, flag, 'image,opts*,args*|:' task flag, [:image] do |_, args| if args.image container(flag, args.extras, id: args.image) else choice_command flag end end else format_desc action, flag, "opts*,id/name#{flag == :update ? '+' : '*'}" task flag do |_, args| container flag, args.to_a end end when 'image' case flag when :push next unless @registry format_desc action, flag, 'tag?,registry/username?,opts*' task flag, [:tag] do |_, args| image flag, args.to_a end when :pull format_desc action, flag, 'tag,registry/username?,opts*' task flag, [:tag] do |_, args| id = param_guard(action, flag, args: args, key: :tag) image(flag, args.extras, id: id) end else format_desc(action, flag, case flag when :rm, :save then 'id,opts*' when :tag then 'version' else 'opts*,args*' end, before: 'pattern?') task flag do |_, args| args = args.to_a n = args.size if (n > 1 || (flag == :ls && n > 0)) && OptionPartition.pattern?(args.first) filter = args.shift end if !args.empty? || flag == :ls image(flag, args, filter: filter) else choice_command flag end end end when 'network' format_desc action, flag, 'target,opts*' task flag, [:target] do |_, args| target = flag == :create ? param_guard(action, flag, args: args, key: :target) : args.target if target network(flag, args.extras, target: target) else choice_command flag end end end end end end end end end |
#ref ⇒ Object
143 144 145 |
# File 'lib/squared/workspace/project/docker.rb', line 143 def ref Docker.ref end |