@balena/compose 0.1.0-import-modules-d457c16709fa5260df6ff68da79c0f0e92f7aaa5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +201 -0
  3. package/README.md +200 -0
  4. package/dist/build/builder.d.ts +18 -0
  5. package/dist/build/builder.js +127 -0
  6. package/dist/build/builder.js.map +1 -0
  7. package/dist/build/index.d.ts +4 -0
  8. package/dist/build/index.js +7 -0
  9. package/dist/build/index.js.map +1 -0
  10. package/dist/build/plugin.d.ts +11 -0
  11. package/dist/build/plugin.js +3 -0
  12. package/dist/build/plugin.js.map +1 -0
  13. package/dist/build/utils.d.ts +8 -0
  14. package/dist/build/utils.js +60 -0
  15. package/dist/build/utils.js.map +1 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +6 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/multibuild/build-metadata.d.ts +24 -0
  20. package/dist/multibuild/build-metadata.js +166 -0
  21. package/dist/multibuild/build-metadata.js.map +1 -0
  22. package/dist/multibuild/build-secrets/Dockerfile +3 -0
  23. package/dist/multibuild/build-secrets/Dockerfile.remove +3 -0
  24. package/dist/multibuild/build-secrets/index.d.ts +43 -0
  25. package/dist/multibuild/build-secrets/index.js +140 -0
  26. package/dist/multibuild/build-secrets/index.js.map +1 -0
  27. package/dist/multibuild/build-task.d.ts +36 -0
  28. package/dist/multibuild/build-task.js +3 -0
  29. package/dist/multibuild/build-task.js.map +1 -0
  30. package/dist/multibuild/build.d.ts +6 -0
  31. package/dist/multibuild/build.js +167 -0
  32. package/dist/multibuild/build.js.map +1 -0
  33. package/dist/multibuild/constants.d.ts +1 -0
  34. package/dist/multibuild/constants.js +5 -0
  35. package/dist/multibuild/constants.js.map +1 -0
  36. package/dist/multibuild/contracts.d.ts +6 -0
  37. package/dist/multibuild/contracts.js +55 -0
  38. package/dist/multibuild/contracts.js.map +1 -0
  39. package/dist/multibuild/errors.d.ts +43 -0
  40. package/dist/multibuild/errors.js +71 -0
  41. package/dist/multibuild/errors.js.map +1 -0
  42. package/dist/multibuild/external.d.ts +5 -0
  43. package/dist/multibuild/external.js +62 -0
  44. package/dist/multibuild/external.js.map +1 -0
  45. package/dist/multibuild/index.d.ts +33 -0
  46. package/dist/multibuild/index.js +187 -0
  47. package/dist/multibuild/index.js.map +1 -0
  48. package/dist/multibuild/local-image.d.ts +25 -0
  49. package/dist/multibuild/local-image.js +29 -0
  50. package/dist/multibuild/local-image.js.map +1 -0
  51. package/dist/multibuild/manifests.d.ts +19 -0
  52. package/dist/multibuild/manifests.js +27 -0
  53. package/dist/multibuild/manifests.js.map +1 -0
  54. package/dist/multibuild/path-utils.d.ts +4 -0
  55. package/dist/multibuild/path-utils.js +28 -0
  56. package/dist/multibuild/path-utils.js.map +1 -0
  57. package/dist/multibuild/registry-secrets.d.ts +16 -0
  58. package/dist/multibuild/registry-secrets.js +75 -0
  59. package/dist/multibuild/registry-secrets.js.map +1 -0
  60. package/dist/multibuild/resolve.d.ts +5 -0
  61. package/dist/multibuild/resolve.js +63 -0
  62. package/dist/multibuild/resolve.js.map +1 -0
  63. package/dist/multibuild/utils.d.ts +10 -0
  64. package/dist/multibuild/utils.js +61 -0
  65. package/dist/multibuild/utils.js.map +1 -0
  66. package/dist/multibuild/validation-types/varlist.d.ts +7 -0
  67. package/dist/multibuild/validation-types/varlist.js +52 -0
  68. package/dist/multibuild/validation-types/varlist.js.map +1 -0
  69. package/package.json +91 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file
4
+ automatically by Versionist. DO NOT EDIT THIS FILE MANUALLY!
5
+ This project adheres to [Semantic Versioning](http://semver.org/).
6
+
7
+ ## 0.1.0 - 2022-04-16
8
+
9
+ * Import resin-docker-build [Akis Kesoglou]
10
+ * Import balena-multibuild [Akis Kesoglou]
11
+
12
+ # v0.0.1
13
+ ## (2022-04-15)
14
+
15
+ * Add scaffolding [Akis Kesoglou]
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 Balena Ltd.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,200 @@
1
+ # balena-compose
2
+
3
+ Complete toolkit to build docker-compose.yml files and optionally deploy them to balenaCloud.
4
+
5
+ Important: balena-compose is stable and perfectly usable but also, fundamentally, just a merge of several pre-existing different modules, that are merely re-exported from this one. You should expect a complete rewrite of the exported API in the medium term. What follows are pretty much the concatenated READMEs of these modules.
6
+
7
+
8
+ ## multibuild
9
+
10
+ This module is designed to make it easy to build a composition given a
11
+ representation of this composition, and a tar stream. The output will be several
12
+ images present on the given docker daemon.
13
+
14
+ ### Reference
15
+
16
+ ```
17
+ function splitBuildStream(composition: Composition, buildStream: ReadableStream): Promise<BuildTask[]>
18
+ ```
19
+
20
+ Given a Composition which conforms to the type from
21
+ [@balena/compose-parse](https://github.com/balena-io-modules/balena-compose-parse)
22
+ and a stream which will produce a tar archive, split this tar archive into a set
23
+ of build tasks which can then be further processed.
24
+
25
+ ```
26
+ function performResolution(
27
+ tasks: BuildTask[],
28
+ architecture: string,
29
+ deviceType: string
30
+ ): Promise<BuildTask[]>
31
+ ```
32
+
33
+ Given a list of build tasks, resolve the projects to a form which the docker
34
+ daemon can build. Currently this function supports all project types which
35
+ [resin-bundle-resolve](https://github.com/resin-io-modules/resin-bundle-resolve)
36
+ supports.
37
+
38
+ Note that this function will also populate the `dockerfile` and `projectType`
39
+ values in the build tasks.
40
+
41
+ ```
42
+ function performBuilds(
43
+ tasks: BuildTask[],
44
+ docker: Dockerode
45
+ ): Promise<LocalImage[]>
46
+ ```
47
+
48
+ Given a list of build tasks, perform the task necessary for the LocalImage to be
49
+ produced. A local image represents an image present on the docker daemon given.
50
+
51
+ Note that one should assign a stream handling function for build output OR a
52
+ progress handling function for image pull output **before** calling this
53
+ function. The fields for these functions are `streamHook` and `progressHook`.
54
+
55
+ ### Example (pseudocode)
56
+
57
+ ```typescript
58
+ import * as Promise from 'bluebird';
59
+
60
+ import { Composition, normalize } from '@balena/compose-parse';
61
+ import { multibuild } from '@balena/compose';
62
+
63
+ const { splitBuildStream, performBuilds } = multibuild;
64
+
65
+ // Get a tar stream and composition from somewhere
66
+ const stream = getBuildStream();
67
+ const composeFile = getComposeFile();
68
+ const docker = getDockerodeHandle();
69
+
70
+ // Parse the compose file
71
+ const comp = normalize(composeFile);
72
+
73
+ splitBuildStream(comp, stream)
74
+ .then((tasks) => {
75
+ return performResolution(tasks, 'armv7hf', 'raspberrypi3');
76
+ })
77
+ .map((task) => {
78
+ if (task.external) {
79
+ task.progressHook = (progress) => {
80
+ console.log(task.serviceName + ': ' + progress);
81
+ };
82
+ } else {
83
+ task.streamHook = (stream) => {
84
+ stream.on('data', (data) => {
85
+ console.log(task.serviceName + ': ', data.toString());
86
+ });
87
+ };
88
+ }
89
+ return task;
90
+ })
91
+ .then((tasks) => {
92
+ return performBuilds(builds, docker);
93
+ })
94
+ .then((images) => {
95
+ // Do something with your images
96
+ });
97
+
98
+ ```
99
+
100
+ ## build
101
+
102
+ A modular, plugin-based approach to building docker containers. Resin-docker-build uses streams and hooks to provide a system which can be added to a build pipeline easily. With a simple but flexible interface, this module is meant to take the pain out of automating docker builds. Resin-docker-build is written in typescript, and all defined types are exported.
103
+
104
+ ### Reference
105
+
106
+ All building is done via the `Builder` object.
107
+
108
+ The `Builder` API has two top-level methods, which are used to trigger builds;
109
+
110
+ * `createBuildStream(buildOpts: Object, hooks: BuildHooks, handler: ErrorHandler): ReadWriteStream`
111
+
112
+ Initialise a docker daemon and set it up to wait for some streaming data. The stream is returned to the caller for both reading and writing. Success and failure callbacks are provided via the hooks interface (see below). `buildOpts` is passed directly to the docker daemon and the expected input by the daemon is a tar stream.
113
+
114
+ * `buildDir(directory: string, buildOpts: Object, hooks: BuildHooks, handler: ErrorHandler): ReadWriteStream`
115
+
116
+ Inform the docker daemon to build a directory on the host. A stream is returned for reading, and the same success/failure callbacks apply. `buildOpts` is passed directly to the docker daemon.
117
+
118
+ * The `handler` parameter:
119
+
120
+ If an exception is thrown from within the hooks, because it is executing in a different context to the initial api call they will not be propagated. Using the error handler means that you can handle the error as necessary (for instance propagate to your global catch, or integrate it into a promise chain using `reject` as a handler). The error handler is optional. Note that the error handler will not be called with a build error, instead with that being dropped to the `buildFailure` hook, but if that hook throws, the handler will be called.
121
+
122
+ ### Hooks
123
+
124
+ Currently the hooks supported are;
125
+
126
+ * `buildStream(stream: ReadWriteStream): void`
127
+
128
+ Called by the builder when a stream is ready to communicate directly with the daemon. This is useful for parsing/showing the output and transforming any input before providing it to the docker daemon.
129
+
130
+ * `buildSuccess(imageId: string, layers: string[]): void`
131
+
132
+ Called by the builder when the daemon has successfully built the image. `imageId` is the sha digest provided by the daemon, which can be used for pushing, running etc. `layers` is a list of sha digests pointing to the intermediate layers used by docker. Can be useful for cleanup.
133
+
134
+ * `buildFailure(error: Error)`
135
+
136
+ Called by the builder when a build has failed for whatever reason. The reason is provided as a standard node error object. This was also close the build stream. No more hooks will be called after this.
137
+
138
+ ### Examples
139
+
140
+ Examples are provided in typescript.
141
+
142
+ #### Building a directory
143
+
144
+ ```typescript
145
+ import { build } from '@balena/compose';
146
+
147
+ const { Builder, BuildHooks } = build;
148
+
149
+ const builder = Builder.fromDockerOpts({ socketPath: '/var/run/docker.sock' })
150
+
151
+ const hooks: BuildHooks = {
152
+ buildStream: (stream: NodeJS.ReadWriteStream): void => {
153
+ stream.pipe(process.stdout)
154
+ },
155
+ buildSuccess: (imageId: string, layers: string[]): void => {
156
+ console.log(`Successful build! ImageId: ${imageId}`)
157
+ },
158
+ buildFailure: (error: Error): void => {
159
+ console.error(`Error building container: ${error}`)
160
+ }
161
+ }
162
+
163
+ builder.buildDir('./my-dir', {}, hooks)
164
+ ```
165
+
166
+ #### Building a tar archive
167
+
168
+ ```typescript
169
+ import * as fs from 'fs'
170
+ import { build } from '@balena/compose';
171
+
172
+ const { Builder, BuildHooks } = build;
173
+
174
+ const builder = Builder.fromDockerOpts({ socketPath: '/var/run/docker.sock' })
175
+
176
+ const getHooks = (archive: string): BuildHooks => {
177
+ return {
178
+ buildSuccess: (imageId: string, layers: string[]): void => {
179
+ console.log(`Successful build! ImageId: ${imageId}`)
180
+ },
181
+ buildFailure: (error: Error): void => {
182
+ console.error(`Error building container: ${error}`)
183
+ },
184
+ buildStream: (stream: NodeJS.ReadWriteStream): void => {
185
+ // Create a stream from the tar archive.
186
+ // Note that this stream could be from a webservice,
187
+ // or any other source. The only requirement is that
188
+ // when consumed, it produces a valid tar archive
189
+ const tarStream = fs.createReadStream(archive)
190
+
191
+ // Send the tar stream to the docker daemon
192
+ tarStream.pipe(stream)
193
+
194
+ stream.pipe(process.stdout)
195
+ }
196
+ }
197
+ }
198
+
199
+ builder.createBuildStream({}, getHooks('my-archive.tar'))
200
+ ```
@@ -0,0 +1,18 @@
1
+ /// <reference types="node" />
2
+ import * as Bluebird from 'bluebird';
3
+ import * as Dockerode from 'dockerode';
4
+ import * as Plugin from './plugin';
5
+ export declare type ErrorHandler = (error: Error) => void;
6
+ export default class Builder {
7
+ private docker;
8
+ private constructor();
9
+ static fromDockerode(docker: Dockerode): Builder;
10
+ static fromDockerOpts(dockerOpts: Dockerode.DockerOptions): Builder;
11
+ createBuildStream(buildOpts: {
12
+ [key: string]: any;
13
+ }, hooks?: Plugin.BuildHooks, handler?: ErrorHandler): NodeJS.ReadWriteStream;
14
+ buildDir(dirPath: string, buildOpts: {
15
+ [key: string]: any;
16
+ }, hooks: Plugin.BuildHooks, handler?: ErrorHandler): Bluebird<NodeJS.ReadableStream>;
17
+ private callHook;
18
+ }
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const Bluebird = require("bluebird");
4
+ const Dockerode = require("dockerode");
5
+ const duplexify = require("duplexify");
6
+ const es = require("event-stream");
7
+ const JSONStream = require("JSONStream");
8
+ const _ = require("lodash");
9
+ const fs = require("mz/fs");
10
+ const path = require("path");
11
+ const tar = require("tar-stream");
12
+ const Utils = require("./utils");
13
+ const emptyHandler = () => undefined;
14
+ class Builder {
15
+ constructor(docker) {
16
+ this.docker = docker;
17
+ }
18
+ static fromDockerode(docker) {
19
+ return new Builder(docker);
20
+ }
21
+ static fromDockerOpts(dockerOpts) {
22
+ return new Builder(new Dockerode(_.merge(dockerOpts, { Promise: Bluebird })));
23
+ }
24
+ createBuildStream(buildOpts, hooks = {}, handler = emptyHandler) {
25
+ const layers = [];
26
+ const fromTags = [];
27
+ const inputStream = es.through();
28
+ const dup = duplexify();
29
+ dup.setWritable(inputStream);
30
+ let streamError;
31
+ const failBuild = _.once((err) => {
32
+ streamError = err;
33
+ dup.destroy(err);
34
+ return this.callHook(hooks, 'buildFailure', handler, err, layers, fromTags);
35
+ });
36
+ inputStream.on('error', failBuild);
37
+ dup.on('error', failBuild);
38
+ const buildPromise = Bluebird.try(() => this.docker.buildImage(inputStream, buildOpts)).then((daemonStream) => {
39
+ return new Bluebird((resolve, reject) => {
40
+ const outputStream = getDockerDaemonBuildOutputParserStream(daemonStream, layers, fromTags, reject);
41
+ outputStream.on('error', (error) => {
42
+ daemonStream.unpipe();
43
+ reject(error);
44
+ });
45
+ outputStream.on('end', () => streamError ? reject(streamError) : resolve());
46
+ dup.setReadable(outputStream);
47
+ });
48
+ });
49
+ Bluebird.all([
50
+ buildPromise,
51
+ this.callHook(hooks, 'buildStream', handler, dup),
52
+ ])
53
+ .then(() => {
54
+ if (!streamError) {
55
+ return this.callHook(hooks, 'buildSuccess', handler, _.last(layers), layers, fromTags);
56
+ }
57
+ })
58
+ .catch(failBuild);
59
+ return dup;
60
+ }
61
+ buildDir(dirPath, buildOpts, hooks, handler = emptyHandler) {
62
+ const pack = tar.pack();
63
+ return Utils.directoryToFiles(dirPath)
64
+ .map((file) => {
65
+ const relPath = path.relative(path.resolve(dirPath), file);
66
+ return Bluebird.all([relPath, fs.stat(file), fs.readFile(file)]);
67
+ })
68
+ .map((fileInfo) => {
69
+ return Bluebird.fromCallback((callback) => pack.entry({ name: fileInfo[0], size: fileInfo[1].size }, fileInfo[2], callback));
70
+ })
71
+ .then(() => {
72
+ pack.finalize();
73
+ const stream = this.createBuildStream(buildOpts, hooks, handler);
74
+ pack.pipe(stream);
75
+ return stream;
76
+ });
77
+ }
78
+ callHook(hooks, hook, handler, ...args) {
79
+ return Bluebird.try(() => {
80
+ const fn = hooks[hook];
81
+ if (_.isFunction(fn)) {
82
+ return fn.apply(null, args);
83
+ }
84
+ }).tapCatch((error) => {
85
+ if (_.isFunction(handler)) {
86
+ handler(error);
87
+ }
88
+ });
89
+ }
90
+ }
91
+ exports.default = Builder;
92
+ function getDockerDaemonBuildOutputParserStream(daemonStream, layers, fromImageTags, onError) {
93
+ const fromAliases = new Set();
94
+ return (daemonStream
95
+ .pipe(JSONStream.parse())
96
+ .pipe(es.through(function (data) {
97
+ if (data == null) {
98
+ return;
99
+ }
100
+ try {
101
+ if (data.error) {
102
+ throw new Error(data.error);
103
+ }
104
+ else {
105
+ const sha = Utils.extractLayer(data.stream);
106
+ if (sha !== undefined) {
107
+ layers.push(sha);
108
+ }
109
+ const fromTag = Utils.extractFromTag(data.stream);
110
+ if (fromTag !== undefined) {
111
+ if (!fromAliases.has(fromTag.repo)) {
112
+ fromImageTags.push(fromTag);
113
+ }
114
+ if (fromTag.alias) {
115
+ fromAliases.add(fromTag.alias);
116
+ }
117
+ }
118
+ this.emit('data', data.stream);
119
+ }
120
+ }
121
+ catch (error) {
122
+ daemonStream.unpipe();
123
+ onError(error);
124
+ }
125
+ })));
126
+ }
127
+ //# sourceMappingURL=builder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builder.js","sourceRoot":"","sources":["../../lib/build/builder.ts"],"names":[],"mappings":";;AAiBA,qCAAqC;AACrC,uCAAuC;AACvC,uCAAuC;AACvC,mCAAmC;AACnC,yCAAyC;AACzC,4BAA4B;AAC5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AAK,CAAC,CAAC;qBAC/B;iBACD;gBACD,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;aAC/B;SACD;QAAC,OAAO,KAAK,EAAE;YACf,YAAY,CAAC,MAAM,EAAE,CAAC;YACtB,OAAO,CAAC,KAAK,CAAC,CAAC;SACf;IACF,CAAC,CAAC,CACF,CACF,CAAC;AACH,CAAC"}
@@ -0,0 +1,4 @@
1
+ import Builder from './builder';
2
+ export { BuildHooks, FromTagInfo } from './plugin';
3
+ export { Builder };
4
+ export default Builder;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Builder = void 0;
4
+ const builder_1 = require("./builder");
5
+ exports.Builder = builder_1.default;
6
+ exports.default = builder_1.default;
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/build/index.ts"],"names":[],"mappings":";;;AAgBA,uCAAgC;AAGvB,kBAHF,iBAAO,CAGE;AAChB,kBAAe,iBAAO,CAAC"}
@@ -0,0 +1,11 @@
1
+ /// <reference types="node" />
2
+ export declare type ValidHook = 'buildStream' | 'buildSuccess' | 'buildFailure';
3
+ export interface FromTagInfo {
4
+ repo: string;
5
+ tag: string;
6
+ }
7
+ export interface BuildHooks {
8
+ buildStream?: (stream: NodeJS.ReadWriteStream) => void;
9
+ buildSuccess?: (imageId: string, layers: string[], fromTags: FromTagInfo[]) => void;
10
+ buildFailure?: (error: Error, layers: string[], fromTags: FromTagInfo[]) => void;
11
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../lib/build/plugin.ts"],"names":[],"mappings":""}
@@ -0,0 +1,8 @@
1
+ import * as Bluebird from 'bluebird';
2
+ import * as Plugin from './plugin';
3
+ export declare const extractLayer: (message: string) => string | undefined;
4
+ export declare const directoryToFiles: (dirPath: string) => Bluebird<string[]>;
5
+ export interface FromTagInfo extends Plugin.FromTagInfo {
6
+ alias?: string;
7
+ }
8
+ export declare const extractFromTag: (message: string) => FromTagInfo | undefined;