[
  {
    "path": ".github/workflows/node.js.yml",
    "content": "# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node\n# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions\n\nname: CI\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n  build_nodejs:\n    runs-on: ubuntu-latest\n    \n    strategy:\n      matrix:\n        node-version: [14.x, 16.x, 18.x, 19.x]\n    \n    steps:\n      - uses: actions/checkout@v3\n      \n      - name: Use Node.js ${{ matrix.node-version }}\n        uses: actions/setup-node@v3\n        with:\n          node-version: ${{ matrix.node-version }}\n\n      - name: Provisioning\n        run: |\n          docker --version\n          node -v\n          docker pull ubuntu\n\n      - name: NPM install\n        run: npm install\n      \n      - name: Nodejs Tests\n        run: npm test\n\n  build_bun:\n    runs-on: ubuntu-latest\n    \n    steps:\n      - uses: actions/checkout@v3\n      - uses: oven-sh/setup-bun@v1\n    \n      - name: Provisioning\n        run: |\n          docker --version\n          bun -v\n\n      - name: Bun install\n        run: bun install\n\n      - name: Bun Tests\n        run: bun run test"
  },
  {
    "path": ".gitignore",
    "content": "examples/reset.sh\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# TypeScript v1 declaration files\ntypings/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n.env.test\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n\n# Next.js build output\n.next\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and *not* Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# TernJS port file\n.tern-port\n.DS_Store\n"
  },
  {
    "path": ".prettierrc.json",
    "content": "{\n    \"singleQuote\": true\n  }"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# dockerode-compose\n\n`docker-compose` in Node.js using [dockerode](https://github.com/apocas/dockerode).\n\nEverything is executed programmatically using `dockerode`, consequently Docker's API.\n\n\n### ToDo:\n* Finish compose spec\n* User friendly functions (partial deploys, etc) needs to be implemented.\n\n## Installation\n\n`npm install dockerode-compose`\n\n\n### Getting started\n\nTo use `dockerode-compose` first you need to instantiate it:\n\n``` js\nvar Dockerode = require('dockerode');\nvar DockerodeCompose = require('dockerode-compose');\n\nvar docker = new Dockerode();\nvar compose = new DockerodeCompose(docker, './test/wordpress.yml', 'wordpress');\n\n(async () => {\n  await compose.pull();\n  var state = await compose.up();\n  console.log(state);\n})();\n```\n\n## Documentation\n- new DockerodeCompose(dockerode, file, project_name)\n- compose.up()\n- compose.pull(service, options) - omit service to pull all images, options.streams return the streams without waiting, options.verbose pipe the streams to stdout.\n\n## Tests\n\n * Tests are implemented using `mocha` and `chai`. Run them with `npm test`.\n\n## Examples\n\nCheck the examples folder for more specific use cases examples.\n\n## License\n\nPedro Dias - [@pedromdias](https://twitter.com/pedromdias)\n\nLicensed under the Apache license, version 2.0 (the \"license\"); You may not use this file except in compliance with the license. You may obtain a copy of the license at:\n\n    http://www.apache.org/licenses/LICENSE-2.0.html\n\nUnless required by applicable law or agreed to in writing, software distributed under the license is distributed on an \"as is\" basis, without warranties or conditions of any kind, either express or implied. See the license for the specific language governing permissions and limitations under the license.\n"
  },
  {
    "path": "compose.js",
    "content": "const yaml = require('js-yaml');\nconst fs = require('fs');\nconst stream = require('stream');\n\nconst secrets = require('./lib/secrets');\nconst volumes = require('./lib/volumes');\nconst configs = require('./lib/configs');\nconst networks = require('./lib/networks');\nconst services = require('./lib/services');\nconst tools = require('./lib/tools');\n\nclass Compose {\n  constructor(dockerode, file, projectName) {\n    this.docker = dockerode;\n\n    if (file === undefined || projectName === undefined) {\n      throw new Error('please specify a file and a project name');\n    }\n\n    this.file = file;\n    this.projectName = projectName;\n\n    try {\n      this.recipe = yaml.load(fs.readFileSync(file, 'utf8'));\n    } catch (e) {\n      throw e;\n    }\n  }\n\n  async down(options) {\n    var output = {};\n    try { \n      output.file = this.file;\n      output.services = await services.down(this.docker, this.projectName, this.recipe, output, options);\n      output.networks = await networks.down(this.docker, this.projectName, this.recipe, output);\n      if (options !== undefined) {\n        if (options.volumes) {\n          output.volumes = await volumes.down(this.docker, this.projectName, this.recipe, output);\n        }\n      }\n      return output;\n    } catch (e) {\n      throw e;\n    }\n  }\n\n  async up(options) {\n    var output = {};\n    try {\n      output.file = this.file;\n      output.secrets = await secrets(this.docker, this.projectName, this.recipe, output);\n      output.volumes = await volumes.up(this.docker, this.projectName, this.recipe, output);\n      output.configs = await configs(this.docker, this.projectName, this.recipe, output);\n      output.networks = await networks.up(this.docker, this.projectName, this.recipe, output);\n      output.services = await services.up(this.docker, this.projectName, this.recipe, output, options);\n      return output;\n    } catch (e) {\n      throw e;\n    }\n  }\n\n  async pull(serviceN, options) {\n    options = options || {};\n    var streams = [];\n    var serviceNames = (serviceN === undefined || serviceN === null) ? tools.sortServices(this.recipe) : [serviceN];\n    for (var serviceName of serviceNames) {\n      var service = this.recipe.services[serviceName];\n      try {\n        var streami = await this.docker.pull(service.image);\n        streams.push(streami);\n\n        if (options.verbose === true) {\n          streami.pipe(process.stdout);\n        }\n\n        if (options.streams !== true) {\n          if (options.verbose === true) {\n            streami.pipe(process.stdout);\n          } else {\n            streami.pipe(stream.PassThrough());\n          }\n          await new Promise(fulfill => streami.once('end', fulfill));\n        }\n      } catch (e) {\n        throw e;\n      }\n    }\n    return streams;\n  }\n}\n\nmodule.exports = Compose;"
  },
  {
    "path": "examples/down.js",
    "content": "var Dockerode = require('dockerode');\nvar DockerodeCompose = require('../compose');\n\nvar docker = new Dockerode();\n\nvar yamlFile = './test/assets/wordpress_original.yml'\nvar projectName = 'wordpress'\n\nif (process.argv.length > 2) {\n  if (process.argv[2] !== undefined) {\n    yamlFile = process.argv[2]\n  }\n  if (process.argv[3] !== undefined) {\n    projectName = process.argv[3]\n  }\n}\n\nvar compose = new DockerodeCompose(docker, yamlFile, projectName);\n\n(async () => {\n  var state = await compose.down({ volumes: true });\n  console.log(state);\n})();\n"
  },
  {
    "path": "examples/pull.js",
    "content": "var Dockerode = require('dockerode');\nvar DockerodeCompose = require('../compose');\n\nvar docker = new Dockerode();\n\nvar yamlFile = './test/assets/wordpress_original.yml'\nvar projectName = 'wordpress'\n\nif (process.argv.length > 2) {\n  if (process.argv[2] !== undefined) {\n    yamlFile = process.argv[2]\n  }\n  if (process.argv[3] !== undefined) {\n    projectName = process.argv[3]\n  }\n}\n\nvar compose = new DockerodeCompose(docker, yamlFile, projectName);\n\n(async () => {\n  console.log(await compose.pull());\n})();\n"
  },
  {
    "path": "examples/up.js",
    "content": "var Dockerode = require('dockerode');\nvar DockerodeCompose = require('../compose');\n\nvar docker = new Dockerode();\n\nvar yamlFile = './test/assets/wordpress_original.yml'\nvar projectName = 'wordpress'\n\nif (process.argv.length > 2) {\n  if (process.argv[2] !== undefined) {\n    yamlFile = process.argv[2]\n  }\n  if (process.argv[3] !== undefined) {\n    projectName = process.argv[3]\n  }\n}\n\nvar compose = new DockerodeCompose(docker, yamlFile, projectName);\n\n(async () => {\n  var state = await compose.up();\n  console.log(state);\n})();\n"
  },
  {
    "path": "lib/configs.js",
    "content": "module.exports = async function (docker, projectName, recipe, output) {\n  var configs = [];\n  var configNames = Object.keys(recipe.configs || []);\n  for (var configName of configNames) {\n    var config = recipe.configs[configName];\n    if (config.external === true) continue;\n    var opts = {\n      'Name': projectName + '_' + configName,\n      'Data': fs.readFileSync(config.file, 'utf8')\n    };\n    if (config.name !== undefined) {\n      opts.Name = configName;\n    }\n    configs.push(await docker.createConfig(opts));\n  }\n  return configs;\n}"
  },
  {
    "path": "lib/networks.js",
    "content": "async function down(docker, projectName, recipe) {\n  var networks = [];\n  var networkNames = Object.keys(recipe.networks || { default: null });\n  for (var networkName of networkNames) {\n    try {\n      var network = await docker.getNetwork(projectName + '_' + networkName);\n    } catch (e) {}\n\n    try {\n      await network.remove();\n    } catch (e) {}\n  }\n  return networks;\n}\n\nasync function up(docker, projectName, recipe, output) {\n  var networks = [];\n  var networkNames = Object.keys(recipe.networks || []);\n  for (var networkName of networkNames) {\n    var network = recipe.networks[networkName];\n    if (network === null) {\n      try {\n        networks.push({\n          name: projectName + '_' + networkName,\n          network: await docker.createNetwork({\n            Name: projectName + '_' + networkName,\n            CheckDuplicate: true,\n          }),\n        });\n      } catch (err) {\n        if (\n          err.statusCode == 409 &&\n          err.json.message.includes('already exists')\n        ) {\n          let returnedNetwork = await docker.listNetworks({\n            filters: { name: [projectName + '_' + networkName] },\n          });\n          networks.push({\n            name: projectName + '_' + networkName,\n            network: await docker.getNetwork(returnedNetwork[0].Id),\n          });\n        } else {\n          throw err;\n        }\n      }\n      continue;\n    }\n    if (network.external === true) continue;\n    var opts = {\n      Name: projectName + '_' + networkName,\n      Driver: network.driver,\n      DriverOpts: network.driver_opts,\n      Labels: {\n        ...network.labels,\n        ...{\n          'com.docker.compose.network': 'default',\n          'com.docker.compose.project': projectName,\n        },\n      },\n      Attachable: network.attachable,\n      EnableIPv6: network.enable_ipv6,\n      Internal: network.internal,\n      CheckDuplicate: true,\n    };\n    if (network.name !== undefined) {\n      opts.Name = networkName;\n    }\n    if (network.ipam !== undefined) {\n      opts.IPAM = {\n        Driver: network.ipam.driver,\n        Options: network.ipam.options,\n      };\n      if (network.ipam.config !== undefined) {\n        opts.IPAM['Config'] = {\n          Subnet: network.ipam.config.subnet,\n          IPRange: network.ipam.config.ip_range,\n          Gateway: network.ipam.config.gateway,\n          AuxAddress: network.ipam.config.aux_addresses,\n        };\n      }\n    }\n    //if exists we have to compare with the existing network\n    networks.push({\n      name: projectName + '_' + networkName,\n      network: await docker.createNetwork(opts),\n    });\n  }\n\n  if (networks.length === 0) {\n    try {\n      networks.push({\n        name: projectName + '_default',\n        network: await docker.createNetwork({\n          Name: projectName + '_default',\n          CheckDuplicate: true,\n        }),\n      });\n    } catch (err) {\n      if (\n        err.statusCode == 409 &&\n        err.json.message.includes('already exists')\n      ) {\n        let returnedNetwork = await docker.listNetworks({\n          filters: { name: [projectName + '_default'] },\n        });\n        networks.push({\n          name: projectName + '_' + networkName,\n          network: await docker.getNetwork(returnedNetwork[0].Id),\n        });\n      } else {\n        throw err;\n      }\n    }\n  }\n  return networks;\n}\n\nmodule.exports = {\n  down,\n  up,\n};\n"
  },
  {
    "path": "lib/secrets.js",
    "content": "const fs = require('fs');\n\nmodule.exports = async function (docker, projectName, recipe, output) {\n  var secrets = [];\n  var secretNames = Object.keys(recipe.secrets || []);\n  for (var secretName of secretNames) {\n    var secret = recipe.secrets[secretName];\n    if (secret.external === true) continue;\n    var opts = {\n      'Name': projectName + '_' + secretName,\n      'Data': fs.readFileSync(secret.file, 'utf8')\n    };\n    if (secret.name !== undefined) {\n      opts.Name = secretName;\n    }\n    secrets.push(await docker.createSecret(opts));\n  }\n  return secrets;\n}"
  },
  {
    "path": "lib/services.js",
    "content": "const tools = require('./tools');\nconst servicesTools = require('./servicesTools');\nconst fs = require('fs');\nconst yaml = require('js-yaml');\nconst path = require('path');\n\nasync function down(docker, projectName, recipe, output, options) {\n  var services = [];\n  var serviceNames = tools.sortServices(recipe);\n  for (var serviceName of serviceNames) {\n    let container = docker.getContainer(projectName + '_' + serviceName + '_1');\n\n    try {\n      await container.stop();\n    } catch (e) {}\n\n    try {\n      await container.remove();\n    } catch (e) {}\n  }\n  return services;\n}\n\nasync function up(docker, projectName, recipe, output, options) {\n  var services = [];\n  var serviceNames = tools.sortServices(recipe);\n  const cwdPath = path.dirname(output.file);\n  for (var serviceName of serviceNames) {\n    var pathScope = {};\n    pathScope.file = output.file;\n    var networksToAttach = [];\n    var service = recipe.services[serviceName];\n    if (service.extends !== undefined) {\n      if (service.extends.service !== undefined) {\n        service = extendsServices(service, recipe, pathScope);\n      } else {\n        throw new Error('Service key in extends is required!');\n      }\n    }\n\n    if (service.build !== undefined) {\n      var absolutePath = path.dirname(pathScope.file);\n      var obj = {};\n\n      if (service.image !== undefined) {\n        obj['t'] = service.image;\n      } else {\n        obj['t'] = projectName + '_' + serviceName;\n        service.image = projectName + '_' + serviceName;\n      }\n\n      if (typeof service.build === 'object') {\n        if (service.build.context !== undefined) {\n          var buildContextPath = path.resolve(\n            path.join(absolutePath, service.build.context)\n          );\n          if (fs.existsSync(buildContextPath)) {\n            if (service.build.args !== undefined) {\n              var out = {};\n              if (Array.isArray(service.build.args)) {\n                for (let arg_line of service.build.args) {\n                  var arg = arg_line.split('=');\n                  out[arg[0]] = arg[1];\n                }\n              } else {\n                var argNames = Object.keys(service.build.args);\n                for (var argName of argNames) {\n                  out[argName] = service.build.args[argName];\n                }\n              }\n              obj['buildargs'] = out;\n            }\n\n            if (service.build.cache_from !== undefined) {\n              obj['cachefrom'] = service.build.cache_from;\n            }\n\n            if (service.build.extra_hosts !== undefined) {\n              obj['extrahosts'] = service.build.extra_hosts;\n            }\n\n            if (service.build.labels !== undefined) {\n              if (service.build.labels.length > 0) {\n                let labels = {};\n                for (let labelsb of service.build.labels) {\n                  let p = labelsb.split('=');\n                  if (p[1] === undefined) {\n                    p[1] = '';\n                  }\n                  labels[p[0]] = p[1];\n                }\n                obj['labels'] = labels;\n              } else {\n                obj['labels'] = service.build.labels;\n              }\n            }\n\n            if (service.build.shm_size !== undefined) {\n              // RE ARRAGE the function \"convertSizeStringToByteValue\" to a generic one\n              obj['shmsize'] = servicesTools.convertSizeStringToByteValue([\n                { path: '', rate: service.build.shm_size },\n              ]).Rate;\n            }\n\n            if (service.build.target !== undefined) {\n              obj['target'] = service.build.target;\n            }\n\n            if (service.build.dockerfile === undefined) {\n              await servicesTools.buildDockerImage(\n                docker,\n                buildContextPath,\n                obj,\n                null,\n                options\n              );\n            } else {\n              await servicesTools.buildDockerImage(\n                docker,\n                buildContextPath,\n                obj,\n                service.build.dockerfile,\n                options\n              );\n            }\n          } else {\n            throw new Error(\n              `build path ${buildContextPath} either does not exist, is not accessible, or is not a valid URL.`\n            );\n          }\n        } else {\n          throw new Error('Build context is required!');\n        }\n      } else {\n        var dockerFilePath = path.resolve(\n          path.join(absolutePath, service.build)\n        );\n        if (fs.existsSync(dockerFilePath)) {\n          await servicesTools.buildDockerImage(\n            docker,\n            dockerFilePath,\n            obj,\n            null,\n            options\n          );\n        } else {\n          throw new Error(\n            `build path ${dockerFilePath} either does not exist, is not accessible, or is not a valid URL.`\n          );\n        }\n      }\n    }\n\n    var opts = {\n      name: projectName + '_' + serviceName + '_1',\n      Image: service.image,\n      HostConfig: servicesTools.buildHostConfig(\n        projectName,\n        service,\n        recipe,\n        cwdPath\n      ),\n      Env: servicesTools.buildEnvVars(service),\n      NetworkingConfig: {\n        EndpointsConfig: {},\n      },\n      Labels: {\n        'com.docker.compose.project': projectName,\n        'com.docker.compose.service': serviceName,\n      },\n    };\n\n    if (service.networks !== undefined) {\n      servicesTools.buildNetworks(projectName, serviceName, service.networks, networksToAttach, opts, recipe.networks);\n    } else {\n      opts.HostConfig.NetworkMode = projectName + '_default';\n      opts.NetworkingConfig.EndpointsConfig[projectName + '_default'] = {\n        IPAMConfig: null,\n        Links: null,\n        Aliases: [serviceName],\n      };\n    }\n\n    // Can be used VolumesFrom from API DIRECTLY inside HostConfig :(\n    if (service.volumes_from) {\n      for (var volume_from of service.volumes_from) {\n        var vf = volume_from.split(':');\n        var svf = recipe.services[vf[0]];\n        servicesTools.buildVolumes(svf.volumes, opts);\n      }\n    }\n\n    if (service.volumes) {\n      servicesTools.buildVolumes(service.volumes, opts);\n    }\n    if (service.container_name !== undefined) {\n      opts.name = service.container_name;\n    }\n    if (service.domainname !== undefined) {\n      opts.Domainname = service.domainname;\n    }\n    if (service.hostname !== undefined) {\n      opts.Hostname = service.hostname;\n    }\n    if (service.mac_address !== undefined) {\n      opts.MacAddress = service.mac_address;\n    }\n    if (service.stdin_open !== undefined) {\n      opts.OpenStdin = service.stdin_open;\n    }\n    if (service.stop_grace_period !== undefined) {\n      let period = parseInt(service.stop_grace_period);\n      if (service.stop_grace_period == period) {\n        opts.StopTimeout = service.stop_grace_period;\n      } else if (\n        service.stop_grace_period.includes('m') &&\n        service.stop_grace_period.includes('s')\n      ) {\n        let minutes = parseInt(\n          service.stop_grace_period.substring(\n            0,\n            service.stop_grace_period.indexOf('m')\n          )\n        );\n        let seconds = parseInt(\n          service.stop_grace_period.substring(\n            service.stop_grace_period.indexOf('m') + 1,\n            service.stop_grace_period.indexOf('s')\n          )\n        );\n        opts.StopTimeout = minutes * 60 + seconds;\n      } else {\n        opts.StopTimeout = service.stop_grace_period.substring(\n          0,\n          service.stop_grace_period.length - 2\n        );\n      }\n    }\n    if (service.stop_signal !== undefined) {\n      opts.StopSignal = service.stop_signal;\n    }\n    if (service.expose !== undefined) {\n      var ports = {};\n      for (var port of service.expose) {\n        ports[port + '/tcp'] = {};\n      }\n      opts.ExposedPorts = ports;\n    }\n    if (service.tty !== undefined) {\n      opts.Tty = service.tty;\n    }\n    if (service.user !== undefined) {\n      opts.User = service.user;\n    }\n    if (service.working_dir !== undefined) {\n      opts.WorkingDir = service.working_dir;\n    }\n    if (service.labels !== undefined) {\n      if (service.labels.length > 0) {\n        let labels = {};\n        for (let labelsb of service.labels) {\n          let p = labelsb.split('=');\n          if (p[1] === undefined) {\n            p[1] = '';\n          }\n          labels[p[0]] = p[1];\n        }\n        opts.Labels = labels;\n      } else {\n        opts.Labels = service.labels;\n      }\n    }\n    if (service.healthcheck !== undefined) {\n      let healthcheck = {};\n      healthcheck.Test = service.healthcheck.test;\n      healthcheck.Interval = convertFancyDurationToMs(\n        service.healthcheck.interval\n      );\n      healthcheck.Timeout = convertFancyDurationToMs(\n        service.healthcheck.timeout\n      );\n      healthcheck.Retries = service.healthcheck.retries;\n      healthcheck.StartPeriod = convertFancyDurationToMs(\n        service.healthcheck.start_period\n      );\n      opts.Healthcheck = healthcheck;\n    }\n    if (service.command !== undefined) {\n      opts.Cmd = service.command;\n    }\n    if (service.entrypoint !== undefined) {\n      if (Array.isArray(service.entrypoint)) {\n        opts.Entrypoint = service.entrypoint;\n      } else {\n        let entrypoint = [];\n        entrypoint.push(service.entrypoint);\n        opts.Entrypoint = entrypoint;\n      }\n    }\n    var container = await docker.createContainer(opts);\n\n    if (networksToAttach.length > 1) {\n      let networkNames = Object.keys(networksToAttach[0]);\n      await findNetwork(output, networkNames[0]).disconnect({\n        Container: container.id,\n      });\n      let networksToAttachSorted = tools.sortNetworksToAttach(networksToAttach);\n      for (var networkToAttach of networksToAttachSorted) {\n        let networkName = Object.keys(networkToAttach);\n        await findNetwork(output, networkName).connect({\n          Container: container.id,\n          EndpointConfig: networkToAttach[networkName],\n        });\n      }\n    }\n    await container.start();\n    services.push(container);\n  }\n  return services;\n}\n\nvar findNetwork = function (output, name) {\n  for (var network of output.networks) {\n    if (network.name == name) return network.network;\n  }\n};\n\nvar convertFancyDurationToMs = function (value) {\n  let interval = parseInt(value);\n  if (value == interval) {\n    return value;\n  } else if (value.includes('m') && value.includes('s')) {\n    let minutes = parseInt(value.substring(0, value.indexOf('m')));\n    let seconds = parseInt(\n      value.substring(value.indexOf('m') + 1, value.indexOf('s'))\n    );\n    return (minutes * 60 + seconds) * 1000 * 1000000;\n  } else {\n    return parseInt(value.substring(0, value.length - 2)) * 1000 * 1000000;\n  }\n};\n\n// https://github.com/compose-spec/compose-spec/blob/master/spec.md#extends\nvar extendsServices = function (service, recipe, pathScope) {\n  // https://github.com/compose-spec/compose-spec/blob/master/spec.md#finding-referenced-service\n  if (service.extends.file === undefined) {\n    // EXTENDS OF THE SAME RECIPE\n    return buildExtendsService(\n      service,\n      service.extends.service,\n      recipe,\n      pathScope\n    );\n  } else {\n    // EXTENDS OF ANOTHER RECIPE\n    var absolutePath = path.dirname(pathScope.file);\n    var extendsRecipe = yaml.load(\n      fs.readFileSync(\n        path.resolve(path.join(absolutePath, service.extends.file)),\n        'utf8'\n      )\n    );\n    return buildExtendsService(\n      service,\n      service.extends.service,\n      extendsRecipe,\n      pathScope\n    );\n  }\n};\n\nvar buildExtendsService = function (\n  service,\n  extendsServiceName,\n  recipe,\n  pathScope\n) {\n  var extend = false;\n  var extendsRecipeServiceNames = Object.keys(recipe.services);\n  for (var extendsRecipeServiceName of extendsRecipeServiceNames) {\n    if (extendsRecipeServiceName == extendsServiceName) {\n      var extendsService = recipe.services[extendsRecipeServiceName];\n      //deep copy\n      //var oldService = JSON.parse(JSON.stringify(service));\n      var oldService = service;\n      service = extendsService;\n      var serviceKeys = Object.keys(service);\n      for (let key of serviceKeys) {\n        verifyRestrictions(key);\n        if (key == 'extends') {\n          extend = true;\n        }\n      }\n      var oldServiceKeys = Object.keys(oldService);\n      for (let key of oldServiceKeys) {\n        if (key != 'extends') {\n          mergingService(key, service, oldService);\n        }\n      }\n      if (oldService.extends.file) {\n        var absolutePath = path.dirname(pathScope.file);\n        pathScope.file = path.resolve(\n          path.join(absolutePath, oldService.extends.file)\n        );\n      }\n      if (extend) service = extendsServices(service, recipe, pathScope);\n\n      return service;\n    }\n  }\n  throw new Error('Extends service not found');\n};\n\n// https://github.com/compose-spec/compose-spec/blob/master/spec.md#restrictions\nvar verifyRestrictions = function (key) {\n  var restrictions = [\n    'links',\n    'volumes_from',\n    'depends_on',\n    'ipc',\n    'pid',\n    'network_mode',\n    //'net'\n  ];\n  if (restrictions.includes(key)) {\n    throw new Error('This extends service cannot be used as a base');\n  }\n};\n\n// https://github.com/compose-spec/compose-spec/blob/master/spec.md#merging-service-definitions\nvar mergingService = function (key, service, oldService) {\n  var mappings = [\n    'environment',\n    //'healthcheck',\n    'labels',\n    'sysctls',\n    'extra_hosts',\n    'ulimits',\n  ];\n  var objectMappings = {\n    build: { args: '', labels: '', extra_hosts: '' },\n    deploy: {\n      labels: '',\n      update_config: '',\n      rollback_config: '',\n      restart_policy: '',\n      resources: { limits: '' },\n    },\n    blkio_config: {\n      device_read_bps: '',\n      device_read_iops: '',\n      device_write_bps: '',\n      device_write_iops: '',\n    },\n    logging: { options: '' },\n  };\n  var sequences = [\n    'cap_add',\n    'cap_drop',\n    //'configs', // not implemented yet\n    'device_cgroup_rules',\n    'expose',\n    //'external_links', // not implemented yet\n    'ports',\n    //'secrets', // not fully implemented yet\n    'security_opt',\n  ];\n  var objectSequences = {\n    deploy: {\n      placement: { constraints: '', preferences: '' },\n      reservations: { generic_resources: '' },\n    },\n  };\n\n  // https://github.com/compose-spec/compose-spec/blob/master/spec.md#mappings - MAPPINGS\n  if (\n    key == 'build' ||\n    key == 'deploy' ||\n    key == 'blkio_config' ||\n    key == 'logging'\n  ) {\n    // one object level missing in deploy resources\n    var objectMappingsKeys = Object.keys(objectMappings[key]);\n    for (let objectMappingsKey of objectMappingsKeys) {\n      if (oldService[key][objectMappingsKey] !== undefined) {\n        service[key][objectMappingsKey] = oldService[key][objectMappingsKey];\n      }\n    }\n  } else if (mappings.includes(key) && service[key] !== undefined) {\n    // TRICKY TRICKY (bugs can appear because long and short syntaxes)\n    if (Array.isArray(oldService[key]) || Array.isArray(service[key])) {\n      if (!Array.isArray(service[key])) {\n        let tempService = [];\n        let envsNames = Object.keys(service[key]);\n        for (let envName of envsNames) {\n          tempService.push(envName + '=' + service[key][envName]);\n        }\n        service[key] = tempService;\n      }\n      if (!Array.isArray(oldService[key])) {\n        var tempOldService = [];\n        let envsNames = Object.keys(oldService[key]);\n        for (let envName of envsNames) {\n          tempOldService.push(envName + '=' + oldService[key][envName]);\n        }\n        oldService[key] = tempOldService;\n      }\n      for (let oldServiceLine of oldService[key]) {\n        for (let serviceLine of service[key]) {\n          if (\n            serviceLine.split('=')[0] == oldServiceLine.split('=')[0] ||\n            serviceLine.split(':')[0] == oldServiceLine.split(':')[0]\n          ) {\n            service[key].splice(\n              service[key].indexOf(serviceLine),\n              1,\n              oldServiceLine\n            );\n          }\n        }\n        if (!service[key].includes(oldServiceLine)) {\n          service[key].push(oldServiceLine);\n        }\n      }\n    } else {\n      Object.assign(service[key], oldService[key]);\n    }\n    // https://github.com/compose-spec/compose-spec/blob/master/spec.md#sequences - SEQUENCES\n  } else if (\n    key == 'dns' ||\n    key == 'dns_search' ||\n    key == 'env_file' ||\n    key == 'tmpfs'\n  ) {\n    if (Array.isArray(oldService[key]) || Array.isArray(service[key])) {\n      if (!Array.isArray(service[key])) {\n        let tempService = [];\n        if (service[key] !== undefined) {\n          tempService.push(service[key]);\n        }\n        service[key] = tempService;\n      }\n      if (!Array.isArray(oldService[key])) {\n        oldService[key] = [oldService[key]];\n      }\n      service[key] = service[key].concat(oldService[key]);\n    } else {\n      service[key] = [];\n      service[key].push(service[key]);\n      service[key].push(oldService[key]);\n    }\n  } else if (key == 'deploy') {\n    var objectSequencesKeys = Object.keys(objectSequences[key]);\n    for (let objectSequencesKey of objectSequencesKeys) {\n      if (oldService[key][objectSequencesKey] !== undefined) {\n        service[key][objectSequencesKey] = oldService[key][objectSequencesKey];\n      }\n    }\n  } else if (sequences.includes(key) && service[key] !== undefined) {\n    if (Array.isArray(oldService[key]) || Array.isArray(service[key])) {\n      for (let oldServiceLine of oldService[key]) {\n        if (!service[key].includes(oldServiceLine)) {\n          service[key].push(oldServiceLine);\n        }\n      }\n    } // else !!! for now all keys are arrays with future implementations can maybe change !!!\n  } else {\n    // https://github.com/compose-spec/compose-spec/blob/master/spec.md#scalars - SCALARS\n    service[key] = oldService[key];\n  }\n};\n\nmodule.exports = {\n  down,\n  up,\n};\n"
  },
  {
    "path": "lib/servicesTools.js",
    "content": "const fs = require('fs');\nconst tar = require('tar-fs');\nconst path = require('path');\nconst stream = require('stream');\n\n/**\n * if host path in the volume string (e.g. `./mylocal/file:/container/file`) is not absolute path,\n * this function will convert it to an absolute path using `cwd` (current working directory) parameter.\n * Otherwise, it will return volume string as it is.\n *\n * @param {*} volumeStr\n * @param {*} cwd\n */\nfunction standardizeVolumeStr(volumeStr, cwd) {\n  if (typeof volumeStr !== 'string' || volumeStr.length < 1) {\n    return volumeStr;\n  }\n  volumeStr = volumeStr.trim();\n  if (\n    volumeStr.substring(0, 2) !== './' &&\n    volumeStr.substring(0, 3) !== '../'\n  ) {\n    return volumeStr;\n  }\n  const parts = volumeStr.split(':');\n  if (parts.length !== 2) {\n    return volumeStr;\n  }\n  if (!cwd) {\n    throw new Error(\n      'Current working dir path not available when local path is a relative path: ' +\n        parts[0]\n    );\n  }\n  const localPath = parts[0];\n  return path.resolve(cwd, localPath) + ':' + parts[1];\n}\n\nmodule.exports = {\n  buildPorts: function (servicePorts, output) {\n    var ports = {};\n    if (typeof servicePorts[0] === 'object') {\n      // LONG SYNTAX\n      // !!! INCOMPLETE - NOT USING DIFFERENT MODES - `mode`: `host` for publishing a host port on each node, or `ingress` for a port to be load balanced.\n      for (let port of servicePorts) {\n        ports[port.target + '/' + port.protocol] = [\n          { HostPort: port.published.toString() },\n        ];\n      }\n      output['PortBindings'] = ports;\n    } else {\n      // SHORT SYNTAX\n      // TODO: SIMPLIFY THIS BLOCK OF CODE! MAYBE!\n      for (let port of servicePorts) {\n        var port_split = port.split(':');\n\n        if (port_split.length == 2) {\n          // \"xxxx:xxxx\"\n          if (port_split[1].includes('-')) {\n            // \"9090-9091:8080-8081\"\n            let split_port_split0 = port_split[0].split('-');\n            let split_port_split0_array = [];\n            split_port_split0_array = fillPortArray(\n              parseInt(split_port_split0[0]),\n              parseInt(split_port_split0[1])\n            );\n\n            let split_port_split1 = port_split[1].split('-');\n            let split_port_split1_array = [];\n            split_port_split1_array = fillPortArray(\n              parseInt(split_port_split1[0]),\n              parseInt(split_port_split1[1])\n            );\n\n            for (let index in split_port_split0_array) {\n              ports[split_port_split1_array[index] + '/tcp'] = [\n                {\n                  HostPort: split_port_split0_array[index].toString(),\n                },\n              ];\n            }\n          } else if (port_split[0].includes('-')) {\n            // \"3000-3005\"\n            let split_port_split = port_split[0].split('-');\n            ports[port_split[1] + '/tcp'] = [];\n            for (let i = split_port_split[0]; i <= split_port_split[1]; i++) {\n              ports[port_split[1] + '/tcp'].push({\n                HostPort: i.toString(),\n              });\n            }\n          } else if (port_split[1].includes('/')) {\n            // \"6060:6060/udp\"\n            ports[port_split[1]] = [{ HostPort: port_split[0] }];\n          } else {\n            // \"8000:8000\"\n            ports[port_split[1] + '/tcp'] = [{ HostPort: port_split[0] }];\n          }\n        } else if (port_split.length == 3) {\n          // \"x.x.x.x:xxxx:xxxx\"\n          if (port_split[2].includes('-')) {\n            // \"127.0.0.1:5000-5010:5000-5010\"\n            let split_port_split1 = port_split[1].split('-');\n            let split_port_split1_array = [];\n            split_port_split1_array = fillPortArray(\n              parseInt(split_port_split1[0]),\n              parseInt(split_port_split1[1])\n            );\n\n            let split_port_split2 = port_split[2].split('-');\n            let split_port_split2_array = [];\n            split_port_split2_array = fillPortArray(\n              parseInt(split_port_split2[0]),\n              parseInt(split_port_split2[1])\n            );\n\n            for (let index in split_port_split1_array) {\n              ports[split_port_split2_array[index] + '/tcp'] = [\n                {\n                  HostPort: split_port_split1_array[index].toString(),\n                  HostIp: port_split[0],\n                },\n              ];\n            }\n          } else if (port_split[1] == '') {\n            // \"127.0.0.1::5000\n            ports[port_split[2] + '/tcp'] = [\n              { HostPort: port_split[2], HostIp: port_split[0] },\n            ];\n          } else {\n            // \"127.0.0.1:8001:8001\"\n            ports[port_split[2] + '/tcp'] = [\n              { HostPort: port_split[1], HostIp: port_split[0] },\n            ];\n          }\n        } else {\n          // \"xxxx\"\n          if (port_split[0].includes('-')) {\n            // \"3000-3005\"\n            let split_port_split = port_split[0].split('-');\n            for (let i = split_port_split[0]; i <= split_port_split[1]; i++) {\n              ports[i + '/tcp'] = [{ HostPort: i.toString() }];\n            }\n          } else {\n            // \"3000\"\n            ports[port + '/tcp'] = [{ HostPort: port }];\n          }\n        }\n      }\n      output['PortBindings'] = ports;\n    }\n  },\n\n  //ToDo: complete the compose specification\n  buildHostConfig: function (projectName, service, recipe, cwd) {\n    var output = {\n      RestartPolicy: { Name: service.restart },\n    };\n\n    if (service.volumes_from !== undefined) {\n      for (var volume_from of service.volumes_from) {\n        var vf = volume_from.split(':');\n        var svf = recipe.services[vf[0]];\n        this.buildVolumesHostconfig(\n          projectName,\n          svf.volumes,\n          output,\n          vf[1],\n          cwd\n        );\n      }\n    }\n\n    if (service.volumes !== undefined) {\n      this.buildVolumesHostconfig(\n        projectName,\n        service.volumes,\n        output,\n        undefined,\n        cwd\n      );\n    }\n\n    if (service.ports !== undefined) {\n      this.buildPorts(service.ports, output);\n    }\n    if (service.devices !== undefined) {\n      output.Devices = service.devices.map((device) => ({\n        CgroupPermissions: \"mrw\",\n        PathInContainer: device,\n        PathOnHost: device,\n      }));\n    }\n    if (service.cpu_count !== undefined) {\n      output.CpuCount = service.cpu_count;\n    }\n    if (service.cpu_percent !== undefined) {\n      output.CpuPercent = service.cpu_percent;\n    }\n    if (service.cpu_shares !== undefined) {\n      output.CpuShares = service.cpu_shares;\n    }\n    if (service.cpu_period !== undefined) {\n      output.CpuPeriod = service.cpu_period;\n    }\n    if (service.cpu_quota !== undefined) {\n      output.CpuQuota = service.cpu_quota;\n    }\n    if (service.cpu_rt_runtime !== undefined) {\n      output.CpuRealtimeRuntime = service.cpu_rt_runtime;\n    }\n    if (service.cpu_rt_period !== undefined) {\n      output.CpuRealtimePeriod = service.cpu_rt_period;\n    }\n    if (service.cpuset !== undefined) {\n      output.CpusetCpus = service.cpuset;\n    }\n    if (service.cap_add !== undefined) {\n      output.CapAdd = service.cap_add;\n    }\n    if (service.cap_drop !== undefined) {\n      output.CapDrop = service.cap_drop;\n    }\n    if (service.cgroup_parent !== undefined) {\n      output.CgroupParent = service.cgroup_parent;\n    }\n    if (service.device_cgroup_rules !== undefined) {\n      output.DeviceCgroupRules = service.device_cgroup_rules;\n    }\n    if (service.dns !== undefined) {\n      output.Dns = service.dns;\n    }\n    if (service.dns_opt !== undefined) {\n      output.DnsOptions = service.dns_opt;\n    }\n    if (service.dns_search !== undefined) {\n      output.DnsSearch = service.dns_search;\n    }\n    if (service.extra_hosts !== undefined) {\n      output.ExtraHosts = service.extra_hosts;\n    }\n    if (service.group_add !== undefined) {\n      output.GroupAdd = service.group_add;\n    }\n    if (service.init !== undefined) {\n      output.Init = service.init;\n    }\n    if (service.ipc !== undefined) {\n      output.IpcMode = service.ipc;\n    }\n    if (service.isolation !== undefined) {\n      output.Isolation = service.isolation;\n    }\n    if (service.mem_swappiness !== undefined) {\n      output.MemorySwappiness = service.mem_swappiness;\n    }\n    if (service.oom_kill_disable !== undefined) {\n      output.OomKillDisable = service.oom_kill_disable;\n    }\n    if (service.oom_score_adj !== undefined) {\n      output.OomScoreAdj = service.oom_score_adj;\n    }\n    if (service.pid !== undefined) {\n      output.PidMode = service.pid;\n    }\n    if (service.pids_limit !== undefined) {\n      output.PidsLimit = service.pids_limit;\n    }\n    if (service.privileged !== undefined) {\n      output.Privileged = service.privileged;\n    }\n    if (service.read_only !== undefined) {\n      output.ReadonlyRootfs = service.read_only;\n    }\n    if (service.runtime !== undefined) {\n      output.Runtime = service.runtime;\n    }\n    if (service.security_opt !== undefined) {\n      output.SecurityOpt = service.security_opt;\n    }\n    if (service.shm_size !== undefined) {\n      output.ShmSize = service.shm_size;\n    }\n    if (service.storage_opt !== undefined) {\n      output.StorageOpt = service.storage_opt;\n    }\n    if (service.sysctls !== undefined) {\n      if (service.sysctls.length > 0) {\n        var sysctls = {};\n        for (var sysctlsb of service.sysctls) {\n          let p = sysctlsb.split('=');\n          sysctls[p[0]] = p[1];\n        }\n        output.Sysctls = sysctls;\n      } else {\n        let sysctlKeys = Object.keys(service.sysctls);\n        let newSysctls = {};\n        for (let key of sysctlKeys) {\n          newSysctls[key] = service.sysctls[key].toString();\n        }\n        output.Sysctls = newSysctls;\n      }\n    }\n    if (service.userns_mode !== undefined) {\n      output.UsernsMode = service.userns_mode;\n    }\n    if (service.tmpfs !== undefined) {\n      var tmpfs = {};\n      if (Array.isArray(service.tmpfs)) {\n        for (var tmpfsb of service.tmpfs) {\n          let p = tmpfsb.split(':');\n          if (p[1] === undefined) {\n            p[1] = '';\n          }\n          tmpfs[p[0]] = p[1];\n        }\n        output.Tmpfs = tmpfs;\n      } else {\n        let p = service.tmpfs.split(':');\n        if (p[1] === undefined) {\n          p[1] = '';\n        }\n        tmpfs[p[0]] = p[1];\n        output.Tmpfs = tmpfs;\n      }\n    }\n    if (service.ulimits !== undefined) {\n      let ulimitsKeys = Object.keys(service.ulimits);\n      let ulimitsArray = [];\n      for (let key of ulimitsKeys) {\n        let ulimitsObject = {};\n        if (typeof service.ulimits[key] === 'object') {\n          ulimitsObject.Name = key;\n          ulimitsObject.Soft = service.ulimits[key].soft;\n          ulimitsObject.Hard = service.ulimits[key].hard;\n          ulimitsArray.push(ulimitsObject);\n        } else {\n          ulimitsObject.Name = key;\n          ulimitsObject.Soft = service.ulimits[key];\n          ulimitsObject.Hard = service.ulimits[key];\n          ulimitsArray.push(ulimitsObject);\n        }\n      }\n      output.Ulimits = ulimitsArray;\n    }\n    if (service.blkio_config !== undefined) {\n      if (service.blkio_config.weight !== undefined) {\n        output.BlkioWeight = service.blkio_config.weight;\n      }\n      if (service.blkio_config.weight_device !== undefined) {\n        let weight_device = [{}];\n        weight_device[0]['Path'] = service.blkio_config.weight_device[0].path;\n        weight_device[0]['Weight'] =\n          service.blkio_config.weight_device[0].weight;\n        output.BlkioWeightDevice = weight_device;\n      }\n      if (service.blkio_config.device_read_bps !== undefined) {\n        output.BlkioDeviceReadBps = convertSizeStringToByteValue(\n          service.blkio_config.device_read_bps\n        );\n      }\n      if (service.blkio_config.device_read_iops !== undefined) {\n        let device_read_iops = [{}];\n        device_read_iops[0]['Path'] =\n          service.blkio_config.device_read_iops[0].path;\n        device_read_iops[0]['Rate'] =\n          service.blkio_config.device_read_iops[0].rate;\n        output.BlkioDeviceReadIOps = device_read_iops;\n      }\n      if (service.blkio_config.device_write_bps !== undefined) {\n        output.BlkioDeviceWriteBps = convertSizeStringToByteValue(\n          service.blkio_config.device_write_bps\n        );\n      }\n      if (service.blkio_config.device_write_iops !== undefined) {\n        let device_write_iops = [{}];\n        device_write_iops[0]['Path'] =\n          service.blkio_config.device_write_iops[0].path;\n        device_write_iops[0]['Rate'] =\n          service.blkio_config.device_write_iops[0].rate;\n        output.BlkioDeviceWriteIOps = device_write_iops;\n      }\n    }\n    if (service.logging !== undefined) {\n      let logging = {};\n      logging.Type = service.logging.driver;\n      logging.Config = service.logging.options;\n      output.LogConfig = logging;\n    }\n    return output;\n  },\n\n  buildVolumesHostconfig: function (projectName, volumes, output, type, cwd) {\n    if (output['Binds'] === undefined) {\n      output['Binds'] = [];\n    }\n    for (var volume of volumes) {\n      if (typeof volume === 'string' || volume instanceof String) {\n        if (\n          volume.substring(0, 2) === './' ||\n          volume.substring(0, 3) === '../' ||\n          volume[0] === '/'\n        ) {\n          const stdVolume = standardizeVolumeStr(volume, cwd);\n          let aux = stdVolume;\n          if (type == 'ro') {\n            aux += ':ro';\n          }\n          output['Binds'].push(aux);\n        } else {\n          var aux = projectName + '_' + volume;\n          if (type == 'ro') {\n            aux += ':ro';\n          }\n          output['Binds'].push(aux);\n        }\n      } else {\n        var volumestr = '';\n        if (volume.source && volume.target) {\n          if (\n            volume.source.substring(0, 2) === './' ||\n            volume.source.substring(0, 3) === '../' ||\n            volume.source[0] === '/'\n          ) {\n            volumestr += standardizeVolumeStr(\n              volume.source + ':' + volume.target,\n              cwd\n            );\n          } else {\n            volumestr +=\n              projectName + '_' + volume.source + ':' + volume.target + ':';\n          }\n        }\n        if (volume.read_only || type == 'ro') {\n          volumestr += 'ro,';\n        }\n        if (volume.volume && volume.volume.nocopy) {\n          volumestr += 'nocopy,';\n        }\n        if (volume.bind && volume.bind.propagation) {\n          volumestr += volume.bind.propagation + ',';\n        }\n        volumestr = volumestr.slice(0, -1);\n        output['Binds'].push(volumestr);\n      }\n    }\n  },\n\n  buildVolumes: function (volumes, opts) {\n    if (opts['Volumes'] === undefined) {\n      opts['Volumes'] = {};\n    }\n    for (var volume of volumes) {\n      if (volume.substring(0, 2) === './' || volume[0] === '/') {\n        continue;\n      }\n      if (typeof volume === 'string' || volume instanceof String) {\n        var v = volume.split(':');\n        opts['Volumes'][v[1]] = {};\n      } else {\n        if (volume.target) {\n          opts['Volumes'][volume.target] = {};\n        }\n      }\n    }\n  },\n\n  buildEnvVars: function (service) {\n    var output = [];\n\n    if (service.env_file !== undefined) {\n      if (Array.isArray(service.env_file)) {\n        for (let env_file_path of service.env_file) {\n          this.buildEnvVarsFromFile(env_file_path, output);\n        }\n      } else {\n        this.buildEnvVarsFromFile(service.env_file, output);\n      }\n    }\n\n    if (service.environment !== undefined) {\n      if (Array.isArray(service.environment)) {\n        for (let environment_line of service.environment) {\n          output.push(environment_line);\n        }\n      } else {\n        var envsNames = Object.keys(service.environment);\n        for (var envName of envsNames) {\n          output.push(envName + '=' + service.environment[envName]);\n        }\n      }\n    }\n    return output;\n  },\n\n  buildNetworks: function (projectName, serviceName, serviceNetworks, networksToAttach, opts, toplevelNetworks) {\n    if (Array.isArray(serviceNetworks)) {\n      for (let index = 0; index < serviceNetworks.length; index++) {\n        let networkName = projectName + '_' + serviceNetworks[index];\n        // check if network is external\n        if (toplevelNetworks !== undefined) {\n          if (Object.keys(toplevelNetworks).includes(serviceNetworks[index])) {\n            if (toplevelNetworks[serviceNetworks[index]].external === true) {\n              // it is external network\n              networkName = toplevelNetworks[serviceNetworks[index]].name\n            }\n          }\n        }\n        let networkTemplate = {\n          NetworkingConfig: {\n            EndpointsConfig: {},\n          },\n        };\n        networkTemplate.NetworkingConfig.EndpointsConfig[networkName] = {};\n        networkTemplate.NetworkingConfig.EndpointsConfig[networkName][\n          'Aliases'\n        ] = [serviceName];\n        if (index === 0)\n          opts.NetworkingConfig.EndpointsConfig =\n            networkTemplate.NetworkingConfig.EndpointsConfig;\n\n        networksToAttach.push(networkTemplate.NetworkingConfig.EndpointsConfig);\n      }\n    } else {\n      let networkNames = Object.keys(serviceNetworks);\n      for (let index = 0; index < networkNames.length; index++) {\n        let network = serviceNetworks[networkNames[index]] || {};\n        let networkName = projectName + '_' + serviceNetworks[index];\n        // check if network is external\n        if (toplevelNetworks !== undefined) {\n          if (Object.keys(toplevelNetworks).includes(networkNames[index])) {\n            if (toplevelNetworks[networkNames[index]].external === true) {\n              // it is external network\n              networkName = toplevelNetworks[networkNames[index]].name\n            }\n          }\n        }\n        let networkTemplate = {\n          NetworkingConfig: {\n            EndpointsConfig: {},\n          },\n        };\n        networkTemplate.NetworkingConfig.EndpointsConfig[networkName] = {};\n        networkTemplate.NetworkingConfig.EndpointsConfig[networkName][\n          'IPAMConfig'\n        ] = {};\n        if (network.aliases !== undefined) {\n          networkTemplate.NetworkingConfig.EndpointsConfig[networkName][\n            'Aliases'\n          ] = network.aliases;\n        }\n        if (network.ipv4_address !== undefined) {\n          networkTemplate.NetworkingConfig.EndpointsConfig[\n            networkName\n          ].IPAMConfig['IPv4Address'] = network.ipv4_address;\n        }\n        if (network.ipv6_address !== undefined) {\n          networkTemplate.NetworkingConfig.EndpointsConfig[\n            networkName\n          ].IPAMConfig['IPv6Address'] = network.ipv6_address;\n        }\n        if (network.link_local_ips !== undefined) {\n          networkTemplate.NetworkingConfig.EndpointsConfig[\n            networkName\n          ].IPAMConfig['LinkLocalIPs'] = network.link_local_ips;\n        }\n        if (network.priority !== undefined) {\n          networkTemplate.NetworkingConfig.EndpointsConfig[\n            networkName\n          ].priority = network.priority;\n        } else {\n          networkTemplate.NetworkingConfig.EndpointsConfig[\n            networkName\n          ].priority = 0;\n        }\n        if (index === 0) {\n          opts.NetworkingConfig.EndpointsConfig =\n            networkTemplate.NetworkingConfig.EndpointsConfig;\n        }\n        networksToAttach.push(networkTemplate.NetworkingConfig.EndpointsConfig);\n      }\n    }\n  },\n\n  // TODO: OPTIMIZE!\n  convertSizeStringToByteValue: function (obj) {\n    let rate = obj[0].rate.toLowerCase();\n    let new_obj = [{}];\n    if (rate.includes('k')) {\n      if (rate.indexOf('k') == rate.length - 1) {\n        rate = rate.replace('k', '');\n      } else if (rate.indexOf('k') == rate.length - 2) {\n        rate = rate.replace('kb', '');\n      }\n      new_obj[0]['Path'] = obj[0].path;\n      new_obj[0]['Rate'] = rate * 1024;\n      return new_obj;\n    } else if (rate.includes('m')) {\n      if (rate.indexOf('m') == rate.length - 1) {\n        rate = rate.replace('m', '');\n      } else if (rate.indexOf('m') == rate.length - 2) {\n        rate = rate.replace('mb', '');\n      }\n      new_obj[0]['Path'] = obj[0].path;\n      new_obj[0]['Rate'] = rate * 1024 * 1024;\n      return new_obj;\n    } else if (rate.includes('g')) {\n      if (rate.indexOf('g') == rate.length - 1) {\n        rate = rate.replace('g', '');\n      } else if (rate.indexOf('g') == rate.length - 2) {\n        rate = rate.replace('gb', '');\n      }\n      new_obj[0]['Path'] = obj[0].path;\n      new_obj[0]['Rate'] = rate * 1024 * 1024 * 1024;\n      return new_obj;\n    }\n  },\n\n  buildEnvVarsFromFile: function (env_file_path, output) {\n    // Each line in an env file MUST be in `VAR=VAL` format.\n    let env_file = fs\n      .readFileSync(env_file_path, 'utf8')\n      .toString()\n      .split('\\n');\n    for (let env_line of env_file) {\n      // Lines beginning with `#` MUST be ignored. Blank lines MUST also be ignored.\n      if (env_line != '' && env_line.indexOf('#') != 0) {\n        let env_line_split = env_line.split('=');\n        // `VAL` MAY be omitted, sin such cases the variable value is empty string. `=VAL` MAY be omitted, in such cases the variable is **unset**.\n        if (env_line_split[0] != '' && env_line_split[1] != '') {\n          output.push(env_line);\n        }\n      }\n    }\n  },\n\n  fillPortArray: function (start, end) {\n    return Array(end - start + 1)\n      .fill()\n      .map((_, idx) => start + idx);\n  },\n\n  buildDockerImage: async function (\n    docker,\n    buildPath,\n    obj,\n    dockerfile,\n    options\n  ) {\n    options = options || {};\n    if (dockerfile !== null) {\n      obj['dockerfile'] = path.basename(dockerfile);\n      let streami = await docker.buildImage(\n        {\n          context: buildPath,\n          src: [dockerfile],\n        },\n        obj\n      );\n      if (options.verbose === true) {\n        streami.pipe(process.stdout);\n      } else {\n        streami.pipe(stream.PassThrough());\n      }\n      await new Promise((fulfill) => streami.once('end', fulfill));\n    } else {\n      var tarStream = tar.pack(buildPath);\n      let streami = await docker.buildImage(tarStream, obj);\n      if (options.verbose === true) {\n        streami.pipe(process.stdout);\n      } else {\n        streami.pipe(stream.PassThrough());\n      }\n      await new Promise((fulfill) => streami.once('end', fulfill));\n    }\n  },\n};\n"
  },
  {
    "path": "lib/tools.js",
    "content": "module.exports = {\n  'getImages': function (recipe) {\n    var images = [];\n    var serviceNames = Object.keys(recipe.services || []);\n\n    for (var serviceName of serviceNames) {\n      if (recipe.services[serviceName].image) {\n        images.push(recipe.services[serviceName].image);\n      }\n    }\n    return images;\n  },\n  'sortServices': function (recipe) {\n    var order = [];\n    var serviceNames = Object.keys(recipe.services || []);\n\n    while (order.length !== serviceNames.length) {\n      for (var serviceName of serviceNames) {\n        if (order.indexOf(serviceName) === -1) {\n          let depends_on = recipe.services[serviceName].depends_on;\n          if (typeof depends_on === \"object\" && !Array.isArray(depends_on)) {\n            // if we are using Long Syntax https://github.com/compose-spec/compose-spec/blob/master/spec.md#long-syntax-1\n            // we will need to get keys from object and use them as dependencies\n            depends_on = Object.keys(depends_on)\n          } \n          insertService(serviceName, depends_on || [], order);\n        }\n      }\n    }\n    return order;\n  },\n  'sortNetworksToAttach': function (networksToAttach) {\n    var networksToAttachSorted = [];\n    for (let i = 0; i < networksToAttach.length; i++) {\n      let networkName = Object.keys(networksToAttach[i]);\n      if (i === 0) {\n        networksToAttachSorted.push(networksToAttach[i]);\n      } else {\n        let aux = 0;\n        for (let j = 0; j < networksToAttachSorted.length; j++) {\n          let networkNameSorted = Object.keys(networksToAttachSorted[j]);\n          if (networksToAttachSorted[j][networkNameSorted].priority > networksToAttach[i][networkName].priority) {\n            aux += j + 1;\n          } else if (networksToAttachSorted[j][networkNameSorted].priority < networksToAttach[i][networkName].priority) {\n            aux += j - 1;\n          } else {\n            aux += j + 1;\n          }\n        }\n        if (aux < 0) aux = 0;\n        networksToAttachSorted.splice(aux, 0, networksToAttach[i]);\n      }\n    }\n    return networksToAttachSorted;\n  }\n}\n\nfunction insertService(serviceName, depends_on, order) {\n  var position = -1;\n  for (var serviceDep of depends_on) {\n    var p = order.indexOf(serviceDep);\n    if (p === -1) return;\n    if (p > position) position = p;\n  }\n  order.splice(position + 1, 0, serviceName);\n}\n"
  },
  {
    "path": "lib/volumes.js",
    "content": "async function down(docker, projectName, recipe, output) {\n  var volumes = [];\n  var volumeNames = Object.keys(recipe.volumes || []);\n  for (var volumeName of volumeNames) {\n    try {\n      var volume = await docker.getVolume(projectName + '_' + volumeName);\n    } catch (e) {}\n\n    try {\n      await volume.remove();\n    } catch (e) {}\n  }\n  return volumes;\n}\n\nasync function up(docker, projectName, recipe, output) {\n  var volumes = [];\n  var volumeNames = Object.keys(recipe.volumes || []);\n  for (var volumeName of volumeNames) {\n    var volume = recipe.volumes[volumeName];\n    if (volume === null) volume = {};\n    if (volume.external === true) continue;\n    var opts = {\n      Name: projectName + '_' + volumeName,\n      Driver: volume.driver,\n      DriverOpts: volume.driver_opts,\n      Labels: {\n        ...volume.labels,\n        ...{\n          'com.docker.compose.project': projectName,\n          'com.docker.compose.volume': volumeName,\n        },\n      },\n    };\n    if (volume.name !== undefined) {\n      opts.Name = volume.name;\n    }\n    volumes.push(await docker.createVolume(opts));\n  }\n  return volumes;\n}\n\nmodule.exports = {\n  down,\n  up,\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"dockerode-compose\",\n  \"version\": \"1.4.0\",\n  \"description\": \"docker-compose in nodejs using dockerode\",\n  \"main\": \"./compose.js\",\n  \"scripts\": {\n    \"test\": \"./node_modules/mocha/bin/mocha.js -R spec --exit\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/apocas/dockerode-compose.git\"\n  },\n  \"author\": \"Pedro Dias <petermdias@gmail.com>\",\n  \"license\": \"Apache-2.0\",\n  \"bugs\": {\n    \"url\": \"https://github.com/apocas/dockerode-compose/issues\"\n  },\n  \"keywords\": [\n    \"docker\",\n    \"docker-compose\"\n  ],\n  \"homepage\": \"https://github.com/apocas/dockerode-compose#readme\",\n  \"dependencies\": {\n    \"dockerode\": \"^4.0.0\",\n    \"js-yaml\": \"^4.0.0\",\n    \"tar-fs\": \"^2.1.1\"\n  },\n  \"devDependencies\": {\n    \"chai\": \"~4.2.0\",\n    \"memorystream\": \"~0.3.0\",\n    \"mocha\": \"^10.2.0\"\n  }\n}\n"
  },
  {
    "path": "test/assets/complex_example/2-nodejs-projects/app2.yml",
    "content": "version: '3'\r\nservices:\r\n\r\n  app2:\r\n    build: ./simple-node-app-1235\r\n  \r\nvolumes:\r\n  db_data: {}"
  },
  {
    "path": "test/assets/complex_example/2-nodejs-projects/docker-compose.yml",
    "content": "version: '3'\r\nservices:\r\n\r\n  db:\r\n    image: mysql:5.7\r\n    volumes:\r\n      - db_data:/var/lib/mysql\r\n    restart: always\r\n    environment:\r\n      MYSQL_ROOT_PASSWORD: root\r\n      MYSQL_DATABASE: test\r\n      MYSQL_USER: test\r\n      MYSQL_PASSWORD: testpassword\r\n\r\n  app1:\r\n    build: ./simple-node-app\r\n    environment:\r\n      DB_HOST: db\r\n      DB_DATABASE: test\r\n      DB_USER: teste\r\n      DB_PASSWORD: testpassword\r\n\r\n  app2:\r\n    extends:\r\n      file: ./app2.yml\r\n      service: app2\r\n\r\n  app3:\r\n    extends:\r\n      service: app1\r\n\r\n  app4:\r\n    extends:\r\n      file: ./simple-node-app-1235/app4.yml\r\n      service: app4\r\n  \r\nvolumes:\r\n  db_data: {}"
  },
  {
    "path": "test/assets/complex_example/2-nodejs-projects/simple-node-app/Dockerfile",
    "content": "FROM ubuntu\r\n\r\nRUN \\\r\n  apt-get update && \\\r\n  apt-get install -y nginx && service nginx start && echo \"BACKEND\"\r\n\r\nCMD [\"bash\"]"
  },
  {
    "path": "test/assets/complex_example/2-nodejs-projects/simple-node-app-1235/Dockerfile",
    "content": "FROM ubuntu\r\n\r\nRUN \\\r\n  apt-get update && \\\r\n  apt-get install -y nginx && service nginx start && echo \"BACKEND\"\r\n\r\nCMD [\"bash\"]"
  },
  {
    "path": "test/assets/complex_example/2-nodejs-projects/simple-node-app-1235/app4.yml",
    "content": "version: '3'\r\nservices:\r\n\r\n  app4:\r\n    build: ./simple-node-app-1236\r\n  \r\nvolumes:\r\n  db_data: {}"
  },
  {
    "path": "test/assets/complex_example/2-nodejs-projects/simple-node-app-1235/simple-node-app-1236/Dockerfile",
    "content": "FROM ubuntu\r\n\r\nRUN \\\r\n  apt-get update && \\\r\n  apt-get install -y nginx && service nginx start && echo \"BACKEND\"\r\n\r\nCMD [\"bash\"]"
  },
  {
    "path": "test/assets/complex_example/docker-compose.yml",
    "content": "version: '3'\r\nservices:\r\n\r\n  db:\r\n    extends:\r\n      file: ./2-nodejs-projects/docker-compose.yml\r\n      service: db\r\n    volumes:\r\n      - db_data:/var/lib/mysql\r\n    expose:\r\n      - \"3306\"\r\n\r\n  app1:\r\n    extends:\r\n      file: ./2-nodejs-projects/docker-compose.yml\r\n      service: app1\r\n    depends_on: \r\n      - db\r\n    ports:\r\n      - \"5001-5005:5000\"\r\n\r\n  app2:\r\n    extends:\r\n      file: ./2-nodejs-projects/docker-compose.yml\r\n      service: app2\r\n    ports:\r\n      - \"5006-5010:5000\"\r\n\r\n  app3:\r\n    extends:\r\n      file: ./2-nodejs-projects/docker-compose.yml\r\n      service: app3\r\n    ports:\r\n      - \"5006-5010:5000\"\r\n    \r\n  app4:\r\n    extends:\r\n      file: ./2-nodejs-projects/docker-compose.yml\r\n      service: app4\r\n    ports:\r\n      - \"5006-5010:5000\"\r\n\r\n  app5:\r\n    extends:\r\n      service: app4\r\n\r\n  app6:\r\n    extends:\r\n      service: app3\r\n\r\n  app7:\r\n    extends:\r\n      service: app2\r\n\r\nvolumes:\r\n  db_data: {}"
  },
  {
    "path": "test/assets/depends.yml",
    "content": "version: \"3.9\"\n\nservices:\n  wordpress4:\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\n      WORDPRESS_DB_NAME: wordpress\n\n  wordpress5:\n    depends_on:\n      - wordpress4\n      - db\n      - wordpress2\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\n      WORDPRESS_DB_NAME: wordpress\n\n  wordpress6:\n    depends_on:\n      db:\n        condition: service_started\n      wordpress2:\n        condition: service_started\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\n      WORDPRESS_DB_NAME: wordpress\n\n  db:\n    image: mysql:5.7\n    volumes:\n      - db_data:/var/lib/mysql\n    restart: always\n    environment:\n      MYSQL_ROOT_PASSWORD: somewordpress\n      MYSQL_DATABASE: wordpress\n      MYSQL_USER: wordpress\n      MYSQL_PASSWORD: wordpress\n\n  wordpress2:\n    depends_on:\n      - wordpress1\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\n      WORDPRESS_DB_NAME: wordpress\n\n  wordpress1:\n    depends_on:\n      - db\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\n      WORDPRESS_DB_NAME: wordpress\n\n  wordpress3:\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\n      WORDPRESS_DB_NAME: wordpress\nvolumes:\n  db_data: {}\nsecrets:\n  server-secret:\n    file: ./test/secret.txt\n  server-secret-external:\n    external: true\n"
  },
  {
    "path": "test/assets/ghost.yml",
    "content": "version: '2'\nservices:\n  gost-db:\n    image: geodan/gost-db\n    volumes:\n      - postgis:/var/lib/postgresql/data\n    environment:\n      POSTGRES_DB: gost\n      POSTGRES_USER: postgres\n      POSTGRES_PASSWORD: postgres\n\n  gost:\n    image: geodan/gost\n    volumes:\n      - gost_conf:/gostserver/config\n    depends_on:\n      - gost-db\n    environment:\n      GOST_LOG_VERBOSE_FLAG: 1\n      GOST_DB_HOST: gost-db\n      GOST_SERVER_EXTERNAL_URI: \"http://localhost:8080\"\n\n  dashboard:\n    image: geodan/gost-dashboard\n    ports:\n      - \"8080:8080\"\n    depends_on:\n      - gost\n\nvolumes:\n  postgis: {}\n  gost_conf: {}"
  },
  {
    "path": "test/assets/mysql.yml",
    "content": "version: '3'\r\nservices:\r\n\r\n  db:\r\n    extends:\r\n      file: ./test/assets/mysql_extends.yml\r\n      service: db\r\n    volumes:\r\n      - db_data:/var/lib/mysql\r\n    expose:\r\n      - \"3306\"\r\n  \r\n  db1:\r\n    extends:\r\n      file: ./test/assets/mysql_extends.yml\r\n      service: db_ext\r\n    volumes:\r\n      - db_data:/var/lib/mysql\r\n    expose:\r\n      - \"3306\"\r\n\r\nvolumes:\r\n  db_data: {}"
  },
  {
    "path": "test/assets/mysql_extends.yml",
    "content": "version: '3'\r\nservices:\r\n\r\n  db:\r\n    image: mysql:5.7\r\n    volumes:\r\n      - db_data:/var/lib/mysql\r\n    restart: always\r\n    environment:\r\n      MYSQL_ROOT_PASSWORD: root\r\n      MYSQL_DATABASE: testdatabase\r\n      MYSQL_USER: testdatabase\r\n      MYSQL_PASSWORD: testdatabase12345\r\n\r\n  db_ext:\r\n    extends:\r\n      service: db\r\n    volumes:\r\n      - db_data:/var/lib/mysql\r\n    expose:\r\n      - \"3306\"\r\n\r\nvolumes:\r\n  db_data: {}"
  },
  {
    "path": "test/assets/secret.txt",
    "content": "xpto"
  },
  {
    "path": "test/assets/test_build/backend/Dockerfile",
    "content": "FROM ubuntu\r\n\r\nRUN \\\r\n  apt-get update && \\\r\n  apt-get install -y nginx && service nginx start && echo \"BACKEND\"\r\n\r\nCMD [\"bash\"]"
  },
  {
    "path": "test/assets/test_build/backend.Dockerfile",
    "content": "FROM ubuntu\r\n\r\nRUN \\\r\n  apt-get update && \\\r\n  apt-get install -y nginx && service nginx start\r\n\r\nCMD [\"bash\"]"
  },
  {
    "path": "test/assets/test_build/build_things/Dockerfile",
    "content": "FROM ubuntu\r\n\r\nRUN \\\r\n  apt-get update && \\\r\n  apt-get install -y nginx && service nginx start\r\n\r\nCMD [\"bash\"]"
  },
  {
    "path": "test/assets/test_build/docker-compose.yml",
    "content": "services:\r\n  frontend:\r\n    build: ./build_things\r\n\r\n  backend:\r\n    build:\r\n      context: backend\r\n      cache_from:\r\n        - ubuntu\r\n      args:\r\n        GIT_COMMIT: cdc3b19\r\n  \r\n  futureend:\r\n    build:\r\n      context: backend\r\n      cache_from:\r\n        - ubuntu\r\n      args:\r\n        GIT_COMMIT: cdc3b19\r\n      dockerfile: ../backend.Dockerfile"
  },
  {
    "path": "test/assets/wordpress.yml",
    "content": "version: \"3.9\"\n    \nservices:\n  db:\n    image: mysql:5.7\n    volumes:\n      - db_data:/var/lib/mysql\n    restart: always\n    environment:\n      MYSQL_ROOT_PASSWORD: somewordpress\n      MYSQL_DATABASE: wordpress\n      MYSQL_USER: wordpress\n      MYSQL_PASSWORD: wordpress\n    \n  wordpress:\n    depends_on:\n      - db\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    volumes_from:\n      - db:ro\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\n      WORDPRESS_DB_NAME: wordpress\nvolumes:\n  db_data: {}"
  },
  {
    "path": "test/assets/wordpress_long.yml",
    "content": "version: \"3.9\"\n    \nservices:\n  db:\n    image: mysql:5.7\n    volumes:\n      - source: db_data\n        target: /var/lib/mysql\n    restart: always\n    environment:\n      MYSQL_ROOT_PASSWORD: somewordpress\n      MYSQL_DATABASE: wordpress\n      MYSQL_USER: wordpress\n      MYSQL_PASSWORD: wordpress\n    \n  wordpress:\n    depends_on:\n      - db\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\n      WORDPRESS_DB_NAME: wordpress\nvolumes:\n  db_data: {}"
  },
  {
    "path": "test/assets/wordpress_original.yml",
    "content": "version: \"3.3\"\n\nservices:\n  db:\n    image: mysql:5.7\n    volumes:\n      - db_data:/var/lib/mysql\n    restart: always\n    environment:\n      MYSQL_ROOT_PASSWORD: somewordpress\n      MYSQL_DATABASE: wordpress\n      MYSQL_USER: wordpress\n      MYSQL_PASSWORD: wordpress\n\n  wordpress:\n    depends_on:\n      - db\n    image: wordpress:latest\n    ports:\n      - \"8000:80\"\n    restart: always\n    environment:\n      WORDPRESS_DB_HOST: db:3306\n      WORDPRESS_DB_USER: wordpress\n      WORDPRESS_DB_PASSWORD: wordpress\nvolumes:\n  db_data:\n"
  },
  {
    "path": "test/compose.js",
    "content": "const expect = require('chai').expect,\n  assert = require('assert');\n\nvar compose = require('./spec_helper').compose;\nvar compose_complex = require('./spec_helper').compose_complex;\nvar compose_build = require('./spec_helper').compose_build;\nvar docker = require('./spec_helper').docker;\n\ndescribe('compose', function () {\n\n  describe('#pull', function () {\n    it(\"should pull all needed images with verbose\", function (done) {\n      this.timeout(600000);\n      (async () => {\n        await compose.pull(null, { 'verbose': true });\n        done();\n      })();\n    });\n\n    it(\"should pull all needed images silently\", function (done) {\n      this.timeout(600000);\n      (async () => {\n        await compose.pull();\n        done();\n      })();\n    });\n\n    it(\"should pull all needed images returning streams\", function (done) {\n      this.timeout(600000);\n      (async () => {\n        var streams = await compose.pull(null, { 'streams': true });\n        expect(streams).to.be.ok;\n        done();\n      })();\n    });\n  });\n\n  describe('#up', function () {\n    it(\"should do compose up\", function (done) {\n      this.timeout(60000);\n      (async () => {\n        var report = await compose.up();\n        expect(report.services).to.be.ok;\n        done();\n      })();\n    });\n    afterEach('clean up', function (done) {\n      this.timeout(60000);\n      (async () => {\n        await compose.down({ volumes: true });\n        done();\n      })();\n    });\n  });\n\n  describe('#down', function () {\n    beforeEach('bring up', function (done) {\n      this.timeout(20000);\n      (async () => {\n        await compose.up();\n        done();\n      })();\n    });\n    it(\"should do compose down\", function (done) {\n      this.timeout(60000);\n      (async () => {\n        await compose.down({volumes: true});\n        let listContainers = await docker.listContainers({ 'all': true, 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}});\n        expect(listContainers).to.be.empty\n        let listVolumes  = await docker.listVolumes({ 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}})\n        expect(listVolumes.Volumes).to.be.empty\n        expect(listVolumes.Warnings).to.be.null\n        let listNetworks = await docker.listNetworks({ 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}})\n        expect(listNetworks).to.be.empty\n        done();\n      })();\n    });\n  });\n\n  describe('#up_complex', function () {\n    it(\"should do compose up complex example with extends and build\", function (done) {\n      this.timeout(300000);\n      (async () => {\n        var report = await compose_complex.up();\n        expect(report.services).to.be.ok;\n        done();\n      })();\n    });\n    afterEach('clean up', function (done) {\n      this.timeout(60000);\n      (async () => {\n        await compose_complex.down({ volumes: true });\n        done();\n      })();\n    });\n  });\n\n  describe('#down_complex', function () {\n    beforeEach('bring up', function (done) {\n      this.timeout(300000);\n      (async () => {\n        await compose_complex.up();\n        done();\n      })();\n    });\n    it(\"should do compose down complex example with extends and build\", function (done) {\n      this.timeout(60000);\n      (async () => {\n        await compose_complex.down({volumes: true});\n        let listContainers = await docker.listContainers({ 'all': true, 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}});\n        expect(listContainers).to.be.empty\n        let listVolumes  = await docker.listVolumes({ 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}})\n        expect(listVolumes.Volumes).to.be.empty\n        expect(listVolumes.Warnings).to.be.null\n        let listNetworks = await docker.listNetworks({ 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}})\n        expect(listNetworks).to.be.empty\n        done();\n      })();\n    });\n  });\n\n  describe('#up_build', function () {\n    it(\"should do compose up example with build\", function (done) {\n      this.timeout(300000);\n      (async () => {\n        var report = await compose_build.up();\n        expect(report.services).to.be.ok;\n        done();\n      })();\n    });\n    it(\"should do compose up example with build(verbose)\", function (done) {\n      this.timeout(300000);\n      (async () => {\n        var report = await compose_build.up({ 'verbose': true });\n        expect(report.services).to.be.ok;\n        done();\n      })();\n    });\n    afterEach('clean up', function (done) {\n      this.timeout(60000);\n      (async () => {\n        await compose_build.down({ volumes: true });\n        done();\n      })();\n    });\n  });\n\n  describe('#down_build', function () {\n    beforeEach('bring up', function (done) {\n      this.timeout(300000);\n      (async () => {\n        await compose_build.up();\n        done();\n      })();\n    });\n    it(\"should do compose down example with build\", function (done) {\n      this.timeout(60000);\n      (async () => {\n        await compose_build.down({volumes: true});\n        let listContainers = await docker.listContainers({ 'all': true, 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}});\n        expect(listContainers).to.be.empty\n        let listVolumes  = await docker.listVolumes({ 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}})\n        expect(listVolumes.Volumes).to.be.empty\n        expect(listVolumes.Warnings).to.be.null\n        let listNetworks = await docker.listNetworks({ 'filters': {\"label\":[`com.docker.compose.project=${compose.projectName}`]}})\n        expect(listNetworks).to.be.empty\n        done();\n      })();\n    });\n  });\n\n});\n"
  },
  {
    "path": "test/spec_helper.js",
    "content": "var Dockerode = require('dockerode');\nvar DockerodeCompose = require('../compose');\n\nvar docker = new Dockerode();\nvar compose = new DockerodeCompose(docker, './test/assets/wordpress_original.yml', 'dockerodec_wordpress');\nvar compose_complex = new DockerodeCompose(docker, './test/assets/complex_example/docker-compose.yml', 'dockerodec_complex');\nvar compose_build = new DockerodeCompose(docker, './test/assets/test_build/docker-compose.yml', 'dockerodec_build');\n\nmodule.exports = {\n  'docker': docker,\n  'compose': compose,\n  'compose_complex': compose_complex,\n  'compose_build': compose_build\n}"
  },
  {
    "path": "test/tools.js",
    "content": "const expect = require('chai').expect;\nconst tools = require('../lib/tools');\nconst yaml = require('js-yaml');\nconst fs = require('fs');\n\ndescribe('tools', function () {\n\n  describe('#sortservices', function () {\n    it(\"should sort services\", function (done) {\n      var recipe = yaml.load(fs.readFileSync('./test/assets/depends.yml', 'utf8'));\n\n      expect(tools.sortServices(recipe)).to.eql([\n        'wordpress3',\n        'db',\n        'wordpress1',\n        'wordpress2',\n        'wordpress6',\n        'wordpress4',\n        'wordpress5'\n      ]);\n      done();\n    });\n  });\n\n});\n"
  }
]