Compare commits

..

122 Commits

Author SHA1 Message Date
George Kalpakas
912911220a test(bazel): fix bazel-workspace schematics test
The test was cherry-picked from #27719 into 7.1.x, where entry module
path ended in `/main`, not `/main.dev`. It was changed to `/main.dev`
in #27277, which was not backported to 7.1.x.
2018-12-24 16:59:17 -08:00
Miško Hevery
395f9cd8d2 release: cut the v7.1.4 release 2018-12-18 15:32:47 -08:00
Ben Lesh
94e4589d30 docs(bazel): Update VSCode config (#27733)
What was there didn't work at all, and resulted in an error `Error processing "attach": Error: Both localRoot and remoteRoot must be specified`
PR Close #27733
2018-12-18 10:14:01 -08:00
Miško Hevery
f43e29b3d5 build: removed merge conflict markers from a bad merge 2018-12-18 10:09:46 -08:00
Christian Oliff
9ab35a1165 build: use https link to editorconfig.org in .editorconfig (#27664)
PR Close #27664
2018-12-18 09:30:09 -08:00
Sharath George M
d622558458 docs: Fixed typo (#27669)
PR Close #27669
2018-12-18 09:29:48 -08:00
Paul Gschwendtner
26501495fc build: load angular.js minified output in upgrade tests (#27711)
* We should try loading Angular.JS for the upgrade tests in their minfied output. There seems to be a lot flakiness in regards to loading `AngularJS` within Travis, and the `onerror` messages aren't really too helpful. In order to reduce the payload that will be passed through the Saucelabs tunnel, we should try to load the minfied output files.

PR Close #27711
2018-12-18 09:29:27 -08:00
Paul Gschwendtner
ad160257fa build: update gulp-clang-format dependency (#27712)
Currently rnning the gulp tasks to format code does not work because the `through2` version used by `gulp-clang-format` is very outdated and seems to cause exceptions like:

```
Error: no writecb in Transform class
    at afterTransform (C:\Users\Paul\projects\angular\node_modules\gulp-clang-format\node_modules\readable-stream\lib\_stream_transform.js:95:33)
    at TransformState.afterTransform (C:\Users\Paul\projects\angular\node_modules\gulp-clang-format\node_modules\readable-stream\lib\_stream_transform.js:79:12)
```

Updating to the latest version of `gulp-clang-format` that comes with 10cbb7f9bf, seems to fix this.

**Note**: This issue seems to depend on the platform because I didn't run into it on MacOS, or Linux. Though I got the failure on Windows. I didn't spend time investigating, but updating to the latest
version should just improve things.

PR Close #27712
2018-12-18 09:28:55 -08:00
Keen Yee Liau
b108e9a036 fix(bazel): devserver entry_module should have underscore name (#27719)
This commit fixes a bug whereby the path of the entry_module is not
consistent with the workspace name, which does not permit dashes
in the name.

PR Close #27719
2018-12-18 09:28:06 -08:00
Brandon Roberts
be08611d11 docs(forms): update API reference for validator directives (#26926)
PR Close #26926
2018-12-17 16:45:35 -08:00
Paul Gschwendtner
6b5c151b88 build: improve error message for upgrade test helper (#27706)
Currently whenever the upgrade test helper fails to load a given AngularJS version, the error that will be rejected is technically not an error because the `onerror` callback is not returning an error, but an "ErrorEvent".

Since that `ErrorEvent` is basically just rejected, browsers will print
the error as followed:

```
Failed: [object Event]
```

This is not helpful at all and also implies that there _might_ be more
information hidden within the `Event` instance. Unfortunately that's not
the case (at least on browsers we test against) and the logic to extract
the data from the event would be not worth the effort, we just return a
simple custom `Error` that won't imply that there is more information
hidden.

PR Close #27706
2018-12-17 16:45:19 -08:00
Keen Yee Liau
183f27894c fix(bazel): Set module_name and enable ng test (#27715)
Relative imports in Typescript files only work when module_name is
defined in ts_library (when run in Node.js).
See issue https://github.com/bazelbuild/rules_typescript/issues/360

With that fixed, `ng test` now works.

`ng build` requires `node_modules` to be available in the project
directory, so it's not usable yet. Running `yarn` in project directory
does not work because of postinstall version check.

PR Close #27715
2018-12-17 16:44:32 -08:00
Emilio Martinez
d1a14f6989 docs: remove misplaced code in Universal guide (#26865)
PR Close #26865
2018-12-17 09:35:36 -08:00
bmarkov
ce4cff60f0 docs: Add Smart UI to UI Components section in resources (#27515)
docs: add Smart UI to UI Components section in resources

PR Close #27515
2018-12-17 09:34:14 -08:00
cyraid
78bd3c70de docs(animations): rename animateChild() to animate() (#26184)
Renamed "animateChild()" to "animate()" in the comments/usage.
  The docs state to use animateChild() but uses animate() in the examples.
PR Close #26184
2018-12-14 15:27:37 -08:00
Ruslan Dzhabbarov
b22405767f docs(common): fix documentation for getLocaleCurrencyName (#27087)
PR Close #27087
2018-12-14 15:27:04 -08:00
levgaas
cd1e206cb3 fix(animations): do not truncate decimals for delay (#24455)
Do not truncate decimals for animation delay if specified in seconds

PR Close #24455
2018-12-14 15:20:23 -08:00
JoostK
453589f9fc fix(animations): mark actual descendant node as disabled (#26180)
PR Close #26180
2018-12-14 15:19:56 -08:00
Ingo Bürk
fa3af8b1e0 fix(common): KeyValuePipe should return empty array for empty objects (#27258)
This lets KeyValuePipe return an empty array (rather than undefined)
when the input is empty.

PR Close #27258
2018-12-14 15:19:14 -08:00
zackarychapple
c220328274 docs: adding ngAtlanta 2019 (#27522)
PR Close #27522
2018-12-14 15:18:55 -08:00
Igor Minar
0d8528b0df fix(bazel): emit full node stack traces when Angular compilation crashes (#27678)
The default 10 items are often not enough to debug deeply nested compilation operations.

This PR is based on @martinprobst's http://cl/225528216.

PR Close #27678
2018-12-14 14:58:21 -08:00
Christopher Dahm
9ac4a4d8a0 docs(common): update currencyPipe default digitsInfo values (#27417)
Change the docs to reflect the actual default values

Fixes #27414
PR Close #27417
2018-12-14 10:26:57 -08:00
cooljeffro
fe8c6b04ef docs(common): Fix typo in KeyValuePipe docs (#27580)
PR Close #27580
2018-12-14 10:21:47 -08:00
Alex Eagle
63d395cb7e build: restrict visibility of npm_package targets (#27611)
dependencies on these cause very long rebuilds which have to re-package angular.
Such tests belong in the integration/ folder

PR Close #27611
2018-12-14 10:20:41 -08:00
Paul Gschwendtner
f5e7208bea build: re-enable saucelabs non-verbose logging (#27657)
Previously the logging to TravisCI has been disabled because the `print-logs.sh` file printed the Sauce-Connect logfile output that is `verbose` by default. See [for example](https://travis-ci.org/angular/angular/jobs/250578973).

Since the default stdout/stderr of sauce-connect is pretty much concise and can alert us if we run into any issues (e.g. rate limit, outdated tunnel version), we should stop piping these to `/dev/null`.

PR Close #27657
2018-12-14 10:19:54 -08:00
Paul Gschwendtner
b3759fdc90 build: disable failing optional travis jobs (#27657)
* Disables the failing optional Travis jobs because those just acquire limited resources of Saucelabs and BrowserStack and cause API rate limit problems if the caretaker merges multiple PRs. The rate limit error will spread across multiple repositories because we use the same license in multiple Angular projects (e.g. Angular Material, angular.js etc.)

PR Close #27657
2018-12-14 10:19:54 -08:00
Paul Gschwendtner
ef056c5fb1 fix(bazel): ng_package writes unrelevant definitions to bazel out (#27519)
In order to keep the bazel bin directory as clean as possible, we should not write definition files that are not relevant to a `ng_package` to an undesired location in the bazel bin directory. This currently just happens because we only filter out external definition files while we also should filter out definitions that aren't just in the current package.

The `packager.ts` file currently tries to write these files to the package, but fails because those are not inside of the current package. So the logic to create a relative path for the file fails, and the definition will be copied to a location like:

```js
// Notice the double "bazel-out" here.
C:\Users\Paul\_bazel_Paul\kn4tsvyh\execroot\angular_material\bazel-out\x64_windows-fastbuild\bin\src\bazel-out\x64_windows-fastbuild\bin\src\cdk
```

[See logic that causes this](4f9374951d/packages/bazel/src/ng_package/packager.ts (L105-L124)) (nothing wrong with that logic because it assumes that only paths from within the package are passed to it)

PR Close #27519
2018-12-13 14:58:38 -08:00
Paul Gschwendtner
a808c7d150 build: ts-api-guardian tsconfig warning with bazel (#27583)
* Suppresses the warning from the Bazel TypeScript rules about overwritten options from the `tools/tsconfig.json` file. This is the only remaining warning that makes our Bazel build on Angular Material "dirty"

PR Close #27583
2018-12-13 11:01:48 -08:00
Keen Yee Liau
89ace1a2d9 fix(bazel): Load http_archive and rules_nodejs dependencies (#27609)
Bazel 0.20 requires loading http_archive explicitly.
rules_nodejs dependencies must now be installed explicity as well.

PR Close #27609
2018-12-13 11:01:31 -08:00
Igor Minar
52fd4a2d35 build: disable postinstall-patch.js log output (#27619)
currently we have no patches so the logging only adds noise to our dev environment.

PR Close #27619
2018-12-13 11:01:15 -08:00
Esteban Marin
8c32a2e8bc fix(docs-infra): fix top menu item clickable area (#27633)
the clickable region of the top menu item is expanded beyond the focused area, so the clickable area is spans the entire height of the navigation

fixes #27618

PR Close #27633
2018-12-13 11:00:34 -08:00
Greg Magolan
3ed1e842d6 fix(bazel): fix major/minor semver check between @angular/bazel npm packager version and angular bazel repo version (#27635)
PR Close #27635
2018-12-13 10:59:15 -08:00
Igor Minar
d53c421768 ci: remove packages/bazel from compiler-cli group (#27641)
it doesn't make sense require approvals from compiler-cli group for most @angular/bazel changes.

PR Close #27641
2018-12-13 10:58:59 -08:00
Igor Minar
01102cb235 ci: exclude unnedeed files and directories from angular-robot g3sync check (#27653)
We are overincluding files, all of these are not necessary in google3 and should not be synced
because it's only slowing us down.

Related CL: http://cl/225197013

PR Close #27653
2018-12-13 10:58:43 -08:00
Paul Gschwendtner
97eb85826f build: update to latest karma-sauce-launcher version (#27634)
PR Close #27634
2018-12-13 10:58:18 -08:00
Emmanuel DEMEY
1059789f9f docs: add Zenika trainings in resources.json (#27216)
PR Close #27216
2018-12-12 11:03:09 -08:00
Greg Magolan
0dba3ee359 build: update to tsickle 0.33.1 (#27612)
PR Close #27612
2018-12-12 11:02:43 -08:00
George Kalpakas
80818549fe build(docs-infra): upgrade cli command docs sources to 02524ab82 (#27556)
Relevant changes in [commit range](a176d127a...02524ab82):

**Modified**
- help/build.json
- help/serve.json
- help/test.json

PR Close #27556
2018-12-12 10:56:48 -08:00
Esteban Marin
348c94911c fix(docs-infra): fix top menu item clickable area (#27620)
the clickable region of the top menu item is reduced to the focused area, so no cursor pointer is shown outside the clickable area

fixes #27618

PR Close #27620
2018-12-12 10:55:28 -08:00
Greg Magolan
26c79efa4a build(bazel): fix postinstall-patches.js script run during yarn postinstall when running yarn_install (#27610)
PR Close #27610
2018-12-12 10:54:59 -08:00
Igor Minar
0b8db92a2b docs: update SAVED_REPLIES and CONTRIBUTING with new issue templates (#27608)
When we launched the new issue templates (.github/ISSUE_TEMPLATE/*), we forgot to update these
docs which got stale and needed a refresh.

PR Close #27608
2018-12-11 16:43:58 -08:00
Igor Minar
d0e6eeb51e build: bump @bazel/ibazel to 0.9.0 (#27601)
This should fix the problem with ibazel crashing on bzl/BUILD file syntax errors. bazelbuild/bazel-watcher/issues/194

https://github.com/bazelbuild/bazel-watcher/blob/master/CHANGELOG.md#v090-2018-12-07

PR Close #27601
2018-12-11 16:31:20 -08:00
Keen Yee Liau
93078e3709 fix(bazel): Read latest versions from latest-versions.ts & use semver check (#27591)
When @angular/bazel is installed, a postinstall script is run to make sure that
the npm version is *exactly* the same as the Angular repository install by
Bazel. This check is overly stringent. Instead, it should enforce that the
version satisfies the range check instead. This is consistent with the range
defined in angular-cli/packages/schematics/angular/utility/latest-versions.ts.

This commit also fixes the Bazel workspace to use the same Rxjs version if it's
already installed.

PR Close #27591
2018-12-11 16:30:52 -08:00
Lucas
29ab72980c docs: fix ngModel typo in form validation guide (#27574)
Fix typo

PR Close #27574
2018-12-11 16:22:58 -08:00
Alex Rickabaugh
5452889aa6 release: cut the v7.1.3 release 2018-12-11 13:31:19 -08:00
Michał Jawulski
590b84fc1d docs: update npm scripts to support angular 7 (#27334)
PR Close #27334
2018-12-11 11:25:37 -08:00
Igor Minar
b6deb00b97 build: exclude ivy commit messages from the release notes (#27532)
there is still too much churn to make this info useful in the release notes, advanced
developers can use git log to find out what's going on with ivy.

PR Close #27532
2018-12-11 11:22:54 -08:00
Alex Eagle
01114dc10a build: fix type-check errors introduced during rules_ts 0.21 (#27586) (#27590)
PR Close #27586

PR Close #27590
2018-12-11 11:22:08 -08:00
Alex Eagle
7b1f3527be build: update rules_typescript (#27586) (#27590)
This release of rules_typescript fixes a critical bug: typescript code
was not checked at all, including type-checking, tsetse, and strict deps

fixes #27569

PR Close #27586

PR Close #27590
2018-12-11 11:22:08 -08:00
Isaac Sunkes
575ef9f5a4 docs: add webucator to resources (#26895)
Added Angular Training by Webucator to Workshops & Onsite Training section of resources.
PR Close #26895
2018-12-10 14:20:03 -08:00
Igor Minar
11996cd1c4 docs: remove AngularDart from the version picker (#27550)
At this point it's only confusing people.

PR Close #27550
2018-12-10 10:29:40 -08:00
Alex Eagle
8fc763d58f build: update to Bazel 0.20 (#27394)
refactor Bazel RBE configs

PR Close #27394
2018-12-07 14:29:03 -08:00
Igor Minar
7a5136bcc1 build: update source-map-support to get rid of Node's DeprecationWarning (#27538)
Removes the following when bazel runs any of our jasmine_node_tests:

(node:85494) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from()
 methods instead.

I was able to find the source of the warning by running the target with the following tags:

```
bazel test packages/language-service/... --test_arg=--node_options=--throw-deprecation
```

PR Close #27538
2018-12-07 11:53:21 -08:00
Paul Gschwendtner
a9f39a4fdf fix(bazel): tsickle dependency not working with typescript 3.1.x (#27402)
`@angular/bazel` currently requires TypeScript 3.1.x as a peer dependency, but comes with `tsickle` as dependency. The current version of `tsickle` that is specified by `@angular/bazel` does not support TypeScript 3.1.x (which is a peer dependency) and therefore we need to make sure that `tsickle` works with the required TypeScript versions.

This change updates `tsickle` to the latest version that comes with b10fb6de0a in order to work with TypeScript 3.1.x.

PR Close #27402
2018-12-07 10:51:37 -08:00
Christopher Dahm
35d0284f45 docs: file new issue needs to have opener choose type from template (#27400)
The submission guidelines for submitting an issue directs issue reporters to a pre-filled unformatted issue form. Reporters need directed to choose from the issue templates.

Fixes #27398
PR Close #27400
2018-12-07 09:27:52 -08:00
Alex Eagle
74346e987a style: run latest buildifier binary (#27489)
PR Close #27489
2018-12-07 09:27:33 -08:00
Alex Eagle
f221e9010e ci: use buildifier binary release (#27489)
Switch from Skylint to buildifier --lint - this is required for the Bazel 0.20 upgrade since Bazel no longer lets us use the embedded JDK to build and run Java programs, and Skylint is a Java program

PR Close #27489
2018-12-07 09:27:33 -08:00
Olivier Combe
90c273a788 ci: update ngbot config to add merge linked labels (#27512)
PR Close #27512
2018-12-07 09:25:45 -08:00
Igor Minar
11d2a8cc81 release: cut the v7.1.2 release 2018-12-06 15:08:57 -08:00
Minko Gechev
ad106abece build: introduce remote bazel caching (#27358)
This PR introduces:

1. Google Cloud Store bucket which contains build artifacts
2. Documentation on how to enable remote caching in development

Each team member should download a service key. More convenient ways of authentication would be more obscure and prevent us from doing identity tracking of the produced artifacts.

PR Close #27358
2018-12-06 11:25:03 -08:00
Paul Gschwendtner
84f2928c8c fix(compiler-cli): ngtsc shim files not being generated on case-insensitive platforms (#27466)
Common insensitive platforms are `win32/win64` (see:
[here](3e4c5c95ab/src/compiler/sys.ts (L681-L682)))

Currently when running `bazel build packages/core --define=compile=aot`, the `compiler-cli` will throw because it cannot find the `index.ngfactory.ts` file in the compiler host. This is because the shim host wrapper is not properly generating the requested `ngfactory` file.

This happens because we call `getCanonicalFileName` that returns a path that is different to the actual program filenames that are used to construct a map of generated files. Since the generators always use the paths which are not "canonical" and pases them internally like that, we can just stop manually calling `getCanonicalFileName`.

PR Close #27466
2018-12-06 09:24:53 -08:00
Igor Minar
610472bf3b Revert "fix(router): change processing url tree children condition (#26243)" (#27516)
This reverts commit ccc77ca441ae11d2b516806b4b1c1b7b3062b896.

Breaks Pantheon see cl/224256517.

PR Close #27516
2018-12-06 09:17:21 -08:00
Igor Minar
7bed896f11 Revert "fix(router): process empty path segment when preceding a named outlet (#26243)" (#27516)
This reverts commit 20cef5078dc86bc5d9831fafec076d912ad3521f.

Breaks Pantheon see cl/224256517.

PR Close #27516
2018-12-06 09:17:21 -08:00
Igor Minar
d7c72fced7 build: remove obsolete gulp build task (#27386)
PR Close #27386
2018-12-05 20:55:33 -08:00
Igor Minar
3ca5de7efd ci: don't run node unit tests on travis (#27386)
we run all these tests on CircleCI with bazel.

PR Close #27386
2018-12-05 20:55:33 -08:00
Igor Minar
485e2a147a test(benchpress): make most of the tests run under bazel (#27386)
PR Close #27386
2018-12-05 20:55:33 -08:00
Igor Minar
b24f1984f3 ci: remove validate-commit-message tests from travis (#27386)
we alredy run them via bazel.

I also removed a bunch of obsolete files that bazel doesn't need.

PR Close #27386
2018-12-05 20:55:33 -08:00
Igor Minar
f8846ef14e docs: remove obsolete packages/examples/web_workers/ts/.gitkeep (#27386)
PR Close #27386
2018-12-05 20:55:33 -08:00
Igor Minar
9a93259b64 test: correct bazel visibility for @angular/private/testing (#27386)
we don't want anyone else to depened on this stuff.

PR Close #27386
2018-12-05 20:55:33 -08:00
Igor Minar
194f1f084f test(service-worker): run the remaining service-worker tests under bazel (#27386)
PR Close #27386
2018-12-05 20:55:33 -08:00
Igor Minar
fba9fa2302 test(common): run @angular/common/http/testing tests under bazel (#27386)
PR Close #27386
2018-12-05 20:55:32 -08:00
Igor Minar
820e2027e0 ci: don't run router tests on travis (#27386)
we already run them on circle under bazel

PR Close #27386
2018-12-05 20:55:32 -08:00
Kara Erickson
0508143128 build: add kara to more approval lists (#27493)
PR Close #27493
2018-12-05 14:41:50 -08:00
George Kalpakas
a97fbfd823 refactor(docs-infra): remove unused custom element (#27250)
PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
e552cadc90 fix(docs-infra): do not use an Angular element in hard-coded FETCH_ERROR document (#27250)
The `FETCH_ERROR` document is used when we are unable to retrieve a
document (except for 404 errors), which includes when there is no
internet connection. Using the `<current-location>` element in the
document's template to show the path of the page we failed to retrieve
assumes that the element's bundle is available (e.g. cached by the SW)
or can be fetched from the server.

When none of these conditions is met, the `DocViewer` is unable to
prepare the document and fails, never showing the `FETCH_ERROR` page to
the user.

Furthermore, the path we are looking to retrieve via
`<current-location>` is essentially the document ID, which we already
have. Thus, loading and instantiating a whole component just for that is
overkill.

This commit addresses both issues by getting rid of the
`<current-location>` component and directly embedding the document ID
into the `FETCH_ERROR` content.

PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
35ab809326 fix(docs-infra): fix sidenav positioning when notification is shown (#27250)
_Before:_
![sidenav-scrollbar-before](https://user-images.githubusercontent.com/8604205/49089078-62519d00-f263-11e8-8369-f39e73dcc239.png)

_After:_
![sidenav-scrollbar-after](https://user-images.githubusercontent.com/8604205/49089077-62519d00-f263-11e8-8a94-0c34044c4ba1.png)

PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
919ef66a7c build(docs-infra): remove dependency on FontAwesome (#27250)
We were only using two FontAwesome icons (`link` and `twitter`). The
twitter icon is already available as an SVG (used in the topbar) and a
similar link icon is available via 'Material Icons', which we are
already brining in.

This commit removes the dependency on FontAwesome and uses the available
icons instead.

_Before:_
![contributor-info-before](https://user-images.githubusercontent.com/8604205/49089076-61b90680-f263-11e8-8c5f-c52d332e6e64.png)

_After:_
![contributor-info-after](https://user-images.githubusercontent.com/8604205/49089075-61b90680-f263-11e8-9785-b8df15aaacd3.png)

PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
a37c65827a fix(docs-infra): correctly cache footer image by the SW (#27250)
When using relative paths for CSS resources (such as background images),
`@angular/cli` will move them to the root `dist/` directory (and update
the paths in CSS accordingly). This results in the SW being unable to
cache the resource, because it is not where it expects it to be.

This commit fixes this issue for the footer background image, by using
an absolute path for the URL. (It also removes an unused style that
would have been affected by the same issue.)

PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
1371cf6d33 fix(docs-infra): ensure material icons are cached for offline access (#27250)
In order for 'Material Icons' to work offline, their `.woff2` file needs
to have been cached by the SW. This file is not requested by the
browser, until an element needs to use the icon font.

In order to speed up the initial page load and avoid FOUC, we use
inlined SVGs for all icons in the app shell. As a result, the `.woff2`
file may not be requested, when a user visits angular.io. If they go
offline before visiting a page that does actually use 'Material Icons',
then such icons will not work correctly (e.g. the `error_outline` icon
used in the error page for failed requests due to network
unanvailability).

This commit fixes this, by adding a non-visible element that needs the
'Material Icons' font on the main component. Thids ensures that the
`.woff2` file will always be loaded, even if the page does not use any
material icons.

(Note: The element is inserted lazily to avoid affecting the initial
rendering.)

PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
e9655720f8 fix(docs-infra): remove hard-coded color from inlined SVG icons (#27250)
This allows the icons to inherit the color of their HTMLElement parent.

PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
8512e34521 fix(docs-infra): inline SVG icons used in page load sensitive UI (#27250)
These icons are part of the app shell and used on every load (on both
desktop and mobile). Inlining them ensures they are rendered asap.

PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
21c9cfff5a fix(docs-infra): always fetch Roboto font (#27250)
Previously, we did not load the Roboto font, instead relying on the user
to have it available on their system and falling back to different fonts
otherwise. This resulted in the page being styled slightly differently
for those people that didn't have the font installed locally.

PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
e902f5ee6a fix(docs-infra): do not create an anchor for the file-not-found header (#27250)
PR Close #27250
2018-12-05 13:26:28 -08:00
George Kalpakas
013a241b94 refactor(docs-infra): move minified lunr script to the generated directory (#27250)
PR Close #27250
2018-12-05 13:26:27 -08:00
George Kalpakas
0d0bc1f725 build: error when files specified in payload size limits are missing (#27250)
PR Close #27250
2018-12-05 13:26:27 -08:00
Filipe Silva
a655d288ca ci: test ts-api-guardian on windows (#27205)
PR Close #27205
2018-12-05 12:49:55 -08:00
Igor Minar
e55088a364 build: to fsevents@2.0.1 (#27469)
the old version was failing to compile on MacOS Mojave 10.14.1.

PR Close #27469
2018-12-05 10:48:20 -08:00
Greg Magolan
2e41631026 build(bazel): replace yarn_install(name = "npm") with @npm local_reporsitory() to speed up build (#27469)
PR Close #27469
2018-12-05 10:48:20 -08:00
miginmrs
2bc85fb77e fix(router): process empty path segment when preceding a named outlet (#26243)
PR Close #10726

PR Close #26243
2018-12-05 10:39:30 -08:00
miginmrs
8167bfc87c fix(router): change processing url tree children condition (#26243)
stop adding next path of pathless activated route to the url

PR Close #26224

PR Close #26243
2018-12-05 10:39:30 -08:00
Alex Eagle
711ef2ded4 build: update to newest ibazel (#27441)
this supports the --define flag which we use for Ivy development

PR Close #27441
2018-12-04 20:00:06 -08:00
George Kalpakas
5c57920dbb fix(docs-infra): log the successful creation of previews (#27436)
This can help with debugging issues, e.g. with the communication between
the preview server and CI, as it gives a better idea of exactly when was
the preview made available and how long it took.

PR Close #27436
2018-12-04 19:59:25 -08:00
Paul Gschwendtner
9b4d95974a fix(bazel): do not throw if ts compile action does not create esm5 outputs (#27401)
In some applications, developers define a `ts_library` that just consists of `d.ts` files (e.g. to type `module.id`; see: https://github.com/angular/material2/blob/master/src/module-typings.d.ts), and expect the `esm5.bzl` file to not throw an error like:

```
  target.typescript.replay_params.outputs
struct' object has no attribute 'outputs'
```

The "replay_parameters" property will exist in that case, but is set to "None" because there is no action that should be replayed in favor of producing ES5 outputs. See: https://github.com/bazelbuild/rules_typescript/pull/326. Notice that this right now breaks similarly because an empty `struct()` is returned that does not have a property called `outputs`. [#326](https://github.com/bazelbuild/rules_typescript/pull/326) fixes that by being explicit that there is no _action_ at all.

PR Close #27401
2018-12-04 19:58:36 -08:00
Paul Gschwendtner
8087b6b611 fix(compiler-cli): flatModuleIndex files not generated on windows with multiple input files (#27200)
* Currently when building a `ng_module` with Bazel and having the flat module id option set, the flat module files are not being generated because `@angular/compiler-cli` does not properly determine the entry-point file.

Note that this logic is not necessarily specific to Bazel and the same problem can happen without Bazel if multiple TypeScript input files are specified while the `flatModuleIndex` option has been enabled.

PR Close #27200
2018-12-04 14:01:25 -08:00
Paul Gschwendtner
1ca292392b fix(bazel): ng_package cannot be run multiple times without clean (#27200)
Currently when building the `ng_package` multiple times, the old `ng_package` output will be copied over to the new `ng_package` content. Resulting in packages like `src/cdk/npm_package/npm_package/npm_package/AND_MORE`.

This happens because currently all TypeScript definition files are resolved from within the `binDir`. This is just wrong because it could then take up the `d.ts` files from the previous `ng_package` output. All typescript definitions that belong to the target package, should be resolved through Bazel and copied based on that computation.

Also fixes that `esm` files aren't written to the `ng_package` on Windows. This is because we try to flatten paths using the `path.delimiter` while the path is always using Posix delimiters (causing the paths to be incorrect)

PR Close #27200
2018-12-04 14:01:25 -08:00
Paul Gschwendtner
079c4b3482 fix(bazel): do not throw error when writing tsickle externs (#27200)
* Currently when building the ES5 and ES2015 output, `ngc_wrapped` will fail because it tries to write the `fs.openSync` the tsickle output file at the same time. This causes a runtime exception in Windows and can be fixed by just writing the externs for ES5 mode to the proper ES5 "output root".

PR Close #27200
2018-12-04 14:01:25 -08:00
Paul Gschwendtner
e476c38dee fix(bazel): ng_package not generating UMD bundles on windows (#27200)
* Fixes that `ng_package` does not work generate UMD bundles on Windows because the `esm5/` files are not written to the output directory. This is because `rootDirs` and `rootDir` are posix paths and cause invalid relative paths when mixed with Windows backslash paths.

PR Close #27200
2018-12-04 14:01:25 -08:00
George Kalpakas
8799ea7ea0 ci(docs-infra): manually trigger the preview server webhook (#27458)
With this change, we no longer depend on CircleCI to trigger the webhook
(which it sometimes does with considerable delay or not at all).

This has the added benefit that other jobs will not unnecessarily
trigger webhooks and spam the preview server logs. It is only the
`aio_preview` job's webhook that we care about.

Related to #27352.

PR Close #27458
2018-12-04 13:59:54 -08:00
volshibenik
03787924da docs: fix typo in toh-pt6.md (#27403)
PR Close #27403
2018-12-03 08:24:19 -08:00
Christopher Dahm
1022db1c8c test(common): add PercentPipe round and trim tests (#27365)
Add tests to cover the percent's decimal to be rounded and trimmed.
PR Close #27365
2018-12-03 08:22:25 -08:00
Christopher Dahm
560cb99f55 docs(common): update PercentPipe default maxFractionDigits value (#27365)
Change the docs to reflect the actual default value

Fixes #27079
PR Close #27365
2018-12-03 08:22:25 -08:00
Alex Eagle
5acfdee3ca build: only stamp version info when releasing (#27362)
Also build releases into a dedicated output_base so you can't
accidentally publish with outdated version stamp.

Bump the version of rules_nodejs so we don't need to create the
symlink_prefixes for the .publish command to work.

PR Close #27362
2018-11-30 16:08:23 -08:00
Igor Minar
fc2c23ef4b fix(bazel): ng_package should correctly map to source maps in secondary entry-points (#27313)
This fixes the issue with broken source maps for @angular/common/http/testing.

Fixes #25510

PR Close #27313
2018-11-30 13:40:01 -08:00
Greg Magolan
1ddc34cbc5 build(bazel): update handling of rules_nodejs transitive deps (#27264)
BREAKING CHANGES:

Bazel users: rules_angular_dependencies() will no longer install transitive dependencies of build_bazel_rules_nodejs and build_bazel_rules_typescript. User WORKSPACE files will now need to install rules_nodejs and rules_typescript transitive deps directly:

```
load("@build_bazel_rules_typescript//:package.bzl", "rules_typescript_dependencies")
rules_typescript_dependencies()

load("@build_bazel_rules_nodejs//:package.bzl", "rules_nodejs_dependencies")
rules_nodejs_dependencies()
```

PR Close #27264
2018-11-30 13:35:52 -08:00
dennisameling
184d63d91d docs: fix dynamic-component-loader example for Adblock Plus + EasyList (#27212)
Reported issue in #18138 is due to EasyList being selected in ABP. This commit fixes both the image at the bottom of the Dynamic Component Loader example, and the Stackblitz demo.

Fixes #18138

PR Close #27212
2018-11-30 13:35:38 -08:00
Igor Minar
236ac060b0 fix(platform-server): add @angular/http to the list of peerDependencies (#27307)
Fixes #26154

PR Close #27307
2018-11-30 10:02:44 -08:00
ryo.s
2cce8d4ebc docs: fix typo (#27294)
PR Close #27294
2018-11-29 22:15:28 -08:00
Brandon Roberts
a149c3a8db docs(forms): update API reference for common APIs and template-driven directives (#27033)
PR Close #27033
2018-11-29 21:33:08 -08:00
seunggabi
013c0ae2e1 style: change style css syntax (#27253)
PR Close #27253
2018-11-29 21:26:53 -08:00
Miško Hevery
c8aebaeb76 build: Replace iteration over depsets with an explicit .to_list() call. (#27336)
PR Close #27336
2018-11-29 21:22:39 -08:00
Kara Erickson
56254b53bd build: add kara to approvers for packages needing ivy TestBed updates (#27337)
PR Close #27337
2018-11-29 21:22:24 -08:00
Minko Gechev
5d0e1147df docs: move Minko to Angular (#27339)
Joined the team at Google about a month ago 

PR Close #27339
2018-11-29 21:21:54 -08:00
Grant Timmerman
a0f239fc71 docs: move past events on events page (#27342)
Moves events that have already happened to the list of past events.

PR Close #27342
2018-11-29 21:21:24 -08:00
Jacob Foshee
88032eb302 docs: Minor: insert missing space (#27213)
PR Close #27213
2018-11-28 11:41:21 -08:00
Amadou Sall
827e223edb docs: replace ChromeNoSandbox by ChromeHeadlessCI (#27304)
the custom launcher name should be named ChromeHeadlessCI instead of ChromeNoSandbox.
PR Close #27304
2018-11-28 11:40:03 -08:00
Filipe Silva
14d75d6971 docs: add instructions to diagnose slow Bazel builds (#27324)
PR Close #27324
2018-11-28 11:39:38 -08:00
Jason Aden
8282e15c2b release: cut the v7.1.1 release 2018-11-28 10:09:48 -08:00
Alex Rickabaugh
bdf5f3e499 fix(core): export a value for InjectFlags (#27279)
A recent commit (probably 2c7386c) has changed the import graph of the
DI types in core, and somehow results in the ngc compiler deciding to
re-export core DI types from application factories which tangentially
use inject(). This is not really surprising; ngc's import graph can be
very unstable.

However, this results in a re-export of InjectFlags surviving JS
compilation. InjectFlags was a const enum, akin to an interface in TS,
with no runtime repesentation. This causes a warning to be emitted by
Webpack when it sees the re-export of InjectFlags.

This commit avoids the issue by removing 'const' from the declaration
of InjectFlags, causing it to have a runtime value. This is a temporary
fix. The real fix will be for ngc to no longer write exports of const
enums.

Testing strategy: manually verified. Due to the problem only manifesting
when recompiling after a change and then running Webpack, there is no
existing framework via which this could be easily tested with an
integration test. Additionally, the potential for this issue is gone in
Ivy, so this solution is only temporarily needed.

Fixes #27251.

PR Close #27279
2018-11-27 13:40:39 -08:00
George Kalpakas
a71038b5fa build(docs-infra): upgrade npm-run-all to latest version for security (#27274)
Earlier versions may transitively depend on a malicious version of
`flatmap-stream` (see dominictarr/event-stream#116).

The `aio-builds-setup/` had an older version of `event-stream` (3.3.4),
which did not depend on `flatmap-stream`, but upgraded it anyway.

PR Close #27274
2018-11-27 13:38:36 -08:00
onlyflix
d735160a11 fix(docs-infra): don't call setSearch when not clicking in the searchBox and no searchResults (#26590)
Fix to call locationService.setSearch less often to avoid unnecessary
downloading of favicons

Fixes #26544

PR Close #26590
2018-11-27 13:38:28 -08:00
Brandon Roberts
498c4c32b1 docs: add forms terms to glossary (#27075)
PR Close #27075
2018-11-27 13:38:20 -08:00
Paul Gschwendtner
b9c7da6503 build: fix source-map warnings for ts-api-guardian (#27098)
* Fixes that running `ts-api-guardian` targets always causes source map warnings to appear.

PR Close #27098
2018-11-27 13:38:13 -08:00
8436 changed files with 236262 additions and 780259 deletions

View File

@ -1,97 +1,3 @@
# Bazel does not yet support wildcards or other .gitignore semantics for
# .bazelignore. Two issues for this feature request are outstanding:
# https://github.com/bazelbuild/bazel/issues/7093
# https://github.com/bazelbuild/bazel/issues/8106
.git
node_modules node_modules
dist dist
aio/content
aio/node_modules aio/node_modules
aio/tools/examples/shared/node_modules
packages/bazel/node_modules
integration/bazel/bazel-bazel
integration/bazel/bazel-bin
integration/bazel/bazel-out
integration/bazel/bazel-testlogs
integration/bazel-schematics/demo
# All integration test node_modules folders
integration/bazel/node_modules
integration/bazel-schematics/node_modules
integration/cli-hello-world/node_modules
integration/cli-hello-world-ivy-compat/node_modules
integration/cli-hello-world-ivy-i18n/node_modules
integration/cli-hello-world-ivy-minimal/node_modules
integration/cli-hello-world-lazy/node_modules
integration/cli-hello-world-lazy-rollup/node_modules
integration/dynamic-compiler/node_modules
integration/hello_world__closure/node_modules
integration/hello_world__systemjs_umd/node_modules
integration/i18n/node_modules
integration/injectable-def/node_modules
integration/ivy-i18n/node_modules
integration/language_service_plugin/node_modules
integration/ng_elements/node_modules
integration/ng_elements_schematics/node_modules
integration/ng_update/node_modules
integration/ng_update_migrations/node_modules
integration/ngcc/node_modules
integration/platform-server/node_modules
integration/service-worker-schema/node_modules
integration/side-effects/node_modules
integration/terser/node_modules
integration/typings_test_ts36/node_modules
integration/typings_test_ts37/node_modules
# All integration test .yarn_local_cache folders
integration/bazel/.yarn_local_cache
integration/bazel-schematics/.yarn_local_cache
integration/cli-hello-world/.yarn_local_cache
integration/cli-hello-world-ivy-compat/.yarn_local_cache
integration/cli-hello-world-ivy-i18n/.yarn_local_cache
integration/cli-hello-world-ivy-minimal/.yarn_local_cache
integration/cli-hello-world-lazy/.yarn_local_cache
integration/cli-hello-world-lazy-rollup/.yarn_local_cache
integration/dynamic-compiler/.yarn_local_cache
integration/hello_world__closure/.yarn_local_cache
integration/hello_world__systemjs_umd/.yarn_local_cache
integration/i18n/.yarn_local_cache
integration/injectable-def/.yarn_local_cache
integration/ivy-i18n/.yarn_local_cache
integration/language_service_plugin/.yarn_local_cache
integration/ng_elements/.yarn_local_cache
integration/ng_elements_schematics/.yarn_local_cache
integration/ng_update/.yarn_local_cache
integration/ng_update_migrations/.yarn_local_cache
integration/ngcc/.yarn_local_cache
integration/platform-server/.yarn_local_cache
integration/service-worker-schema/.yarn_local_cache
integration/side-effects/.yarn_local_cache
integration/terser/.yarn_local_cache
integration/typings_test_ts36/.yarn_local_cache
integration/typings_test_ts37/.yarn_local_cache
# All integration test NPM_PACKAGE_MANIFEST.json folders
integration/bazel/NPM_PACKAGE_MANIFEST.json
integration/bazel-schematics/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-ivy-compat/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-ivy-i18n/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-ivy-minimal/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-lazy/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-lazy-rollup/NPM_PACKAGE_MANIFEST.json
integration/dynamic-compiler/NPM_PACKAGE_MANIFEST.json
integration/hello_world__closure/NPM_PACKAGE_MANIFEST.json
integration/hello_world__systemjs_umd/NPM_PACKAGE_MANIFEST.json
integration/i18n/NPM_PACKAGE_MANIFEST.json
integration/injectable-def/NPM_PACKAGE_MANIFEST.json
integration/ivy-i18n/NPM_PACKAGE_MANIFEST.json
integration/language_service_plugin/NPM_PACKAGE_MANIFEST.json
integration/ng_elements/NPM_PACKAGE_MANIFEST.json
integration/ng_elements_schematics/NPM_PACKAGE_MANIFEST.json
integration/ng_update/NPM_PACKAGE_MANIFEST.json
integration/ng_update_migrations/NPM_PACKAGE_MANIFEST.json
integration/ngcc/NPM_PACKAGE_MANIFEST.json
integration/platform-server/NPM_PACKAGE_MANIFEST.json
integration/service-worker-schema/NPM_PACKAGE_MANIFEST.json
integration/side-effects/NPM_PACKAGE_MANIFEST.json
integration/terser/NPM_PACKAGE_MANIFEST.json
integration/typings_test_ts36/NPM_PACKAGE_MANIFEST.json
integration/typings_test_ts37/NPM_PACKAGE_MANIFEST.json

137
.bazelrc
View File

@ -1,3 +1,20 @@
# Load any settings specific to the current user
try-import .bazelrc.user
################################
# Settings for Angular team members only
################################
# To enable this feature check the "Remote caching" section in docs/BAZEL.md.
build:angular-team --remote_http_cache=https://storage.googleapis.com/angular-team-cache
###############################
# Typescript / Angular / Sass #
###############################
# Make compilation fast, by keeping a few copies of the compilers
# running as daemons, and cache SourceFile AST's to reduce parse time.
build --strategy=TypeScriptCompile=worker
build --strategy=AngularTemplateCompile=worker
# Enable debugging tests with --config=debug # Enable debugging tests with --config=debug
test:debug --test_arg=--node_options=--inspect-brk --test_output=streamed --test_strategy=exclusive --test_timeout=9999 --nocache_test_results test:debug --test_arg=--node_options=--inspect-brk --test_output=streamed --test_strategy=exclusive --test_timeout=9999 --nocache_test_results
@ -5,39 +22,20 @@ test:debug --test_arg=--node_options=--inspect-brk --test_output=streamed --test
# Filesystem interactions # # Filesystem interactions #
############################### ###############################
# Create symlinks in the project: # Don't create symlinks like bazel-out in the project.
# - dist/bin for outputs # These cause VSCode to traverse a massive tree, opening file handles and
# - dist/testlogs, dist/genfiles
# - bazel-out
# NB: bazel-out should be excluded from the editor configuration.
# The checked-in /.vscode/settings.json does this for VSCode.
# Other editors may require manual config to ignore this directory.
# In the past, we say a problem where VSCode traversed a massive tree, opening file handles and
# eventually a surprising failure with auto-discovery of the C++ toolchain in # eventually a surprising failure with auto-discovery of the C++ toolchain in
# MacOS High Sierra. # MacOS High Sierra.
# See https://github.com/bazelbuild/bazel/issues/4603 # See https://github.com/bazelbuild/bazel/issues/4603
build --symlink_prefix=dist/ build --symlink_prefix=/
# Performance: avoid stat'ing input files
build --watchfs
# Turn off legacy external runfiles # Turn off legacy external runfiles
build --nolegacy_external_runfiles
run --nolegacy_external_runfiles run --nolegacy_external_runfiles
test --nolegacy_external_runfiles test --nolegacy_external_runfiles
# Turn on --incompatible_strict_action_env which was on by default
# in Bazel 0.21.0 but turned off again in 0.22.0. Follow
# https://github.com/bazelbuild/bazel/issues/7026 for more details.
# This flag is needed to so that the bazel cache is not invalidated
# when running bazel via `yarn bazel`.
# See https://github.com/angular/angular/issues/27514.
build --incompatible_strict_action_env
run --incompatible_strict_action_env
test --incompatible_strict_action_env
# Do not build runfile trees by default. If an execution strategy relies on runfile
# symlink teee, the tree is created on-demand. See: https://github.com/bazelbuild/bazel/issues/6627
# and https://github.com/bazelbuild/bazel/commit/03246077f948f2790a83520e7dccc2625650e6df
build --nobuild_runfile_links
############################### ###############################
# Release support # # Release support #
# Turn on these settings with # # Turn on these settings with #
@ -45,10 +43,7 @@ build --nobuild_runfile_links
############################### ###############################
# Releases should always be stamped with version control info # Releases should always be stamped with version control info
# This command assumes node on the path and is a workaround for build:release --workspace_status_command=./tools/bazel_stamp_vars.sh
# https://github.com/bazelbuild/bazel/issues/4802
build:release --workspace_status_command="yarn -s ng-dev release build-env-stamp"
build:release --stamp
############################### ###############################
# Output # # Output #
@ -61,86 +56,46 @@ query --output=label_kind
# By default, failing tests don't print any output, it goes to the log file # By default, failing tests don't print any output, it goes to the log file
test --test_output=errors test --test_output=errors
# Show which actions are run under workers,
# and print all the actions running in parallel.
# Helps to demonstrate that bazel uses all the cores on the machine.
build --experimental_ui
test --experimental_ui
################################ ################################
# Settings for CircleCI # # Settings for CircleCI #
################################ ################################
# Bazel flags for CircleCI are in /.circleci/bazel.linux.rc and /.circleci/bazel.windows.rc # Bazel flags for CircleCI are in /.circleci/bazel.rc
##################################
# Settings for integration tests #
##################################
# Trick bazel into treating BUILD files under integration/bazel as being regular files
# This lets us glob() up all the files inside this integration test to make them inputs to tests
# (Note, we cannot use common --deleted_packages because the bazel version command doesn't support it)
build --deleted_packages=integration/bazel,integration/bazel/src,integration/bazel/src/hello-world,integration/bazel/test,integration/bazel/test/e2e
query --deleted_packages=integration/bazel,integration/bazel/src,integration/bazel/src/hello-world,integration/bazel/test,integration/bazel/test/e2e
################################ ################################
# Temporary Settings for Ivy # # Temporary Settings for Ivy #
################################ ################################
# To determine if the compiler used should be Ivy instead of ViewEngine, one can use `--config=ivy` # to determine if the compiler used should be Ivy or ViewEngine one can use `--define=compile=local` on
# on any bazel target. This is a temporary flag until codebase is permanently switched to Ivy. # any bazel target. This is a temporary flag until codebase is permanently switched to Ivy.
build --define=angular_ivy_enabled=False build --define=compile=legacy
build:view-engine --define=angular_ivy_enabled=False ###############################
build:ivy --define=angular_ivy_enabled=True # Remote Build Execution support
# Turn on these settings with
# --config=remote
###############################
################################## # Load default settings for Remote Build Execution
# Remote Build Execution support # import %workspace%/third_party/github.com/bazelbuild/bazel-toolchains/bazelrc/bazel-0.20.0.bazelrc
# Turn on these settings with #
# --config=remote #
##################################
# The following --define=EXECUTOR=remote will be able to be removed
# once https://github.com/bazelbuild/bazel/issues/7254 is fixed
build:remote --define=EXECUTOR=remote
# Set a higher timeout value, just in case.
build:remote --remote_timeout=600
# Increase the default number of jobs by 50% because our build has lots of # Increase the default number of jobs by 50% because our build has lots of
# parallelism # parallelism
build:remote --jobs=150 build:remote --jobs=150
build:remote --google_default_credentials
# Force remote exeuctions to consider the entire run as linux # Point to our custom execution platform; see tools/BUILD.bazel
build:remote --cpu=k8
build:remote --host_cpu=k8
# Toolchain and platform related flags
build:remote --host_javabase=@rbe_ubuntu1604_angular//java:jdk
build:remote --javabase=@rbe_ubuntu1604_angular//java:jdk
build:remote --host_java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8
build:remote --java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8
build:remote --crosstool_top=@rbe_ubuntu1604_angular//cc:toolchain
build:remote --extra_toolchains=@rbe_ubuntu1604_angular//config:cc-toolchain
build:remote --extra_execution_platforms=//tools:rbe_ubuntu1604-angular build:remote --extra_execution_platforms=//tools:rbe_ubuntu1604-angular
build:remote --host_platform=//tools:rbe_ubuntu1604-angular build:remote --host_platform=//tools:rbe_ubuntu1604-angular
build:remote --platforms=//tools:rbe_ubuntu1604-angular build:remote --platforms=//tools:rbe_ubuntu1604-angular
# Remote instance and caching # Remote instance.
build:remote --remote_instance_name=projects/internal-200822/instances/default_instance build:remote --remote_instance_name=projects/internal-200822/instances/default_instance
build:remote --project_id=internal-200822
build:remote --remote_cache=remotebuildexecution.googleapis.com
build:remote --remote_executor=remotebuildexecution.googleapis.com
################################## # Do not accept remote cache.
# Saucelabs tests settings # # We need to understand the security risks of using prior build artifacts.
# Turn on these settings with # build:remote --remote_accept_cached=false
# --config=saucelabs #
##################################
# For saucelabs tests we don't want to enable flaky test attempts. Karma has its own integrated
# retry mechanism and we do not want to retry unnecessarily if Karma already tried multiple times.
test:saucelabs --flaky_test_attempts=1
####################################################
# User bazel configuration
# NOTE: This needs to be the *last* entry in the config.
####################################################
# Load any settings which are specific to the current user. Needs to be *last* statement
# in this config, as the user configuration should be able to overwrite flags from this file.
try-import .bazelrc.user

View File

@ -1,3 +0,0 @@
3.2.0
# [NB: this comment has to be after the first line, see https://github.com/bazelbuild/bazelisk/issues/117]
# When updating the Bazel version you also need to update the RBE toolchains version in package.bzl

3
.bowerrc Normal file
View File

@ -0,0 +1,3 @@
{
"directory" : "bower_components"
}

42
.buildkite/Dockerfile Normal file
View File

@ -0,0 +1,42 @@
# Heavily based on https://github.com/StefanScherer/dockerfiles-windows/ images.
# Combines the node windowsservercore image with the Bazel Prerequisites (https://docs.bazel.build/versions/master/install-windows.html).
# msys install taken from https://github.com/StefanScherer/dockerfiles-windows/issues/30
# VS redist install taken from https://github.com/StefanScherer/dockerfiles-windows/blob/master/apache/Dockerfile
# The nanoserver image won't work because MSYS2 does not run in it https://github.com/Alexpux/MSYS2-packages/issues/1493
# Before building this image, you must locally build node-windows:10.13.0-windowsservercore-1803.
# Clone https://github.com/StefanScherer/dockerfiles-windows/commit/4ce7101a766b9b880ac262479dd9126b64d656cf and build using
# docker build -t node-windows:10.13.0-windowsservercore-1803 --build-arg core=microsoft/windowsservercore:1803 --build-arg target=microsoft/windowsservercore:1803 .
FROM node-windows:10.13.0-windowsservercore-1803
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
# Install 7zip to extract msys2
RUN Invoke-WebRequest -UseBasicParsing 'https://www.7-zip.org/a/7z1805-x64.exe' -OutFile 7z.exe
# For some reason the last letter in the destination directory is lost. So '/D=C:\\7zip0' will extract to '/D=C:\\7zip'.
RUN Start-Process -FilePath 'C:\\7z.exe' -ArgumentList '/S', '/D=C:\\7zip0' -NoNewWindow -Wait
# Extract msys2
RUN Invoke-WebRequest -UseBasicParsing 'http://repo.msys2.org/distrib/x86_64/msys2-base-x86_64-20180531.tar.xz' -OutFile msys2.tar.xz
RUN Start-Process -FilePath 'C:\\7zip\\7z' -ArgumentList 'e', 'msys2.tar.xz' -Wait
RUN Start-Process -FilePath 'C:\\7zip\\7z' -ArgumentList 'x', 'msys2.tar', '-oC:\\' -Wait
RUN Remove-Item msys2.tar.xz
RUN Remove-Item msys2.tar
RUN Remove-Item 7z.exe
RUN Remove-Item -Recurse 7zip
# Add MSYS2 to PATH, and set BAZEL_SH
RUN [Environment]::SetEnvironmentVariable('Path', $env:Path + ';C:\msys64\usr\bin', [System.EnvironmentVariableTarget]::Machine)
RUN [Environment]::SetEnvironmentVariable('BAZEL_SH', 'C:\msys64\usr\bin\bash.exe', [System.EnvironmentVariableTarget]::Machine)
# Install Microsoft Visual C++ Redistributable for Visual Studio 2015
RUN Invoke-WebRequest -UseBasicParsing 'https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.x64.exe' -OutFile vc_redist.x64.exe
RUN Start-Process 'c:\\vc_redist.x64.exe' -ArgumentList '/Install', '/Passive', '/NoRestart' -NoNewWindow -Wait
RUN Remove-Item vc_redist.x64.exe
# Add a fix for https://github.com/docker/for-win/issues/2920 as entry point to the container.
SHELL ["cmd", "/c"]
COPY "fix-msys64.cmd" "C:\\fix-msys64.cmd"
ENTRYPOINT cmd /C C:\\fix-msys64.cmd && cmd /c
CMD ["cmd.exe"]

96
.buildkite/README.md Normal file
View File

@ -0,0 +1,96 @@
# BuildKite configuration
This folder contains configuration for the [BuildKite](https://buildkite.com) based CI checks for
this repository.
BuildKite is a CI provider that provides build coordination and reports while we provide the
infrastructure.
CI runs are triggered by new PRs and will show up on the GitHub checks interface, along with the
other current CI solutions.
Currently it is only used for tests on Windows platforms.
## The build pipeline
BuildKite uses a pipeline for each repository. The `pipeline.yml` file defines pipeline
[build steps](https://buildkite.com/docs/pipelines/defining-steps) for this repository.
Run results can be seen in the GitHub checks interface and in the
[pipeline dashboard](https://buildkite.com/angular/angular).
Although most configuration is done via `pipeline.yml`, some options are only available
in the online [pipeline settings](https://buildkite.com/angular/angular/settings).
## Infrastructure
BuildKite does not provide the host machines where the builds runs, providing instead the
[BuildKite Agent](https://buildkite.com/docs/agent/v3) that should be run our own infrastructure.
### Agents
This agent polls the BuildKite API for builds, runs them, and reports back the results.
Agents are the unit of concurrency: each agent can run one build at any given time.
Adding agents allows more builds to be ran at the same time.
Individual agents can have tags, and pipeline steps can target only agents with certain tags via the
`agents` field in `pipeline.yml`.
For example: agents on Windows machines are tagged as `windows`, and the Windows specific build
steps list `windows: true` in their `agents` field.
You can see the current agent pool, along with their tags, in the
[agents list](https://buildkite.com/organizations/angular/agents).
### Our host machines
We use [Google Cloud](https://cloud.google.com/) as our cloud provider, under the
[Angular project](https://console.cloud.google.com/home/dashboard?project=internal-200822).
To access this project you need need to be logged in with a Google account that's a member of
team@angular.io.
For googlers this may be your google.com account, for others it is an angular.io account.
In this project we have a number of Windows VMs running, each of them with several agents.
The `provision-windows-buildkite.ps1` file contains instructions on how to create new host VMs that
are fully configured to run the BuildKite agents as services.
Our pipeline uses [docker-buildkite-plugin](https://github.com/buildkite-plugins/docker-buildkite-plugin)
to run build steps inside docker containers.
This way we achieve isolation and hermeticity.
The `Dockerfile` file describes a custom Docker image that includes NodeJs, Yarn, and the Bazel
pre-requisites on Windows.
To upload a new version of the docker image, follow any build instructions in `Dockerfile` and then
run `docker build -t angular/node-bazel-windows:NEW_VERSION`, followed by
`docker push angular/node-bazel-windows:NEW_VERSION`.
After being pushed it should be available online, and you can use the new version in `pipeline.yml`.
## Caretaker
BuildKite status can be found at https://www.buildkitestatus.com/.
Issues related to the BuildKite setup should be escalated to the Tools Team via the current
caretaker, followed by Alex Eagle and Filipe Silva.
Support requests should be submitted via email to support@buildkite.com and cc Igor, Misko, Alex,
Jeremy and Manu
## Rollout strategy
At the moment our BuildKite CI uses 1 host VM running 4 agents, thus being capable of 4 concurrent
builds.
The only test running is `bazel test //tools/ts-api-guardian:all`, and the PR check is not
mandatory.
In the future we should add cache support to speed up the initial `yarn` install, and also Bazel
remote caching to speed up Bazel builds.
After the current setup is verified as stable and reliable the GitHub PR check can become mandatory.
The tests ran should also be expanded to cover most, if not all, of the Bazel tests.

View File

@ -0,0 +1,6 @@
@echo off
REM Fix for https://github.com/docker/for-win/issues/2920
REM echo "Fixing msys64 folder..."
REM Touch all .dll files inside C:\msys64\
forfiles /p C:\msys64\ /s /m *.dll /c "cmd /c Copy /B @path+,, >NUL"
REM echo "Fixed msys64 folder."

10
.buildkite/pipeline.yml Normal file
View File

@ -0,0 +1,10 @@
steps:
- label: windows-test
commands:
- "yarn install --frozen-lockfile --non-interactive --network-timeout 100000"
- "yarn bazel test //tools/ts-api-guardian:all --noshow_progress"
plugins:
- docker#v2.1.0:
image: "filipesilva/node-bazel-windows:0.0.2"
agents:
windows: true

View File

@ -0,0 +1,92 @@
# PowerShell script to provision a Windows Server with BuildKite
# This script follows https://buildkite.com/docs/agent/v3/windows.
# Instructions
# VM creation:
# In Google Cloud Platform, create a Compute Engine instance.
# We recommend machine type n1-highcpu-16 (16 vCPUs, 14.4 GB memory).
# Use a windows boot disk with container support such as
# "Windows Server version 1803 Datacenter Core for Containers".
# Give it a name, then click "Create".
# VM setup:
# In the Compute Engine menu, select "VM Instances". Click on the VM name you chose before.
# Click "Set Windows Password" to choose a username and password.
# Click RDP to open a remote desktop via browser, using the username and password.
# In the Windows command prompt start an elevated powershell by inputing
# "powershell -Command "Start-Process PowerShell -Verb RunAs" followed by Enter.
# Download and execute this script from GitHub, passing the token (mandatory), tags (optional)
# and number of agents (optional) as args:
# ```
# Invoke-WebRequest -Uri https://raw.githubusercontent.com/angular/angular/master/.buildkite/provision-windows-buildkite.ps1 -OutFile provision.ps1
# .\provision.ps1 -token "MY_TOKEN" -tags "windows=true,another_tag=true" -agents 4
# ```
# The VM should restart and be fully configured.
# Creating extra VMs
# You can create an image of the current VM by following the instructions below.
# https://cloud.google.com/compute/docs/instances/windows/creating-windows-os-image
# Then create a new VM and choose "Custom images".
# Script proper.
# Get the token and tags from arguments.
param (
[Parameter(Mandatory=$true)][string]$token,
[string]$tags = ""
[Int]$agents = 1
)
# Allow HTTPS
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
# Helper to add to PATH.
# Will take current PATH so avoid running it after anything to modifies only the powershell session path.
function Add-Path ([string]$newPathItem) {
$Env:Path+= ";" + $newPathItem + ";"
[Environment]::SetEnvironmentVariable("Path",$env:Path, [System.EnvironmentVariableTarget]::Machine)
}
# Install Git for Windows
Write-Host "Installing Git for Windows."
Invoke-WebRequest -Uri https://github.com/git-for-windows/git/releases/download/v2.19.1.windows.1/Git-2.19.1-64-bit.exe -OutFile git.exe
.\git.exe /VERYSILENT /NORESTART /NOCANCEL /SP- /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS /COMPONENTS="icons,ext\reg\shellhere,assoc,assoc_sh" /DIR="C:\git"
Add-Path "C:\git\bin"
Remove-Item git.exe
# Download NSSM (https://nssm.cc/) to run the BuildKite agent as a service.
Write-Host "Downloading NSSM."
Invoke-WebRequest -Uri https://nssm.cc/ci/nssm-2.24-101-g897c7ad.zip -OutFile nssm.zip
Expand-Archive -Path nssm.zip -DestinationPath C:\nssm
Add-Path "C:\nssm\nssm-2.24-101-g897c7ad\win64"
Remove-Item nssm.zip
# Run the BuildKite agent install script
Write-Host "Installing BuildKite agent."
$env:buildkiteAgentToken = $token
$env:buildkiteAgentTags = $tags
Set-ExecutionPolicy Bypass -Scope Process -Force
iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/buildkite/agent/master/install.ps1'))
# Configure the BuildKite agent clone and timestamp behavior
Add-Content C:\buildkite-agent\buildkite-agent.cfg "`ngit-clone-flags=--config core.autocrlf=input --config core.eol=lf --config core.longpaths=true --config core.symlinks=true`n"
Add-Content C:\buildkite-agent\buildkite-agent.cfg "`ntimestamp-lines=true`n"
# Register the BuildKite agent service using NSSM, so that it persists through restarts and is
# restarted if the process dies.
for ($i=1; $i -le $agents; $i++)
{
$agentName = "buildkite-agent-$i"
Write-Host "Registering $agentName as a service."
nssm.exe install $agentName "C:\buildkite-agent\bin\buildkite-agent.exe" "start"
nssm.exe set $agentName AppStdout "C:\buildkite-agent\$agentName.log"
nssm.exe set $agentName AppStderr "C:\buildkite-agent\$agentName.log"
nssm.exe status $agentName
nssm.exe start $agentName
nssm.exe status $agentName
}
# Restart the machine.
Restart-Computer

View File

@ -12,8 +12,8 @@ We use this as a symmetric AES encryption key to encrypt tokens like
a GitHub token that enables publishing snapshots. a GitHub token that enables publishing snapshots.
To create the github_token file, we take this approach: To create the github_token file, we take this approach:
- Find the angular-builds:token in the internal pw database - Find the angular-builds:token in http://valentine
- Go inside the CircleCI default docker image so you use the same version of openssl as we will at runtime: `docker run --rm -it circleci/node:10.12` - Go inside the CircleCI default docker image so you use the same version of openssl as we will at runtime: `docker run --rm -it circleci/node:10.12`
- echo "https://[token]:@github.com" > credentials - echo "https://[token]:@github.com" > credentials
- openssl aes-256-cbc -e -in credentials -out .circleci/github_token -k $KEY - openssl aes-256-cbc -e -in credentials -out .circleci/github_token -k $KEY
- If needed, base64-encode the result so you can copy-paste it out of docker: `base64 github_token` - If needed, base64-encode the result so you can copy-paste it out of docker: `base64 github_token`

View File

@ -1,15 +0,0 @@
# Settings in this file should be OS agnostic. Use the bazel.<OS>.rc files for OS specific settings.
# Don't be spammy in the logs
build --noshow_progress
# Print all the options that apply to the build.
# This helps us diagnose which options override others
# (e.g. /etc/bazel.bazelrc vs. tools/bazel.rc)
build --announce_rc
# Retry in the event of flakes, eg. https://circleci.com/gh/angular/angular/31309
test --flaky_test_attempts=2
# More details on failures
build --verbose_failures=true

View File

@ -1,30 +0,0 @@
# These options are enabled when running on CI
# We do this by copying this file to /etc/bazel.bazelrc at the start of the build.
# See documentation in /docs/BAZEL.md
# Import config items common to both Linux and Windows setups.
# https://docs.bazel.build/versions/master/guide.html#bazelrc-syntax-and-semantics
try-import %workspace%/.circleci/bazel.common.rc
# Save downloaded repositories in a location that can be cached by CircleCI. This helps us
# speeding up the analysis time significantly with Bazel managed node dependencies on the CI.
build --repository_cache=/home/circleci/bazel_repository_cache
# Workaround https://github.com/bazelbuild/bazel/issues/3645
# Bazel doesn't calculate the memory ceiling correctly when running under Docker.
# Limit Bazel to consuming resources that fit in CircleCI "xlarge" class
# https://circleci.com/docs/2.0/configuration-reference/#resource_class
build --local_cpu_resources=8
build --local_ram_resources=14336
# All build executed remotely should be done using our RBE configuration.
build:remote --google_default_credentials
# Upload to GCP's Build Status viewer to allow for us to have better viewing of execution/build
# logs. This is only done on CI as the BES (GCP's Build Status viewer) API requires credentials
# from service accounts, rather than end user accounts.
build:remote --bes_backend=buildeventservice.googleapis.com
build:remote --bes_timeout=30s
build:remote --bes_results_url="https://source.cloud.google.com/results/invocations/"
build --config=remote

26
.circleci/bazel.rc Normal file
View File

@ -0,0 +1,26 @@
# These options are enabled when running on CI
# We do this by copying this file to /etc/bazel.bazelrc at the start of the build.
# See documentation in /docs/BAZEL.md
# Don't be spammy in the logs
# TODO(gmagolan): Hide progress again once build performance improves
# Presently, CircleCI can timeout during bazel test ... with the following
# error: Too long with no output (exceeded 10m0s)
# build --noshow_progress
# Print all the options that apply to the build.
# This helps us diagnose which options override others
# (e.g. /etc/bazel.bazelrc vs. tools/bazel.rc)
build --announce_rc
# Workaround https://github.com/bazelbuild/bazel/issues/3645
# Bazel doesn't calculate the memory ceiling correctly when running under Docker.
# Limit Bazel to consuming resources that fit in CircleCI "xlarge" class
# https://circleci.com/docs/2.0/configuration-reference/#resource_class
build --local_resources=14336,8.0,1.0
# Retry in the event of flakes, eg. https://circleci.com/gh/angular/angular/31309
test --flaky_test_attempts=2
# More details on failures
build --verbose_failures=true

View File

@ -1,21 +0,0 @@
# These options are enabled when running on CI
# We do this by copying this file to $env:ProgramData\bazel.bazelrc at the start of the build.
# See documentation in /docs/BAZEL.md
# Import config items common to both Linux and Windows setups.
# https://docs.bazel.build/versions/master/guide.html#bazelrc-syntax-and-semantics
try-import %workspace%/.circleci/bazel.common.rc
# Save downloaded repositories in a location that can be cached by CircleCI. This helps us
# speeding up the analysis time significantly with Bazel managed node dependencies on the CI.
build --repository_cache=C:/Users/circleci/bazel_repository_cache
# Manually set the local resources used in windows CI runs
build --local_ram_resources=13500
build --local_cpu_resources=4
# All windows jobs run on master and should use http caching
build --remote_http_cache=https://storage.googleapis.com/angular-team-cache
build --remote_accept_cached=true
build --remote_upload_local_results=true
build --google_default_credentials

View File

@ -7,300 +7,210 @@
# To validate changes, use an online parser, eg. # To validate changes, use an online parser, eg.
# http://yaml-online-parser.appspot.com/ # http://yaml-online-parser.appspot.com/
# CircleCI configuration version # Note that the browser docker image comes with Chrome and Firefox preinstalled. This is just
# Version 2.1 allows for extra config reuse features # needed for jobs that run tests without Bazel. Bazel runs tests with browsers that will be
# https://circleci.com/docs/2.0/reusing-config/#getting-started-with-config-reuse # fetched by the Webtesting rules. Therefore for jobs that run tests with Bazel, we don't need a
version: 2.1 # docker image with browsers pre-installed.
# **NOTE**: If you change the version of the docker images, also change the `cache_key` suffix.
var_1: &default_docker_image circleci/node:10.12
var_2: &browsers_docker_image circleci/node:10.12-browsers
var_3: &cache_key v2-angular-{{ .Branch }}-{{ checksum "yarn.lock" }}-node-10.12
# We don't want to include the current branch name in the cache key because that would prevent # Define common ENV vars
# PRs from being able to restore the cache since the branch names are always different for PRs. var_4: &define_env_vars
# The cache key should only consist of dynamic values that change whenever something in the run:
# cache changes. For example: name: Define environment variables
# 1) yarn lock file changes --> cached "node_modules" are different. command: ./.circleci/env.sh
# 2) bazel repository definitions change --> cached bazel repositories are different.
# Windows needs its own cache key because binaries in node_modules are different.
# **NOTE 1 **: If you change the cache key prefix, also sync the cache_key_fallback to match.
# **NOTE 2 **: Keep the static part of the cache key as prefix to enable correct fallbacks.
# See https://circleci.com/docs/2.0/caching/#restoring-cache for how prefixes work in CircleCI.
var_3: &cache_key v7-angular-node-12-{{ checksum ".bazelversion" }}-{{ checksum "yarn.lock" }}-{{ checksum "WORKSPACE" }}-{{ checksum "packages/bazel/package.bzl" }}-{{ checksum "aio/yarn.lock" }}
# We invalidate the cache if the Bazel version changes because otherwise the `bazelisk` cache
# folder will contain all previously used versions and ultimately cause the cache restoring to
# be slower due to its growing size.
var_4: &cache_key_fallback v7-angular-node-12-{{ checksum ".bazelversion" }}
var_3_win: &cache_key_win v7-angular-win-node-12-{{ checksum ".bazelversion" }}-{{ checksum "yarn.lock" }}-{{ checksum "WORKSPACE" }}-{{ checksum "packages/bazel/package.bzl" }}-{{ checksum "aio/yarn.lock" }}
var_4_win: &cache_key_win_fallback v7-angular-win-node-12-{{ checksum ".bazelversion" }}
# Workspace initially persisted by the `setup` job, and then enhanced by `build-npm-packages` and var_5: &setup_bazel_remote_execution
# `build-ivy-npm-packages`. run:
# https://circleci.com/docs/2.0/workflows/#using-workspaces-to-share-data-among-jobs name: "Setup bazel RBE remote execution"
# https://circleci.com/blog/deep-diving-into-circleci-workspaces/ command: |
var_7: &workspace_location ~/ openssl aes-256-cbc -d -in .circleci/gcp_token -k "$CI_REPO_NAME" -out /home/circleci/.gcp_credentials
echo "export GOOGLE_APPLICATION_CREDENTIALS=/home/circleci/.gcp_credentials" >> $BASH_ENV
sudo bash -c "echo 'build --config=remote' >> /etc/bazel.bazelrc"
# Filter to run a job on builds for pull requests only. # Settings common to each job
var_8: &only_on_pull_requests var_6: &job_defaults
filters: working_directory: ~/ng
branches: docker:
only: - image: *default_docker_image
- /pull\/\d+/
# Filter to skip a job on builds for pull requests. # After checkout, rebase on top of master.
var_9: &skip_on_pull_requests # Similar to travis behavior, but not quite the same.
filters: # See https://discuss.circleci.com/t/1662
branches: var_7: &post_checkout
ignore: post: git pull --ff-only origin "refs/pull/${CI_PULL_REQUEST//*pull\//}/merge"
- /pull\/\d+/
# Filter to run a job on builds for the master branch only. var_8: &yarn_install
var_10: &only_on_master run:
filters: name: Running Yarn install
branches: command: yarn install --frozen-lockfile --non-interactive
only:
- master
# Executor Definitions var_9: &setup_circleci_bazel_config
# https://circleci.com/docs/2.0/reusing-config/#authoring-reusable-executors run:
# **NOTE 1**: Pin to exact images using an ID (SHA). See https://circleci.com/docs/2.0/circleci-images/#using-a-docker-image-id-to-pin-an-image-to-a-fixed-version. name: Setting up CircleCI bazel configuration
# (Using the tag in not necessary when pinning by ID, but include it anyway for documentation purposes.) command: sudo cp .circleci/bazel.rc /etc/bazel.bazelrc
# **NOTE 2**: If you change the version of the docker images, also change the `cache_key` suffix.
executors:
default-executor:
parameters:
resource_class:
type: string
default: medium
docker:
- image: circleci/node:12.14.1@sha256:f9de24fc0017059cc42ef7d07db060008af65a98b1f0cdd1ef3339213226bf6d
resource_class: << parameters.resource_class >>
working_directory: ~/ng
windows-executor: version: 2
working_directory: ~/ng
resource_class: windows.medium
# CircleCI windows VMs do have the GitBash shell available:
# https://github.com/CircleCI-Public/windows-preview-docs#shells
# But in this specific case we really should not use it because Bazel must not be ran from
# GitBash. These issues discuss why:
# https://github.com/bazelbuild/bazel/issues/5751
# https://github.com/bazelbuild/bazel/issues/5724#issuecomment-410194038
# https://github.com/bazelbuild/bazel/issues/6339#issuecomment-441600879
shell: powershell.exe -ExecutionPolicy Bypass
machine:
# Windows preview image that includes the following:
# - Visual Studio 2019 build tools
# - Node 12
# - yarn 1.17
# - Python 3 3.7.4
image: windows-server-2019-vs2019:201908-02
# Command Definitions
# https://circleci.com/docs/2.0/reusing-config/#authoring-reusable-commands
commands:
custom_attach_workspace:
description: Attach workspace at a predefined location
steps:
- attach_workspace:
at: *workspace_location
# Install shared libs used by Chrome that is either provisioned by
# rules_webtesting or by puppeteer.
install_chrome_libs:
description: Install shared Chrome libs
steps:
- run:
name: Install shared Chrome libs
command: |
sudo apt-get update
# Install GTK+ graphical user interface (libgtk-3-0), advanced linux sound architecture (libasound2)
# and network security service libraries (libnss3) & X11 Screen Saver extension library (libssx1)
# which are dependencies of chrome & needed for karma & protractor headless chrome tests.
# This is a very small install which takes around 7s in comparing to using the full
# circleci/node:x.x.x-browsers image.
sudo apt-get -y install libgtk-3-0 libasound2 libnss3 libxss1
# Install java runtime which is required by some integration tests such as
# //integration:hello_world__closure_test, //integration:i18n_test and
# //integration:ng_elements_test to run the closure compiler
install_java:
description: Install java
steps:
- run:
name: Install java
command: |
sudo apt-get update
# Install java runtime
sudo apt-get install default-jre
# Initializes the CI environment by setting up common environment variables.
init_environment:
description: Initializing environment (setting up variables)
steps:
- run:
name: Set up environment
environment:
CIRCLE_GIT_BASE_REVISION: << pipeline.git.base_revision >>
CIRCLE_GIT_REVISION: << pipeline.git.revision >>
command: ./.circleci/env.sh
- run:
# Configure git as the CircleCI `checkout` command does.
# This is needed because we only checkout on the setup job.
# Add GitHub to known hosts
name: Configure git
command: |
mkdir -p ~/.ssh
echo 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==' >> ~/.ssh/known_hosts
git config --global url."ssh://git@github.com".insteadOf "https://github.com" || true
git config --global gc.auto 0 || true
# Normally this would be an individual job instead of a command.
# But startup and setup time for each individual windows job are high enough to discourage
# many small jobs, so instead we use a command for setup unless the gain becomes significant.
setup_win:
description: Setup windows node environment
steps:
# Use the Linux workspace directly, as it already has checkout, rebased and node modules.
- custom_attach_workspace
# Install Bazel pre-requisites that aren't in the preconfigured CircleCI Windows VM.
- run: ./.circleci/windows-env.ps1
- run: node --version
- run: yarn --version
- restore_cache:
keys:
- *cache_key_win
- *cache_key_win_fallback
# Reinstall to get windows binaries.
- run: yarn install --frozen-lockfile --non-interactive
# Install @bazel/bazelisk globally and use that for the first run.
# Workaround for https://github.com/bazelbuild/rules_nodejs/issues/894
# NB: the issue was for @bazel/bazel but the same problem applies to @bazel/bazelisk
- run: yarn global add @bazel/bazelisk@$env:BAZELISK_VERSION
- run: bazelisk info
notify_webhook_on_fail:
description: Notify a webhook about failure
parameters:
# `webhook_url_env_var` are secret env vars defined in CircleCI project settings.
# The URLs come from https://angular-team.slack.com/apps/A0F7VRE7N-circleci.
webhook_url_env_var:
type: env_var_name
steps:
- run:
when: on_fail
command: |
notificationJson="{\"text\":\":x: \`$CIRCLE_JOB\` job for $CIRCLE_BRANCH branch failed on build $CIRCLE_BUILD_NUM: $CIRCLE_BUILD_URL :scream:\"}"
curl --request POST --header "Content-Type: application/json" --data "$notificationJson" ${<< parameters.webhook_url_env_var >>}
# Job definitions
# Jobs can include parameters that are passed in the workflow job invocation.
# https://circleci.com/docs/2.0/reusing-config/#authoring-parameterized-jobs
jobs: jobs:
setup:
executor: default-executor
steps:
- checkout
- init_environment
- run:
name: Rebase PR on target branch
# After checkout, rebase on top of target branch.
command: >
if [[ -n "${CIRCLE_PR_NUMBER}" ]]; then
# User is required for rebase.
git config user.name "angular-ci"
git config user.email "angular-ci"
# Rebase PR on top of target branch.
node tools/rebase-pr.js
else
echo "This build is not over a PR, nothing to do."
fi
# This cache is saved in the build-npm-packages so that Bazel cache is also included.
- restore_cache:
keys:
- *cache_key
- *cache_key_fallback
- run:
name: Running Yarn install
command: yarn install --frozen-lockfile --non-interactive
# Yarn's requests sometimes take more than 10mins to complete.
no_output_timeout: 45m
- run: yarn --cwd aio install --frozen-lockfile --non-interactive
# Make the bazel directories and add a file to them if they don't exist already so that
# persist_to_workspace does not fail.
- run: |
if [ ! -d ~/bazel_repository_cache ]; then
mkdir ~/bazel_repository_cache
touch ~/bazel_repository_cache/MARKER
fi
# Persist any changes at this point to be reused by further jobs.
# **NOTE**: To add new content to the workspace, always persist on the same root.
- persist_to_workspace:
root: *workspace_location
paths:
- ./ng
- ./bazel_repository_cache
lint: lint:
executor: default-executor <<: *job_defaults
steps: steps:
- custom_attach_workspace - checkout:
- init_environment <<: *post_checkout
- restore_cache:
key: *cache_key
- *define_env_vars
- *yarn_install
- run: yarn -s tslint - run: 'yarn bazel:format -mode=check ||
- run: yarn -s ng-dev format changed $CI_GIT_BASE_REVISION --check (echo "BUILD files not formatted. Please run ''yarn bazel:format''" ; exit 1)'
- run: yarn -s ts-circular-deps:check # Run the skylark linter to check our Bazel rules
- run: yarn -s ng-dev commit-message validate-range --range $CI_COMMIT_RANGE - run: 'yarn bazel:lint ||
(echo -e "\n.bzl files have lint errors. Please run ''yarn bazel:lint-fix''"; exit 1)'
- run: ./node_modules/.bin/gulp lint
test:
<<: *job_defaults
resource_class: xlarge
steps:
- checkout:
<<: *post_checkout
- restore_cache:
key: *cache_key
- *define_env_vars
- *setup_circleci_bazel_config
- *yarn_install
# Setup remote execution and run RBE-compatible tests.
- *setup_bazel_remote_execution
- run: yarn bazel test //... --build_tag_filters=-ivy-only --test_tag_filters=-ivy-only,-local
# Now run RBE incompatible tests locally.
- run: sudo cp .circleci/bazel.rc /etc/bazel.bazelrc
- run: yarn bazel test //... --build_tag_filters=-ivy-only,local --test_tag_filters=-ivy-only,local
- save_cache:
key: *cache_key
paths:
- "node_modules"
- "~/bazel_repository_cache"
# Temporary job to test what will happen when we flip the Ivy flag to true
test_ivy_aot:
<<: *job_defaults
resource_class: xlarge
steps:
- checkout:
<<: *post_checkout
- restore_cache:
key: *cache_key
- *define_env_vars
- *setup_circleci_bazel_config
- *yarn_install
- *setup_bazel_remote_execution
# We need to explicitly specify the --symlink_prefix option because otherwise we would
# not be able to easily find the output bin directory when uploading artifacts for size
# measurements.
- run: yarn test-ivy-aot //... --symlink_prefix=dist/
# Publish bundle artifacts which will be used to calculate the size change. **Note**: Make
# sure that the size plugin from the Angular robot fetches the artifacts from this CircleCI
# job (see .github/angular-robot.yml). Additionally any artifacts need to be stored with the
# following path format: "{projectName}/{context}/{fileName}". This format is necessary
# because otherwise the bot is not able to pick up the artifacts from CircleCI. See:
# https://github.com/angular/github-robot/blob/master/functions/src/plugins/size.ts#L392-L394
- store_artifacts:
path: dist/bin/packages/core/test/bundling/hello_world/bundle.min.js
destination: core/hello_world/bundle
- store_artifacts:
path: dist/bin/packages/core/test/bundling/todo/bundle.min.js
destination: core/todo/bundle
- store_artifacts:
path: dist/bin/packages/core/test/bundling/hello_world/bundle.min.js.br
destination: core/hello_world/bundle.br
- store_artifacts:
path: dist/bin/packages/core/test/bundling/todo/bundle.min.js.br
destination: core/todo/bundle.br
test_aio: test_aio:
executor: default-executor <<: *job_defaults
docker:
# Needed because the AIO tests and the PWA score test depend on Chrome being available.
- image: *browsers_docker_image
steps: steps:
- custom_attach_workspace - checkout:
- init_environment <<: *post_checkout
- install_chrome_libs - restore_cache:
key: *cache_key
- *define_env_vars
# Build aio # Build aio
- run: yarn --cwd aio build --progress=false - run: yarn --cwd aio build --progress=false
# Lint the code # Lint the code
- run: yarn --cwd aio lint - run: yarn --cwd aio lint
# Run unit tests
- run: yarn --cwd aio test --progress=false --watch=false
# Run e2e tests
- run: yarn --cwd aio e2e --configuration=ci
# Run PWA-score tests # Run PWA-score tests
# (Run before unit and e2e tests, which destroy the `dist/` directory.)
- run: yarn --cwd aio test-pwa-score-localhost $CI_AIO_MIN_PWA_SCORE - run: yarn --cwd aio test-pwa-score-localhost $CI_AIO_MIN_PWA_SCORE
# Run accessibility tests # Check the bundle sizes.
- run: yarn --cwd aio test-a11y-score-localhost # (Run before unit and e2e tests, which destroy the `dist/` directory.)
- run: yarn --cwd aio payload-size
# Run unit tests
- run: yarn --cwd aio test --watch=false
# Run e2e tests
- run: yarn --cwd aio e2e
# Run unit tests for Firebase redirects
- run: yarn --cwd aio redirects-test
deploy_aio: deploy_aio:
executor: default-executor <<: *job_defaults
docker:
# Needed because before deploying the deploy-production script runs the PWA score tests.
- image: *browsers_docker_image
steps: steps:
- custom_attach_workspace - checkout:
- init_environment <<: *post_checkout
- install_chrome_libs - restore_cache:
key: *cache_key
- *define_env_vars
# Deploy angular.io to production (if necessary) # Deploy angular.io to production (if necessary)
- run: setPublicVar_CI_STABLE_BRANCH - run: setPublicVar CI_STABLE_BRANCH "$(npm info @angular/core dist-tags.latest | sed -r 's/^\s*([0-9]+\.[0-9]+)\.[0-9]+.*$/\1.x/')"
- run: yarn --cwd aio deploy-production - run: yarn --cwd aio deploy-production
test_aio_local: test_aio_local:
parameters: <<: *job_defaults
viewengine: docker:
type: boolean # Needed because the AIO tests and the PWA score test depend on Chrome being available.
default: false - image: *browsers_docker_image
executor: default-executor
steps: steps:
- custom_attach_workspace - checkout:
- init_environment <<: *post_checkout
- install_chrome_libs - restore_cache:
key: *cache_key
- attach_workspace:
at: dist
- *define_env_vars
# Build aio (with local Angular packages) # Build aio (with local Angular packages)
- run: yarn --cwd aio build-local<<# parameters.viewengine >>-with-viewengine<</ parameters.viewengine >>-ci - run: yarn --cwd aio build-local --progress=false
# Run unit tests
- run: yarn --cwd aio test --progress=false --watch=false
# Run e2e tests
- run: yarn --cwd aio e2e --configuration=ci
# Run PWA-score tests # Run PWA-score tests
# (Run before unit and e2e tests, which destroy the `dist/` directory.)
- run: yarn --cwd aio test-pwa-score-localhost $CI_AIO_MIN_PWA_SCORE - run: yarn --cwd aio test-pwa-score-localhost $CI_AIO_MIN_PWA_SCORE
# Run unit tests
- run: yarn --cwd aio test --watch=false
# Run e2e tests
- run: yarn --cwd aio e2e
test_aio_tools: test_aio_tools:
executor: default-executor <<: *job_defaults
steps: steps:
- custom_attach_workspace - checkout:
- init_environment <<: *post_checkout
- restore_cache:
key: *cache_key
- attach_workspace:
at: dist
- *define_env_vars
# Install # Install
- run: yarn --cwd aio install --frozen-lockfile --non-interactive - run: yarn --cwd aio install --frozen-lockfile --non-interactive
- run: yarn --cwd aio extract-cli-command-docs - run: yarn --cwd aio extract-cli-command-docs
@ -308,14 +218,58 @@ jobs:
- run: yarn --cwd aio tools-test - run: yarn --cwd aio tools-test
- run: ./aio/aio-builds-setup/scripts/test.sh - run: ./aio/aio-builds-setup/scripts/test.sh
test_docs_examples_0:
<<: *job_defaults
docker:
# Needed because the example e2e tests depend on Chrome.
- image: *browsers_docker_image
steps:
- checkout:
<<: *post_checkout
- restore_cache:
key: *cache_key
- attach_workspace:
at: dist
- *define_env_vars
# Install root
- *yarn_install
# Install aio
- run: yarn --cwd aio install --frozen-lockfile --non-interactive
# Run examples tests
- run: yarn --cwd aio example-e2e --setup --local --shard=0/2
test_docs_examples_1:
<<: *job_defaults
docker:
# Needed because the example e2e tests depend on Chrome.
- image: *browsers_docker_image
steps:
- checkout:
<<: *post_checkout
- restore_cache:
key: *cache_key
- attach_workspace:
at: dist
- *define_env_vars
# Install root
- *yarn_install
# Install aio
- run: yarn --cwd aio install --frozen-lockfile --non-interactive
# Run examples tests
- run: yarn --cwd aio example-e2e --setup --local --shard=1/2
# This job should only be run on PR builds, where `CI_PULL_REQUEST` is not `false`. # This job should only be run on PR builds, where `CI_PULL_REQUEST` is not `false`.
aio_preview: aio_preview:
executor: default-executor <<: *job_defaults
environment: environment:
AIO_SNAPSHOT_ARTIFACT_PATH: &aio_preview_artifact_path 'aio/tmp/snapshot.tgz' AIO_SNAPSHOT_ARTIFACT_PATH: &aio_preview_artifact_path 'aio/tmp/snapshot.tgz'
steps: steps:
- custom_attach_workspace - checkout:
- init_environment <<: *post_checkout
- restore_cache:
key: *cache_key
- *define_env_vars
- *yarn_install
- run: ./aio/scripts/build-artifacts.sh $AIO_SNAPSHOT_ARTIFACT_PATH $CI_PULL_REQUEST $CI_COMMIT - run: ./aio/scripts/build-artifacts.sh $AIO_SNAPSHOT_ARTIFACT_PATH $CI_PULL_REQUEST $CI_COMMIT
- store_artifacts: - store_artifacts:
path: *aio_preview_artifact_path path: *aio_preview_artifact_path
@ -326,81 +280,186 @@ jobs:
# This job should only be run on PR builds, where `CI_PULL_REQUEST` is not `false`. # This job should only be run on PR builds, where `CI_PULL_REQUEST` is not `false`.
test_aio_preview: test_aio_preview:
executor: default-executor <<: *job_defaults
docker:
# Needed because the test-preview script runs e2e tests and the PWA score test with Chrome.
- image: *browsers_docker_image
steps: steps:
- custom_attach_workspace - checkout:
- init_environment <<: *post_checkout
- install_chrome_libs - restore_cache:
- run: yarn --cwd aio install --frozen-lockfile --non-interactive key: *cache_key
- *define_env_vars
- run: yarn install --cwd aio --frozen-lockfile --non-interactive
- run: - run:
name: Wait for preview and run tests name: Wait for preview and run tests
command: node aio/scripts/test-preview.js $CI_PULL_REQUEST $CI_COMMIT $CI_AIO_MIN_PWA_SCORE command: node aio/scripts/test-preview.js $CI_PULL_REQUEST $CI_COMMIT $CI_AIO_MIN_PWA_SCORE
# The `build-npm-packages` tasks exist for backwards-compatibility with old scripts and # This job exists only for backwards-compatibility with old scripts and tests
# tests that rely on the pre-Bazel `dist/packages-dist` output structure (build.sh). # that rely on the pre-Bazel dist/packages-dist layout.
# Having multiple jobs that independently build in this manner duplicates some work; we build # It duplicates some work with the job above: we build the bazel packages
# the bazel packages more than once. Even though we have a remote cache, these jobs will # twice. Even though we have a remote cache, these jobs will typically run in
# typically run in parallel so up-to-date outputs will not be available at the time the build # parallel so up-to-date outputs will not be available at the time the build
# starts. # starts.
# No new jobs should depend on this one.
# Build the view engine npm packages. No new jobs should depend on this. build-packages-dist:
build-npm-packages: <<: *job_defaults
executor: resource_class: xlarge
name: default-executor
resource_class: medium
steps: steps:
- custom_attach_workspace - checkout:
- init_environment <<: *post_checkout
- run: node scripts/build/build-packages-dist.js - restore_cache:
key: *cache_key
- *define_env_vars
- *setup_circleci_bazel_config
- *yarn_install
- *setup_bazel_remote_execution
- run: scripts/build-packages-dist.sh
# Save the npm packages from //packages/... for other workflow jobs to read # Save the npm packages from //packages/... for other workflow jobs to read
# https://circleci.com/docs/2.0/workflows/#using-workspaces-to-share-data-among-jobs
- persist_to_workspace: - persist_to_workspace:
root: *workspace_location root: dist
paths: paths:
- ng/dist/packages-dist - packages-dist
- ng/dist/zone.js-dist - packages-dist-ivy-jit
- packages-dist-ivy-aot
# Save dependencies and bazel repository cache to use on subsequent runs. # We run the integration tests outside of Bazel for now.
- save_cache: # They are a separate workflow job so that they can be easily re-run.
# When the tests are ported to bazel test targets, they should move to the "test"
# job above, as part of the bazel test command. That has flaky_test_attempts so the
# need to re-run manually should be alleviated.
# See comments inside the integration/run_tests.sh script.
integration_test:
<<: *job_defaults
docker:
# Needed because the integration tests expect Chrome to be installed (e.g cli-hello-world)
- image: *browsers_docker_image
# Note: we run Bazel in one of the integration tests, and it can consume >2G
# of memory. Together with the system under test, this can exhaust the RAM
# on a 4G worker so we use a larger machine here too.
resource_class: xlarge
steps:
- checkout:
<<: *post_checkout
- restore_cache:
key: *cache_key key: *cache_key
paths: - attach_workspace:
- "node_modules" at: dist
- "aio/node_modules" - *define_env_vars
- "~/bazel_repository_cache" - run: ./integration/run_tests.sh
- "~/.cache/bazelisk"
# This job updates the content of repos like github.com/angular/core-builds
# for every green build on angular/angular.
publish_snapshot:
<<: *job_defaults
steps:
- checkout:
<<: *post_checkout
- *define_env_vars
# See below - ideally this job should not trigger for non-upstream builds.
# But since it does, we have to check this condition.
- run:
name: Skip this job for Pull Requests and Fork builds
# Note, `|| true` on the end makes this step always exit 0
command: '[[
"$CI_PULL_REQUEST" != "false"
|| "$CI_REPO_OWNER" != "angular"
|| "$CI_REPO_NAME" != "angular"
]] && circleci step halt || true'
- attach_workspace:
at: dist
# CircleCI has a config setting to force SSH for all github connections
# This is not compatible with our mechanism of using a Personal Access Token
# Clear the global setting
- run: git config --global --unset "url.ssh://git@github.com.insteadof"
- run:
name: Decrypt github credentials
command: 'openssl aes-256-cbc -d -in .circleci/github_token -k "${KEY}" -out ~/.git_credentials'
- run: ./scripts/ci/publish-build-artifacts.sh
aio_monitoring:
<<: *job_defaults
docker:
# This job needs Chrome to be globally installed because the tests run with Protractor
# which does not load the browser through the Bazel webtesting rules.
- image: *browsers_docker_image
steps:
- checkout:
<<: *post_checkout
- restore_cache:
key: *cache_key
- *define_env_vars
- run:
name: Run tests against the deployed apps
command: ./aio/scripts/test-production.sh $CI_AIO_MIN_PWA_SCORE
- run:
name: Notify caretaker about failure
command: 'curl --request POST --header "Content-Type: application/json" --data "{\"text\":\":x: \`$CIRCLE_JOB\` job failed on build $CIRCLE_BUILD_NUM: $CIRCLE_BUILD_URL :scream:\"}" $CI_SECRET_SLACK_CARETAKER_WEBHOOK_URL'
when: on_fail
workflows: workflows:
version: 2 version: 2
default_workflow: default_workflow:
jobs: jobs:
- setup: - lint
filters: - test
branches: - test_ivy_aot
ignore: g3 - build-packages-dist
- lint: - test_aio
requires:
- setup
- build-npm-packages:
requires:
- setup
- test_aio:
requires:
- setup
- deploy_aio: - deploy_aio:
requires: requires:
- test_aio - test_aio
- test_aio_local: - test_aio_local:
requires: requires:
- build-npm-packages - build-packages-dist
- test_aio_tools: - test_aio_tools:
requires: requires:
- build-npm-packages - build-packages-dist
- test_docs_examples_0:
requires:
- build-packages-dist
- test_docs_examples_1:
requires:
- build-packages-dist
- aio_preview: - aio_preview:
# Only run on PR builds. (There can be no previews for non-PR builds.) # Only run on PR builds. (There can be no previews for non-PR builds.)
<<: *only_on_pull_requests filters:
requires: branches:
- setup only: /pull\/\d+/
- test_aio_preview: - test_aio_preview:
requires: requires:
- aio_preview - aio_preview
- integration_test:
requires:
- build-packages-dist
- publish_snapshot:
# Note: no filters on this job because we want it to run for all upstream branches
# We'd really like to filter out pull requests here, but not yet available:
# https://discuss.circleci.com/t/workflows-pull-request-filter/14396/4
# Instead, the job just exits immediately at the first step.
requires:
# Only publish if tests and integration tests pass
- test
- test_ivy_aot
- integration_test
# Only publish if `aio`/`docs` tests using the locally built Angular packages pass
- test_aio_local
- test_docs_examples_0
- test_docs_examples_1
# Get the artifacts to publish from the build-packages-dist job
# since the publishing script expects the legacy outputs layout.
- build-packages-dist
aio_monitoring:
jobs:
- aio_monitoring
triggers:
- schedule:
cron: "0 0 * * *"
filters:
branches:
only:
- master

View File

@ -15,7 +15,7 @@
# #
# Usage: `setPublicVar <name> <value>` # Usage: `setPublicVar <name> <value>`
function setPublicVar() { function setPublicVar() {
setSecretVar $1 "$2"; setSecretVar $1 $2;
echo "$1=$2"; echo "$1=$2";
} }
@ -36,38 +36,3 @@ function setSecretVar() {
# Restore original shell options. # Restore original shell options.
eval "$originalShellOptions"; eval "$originalShellOptions";
} }
# Create a function to set an environment variable, when called.
#
# Use this function for creating setter for public environment variables that require expensive or
# time-consuming computaions and may not be needed. When needed, you can call this function to set
# the environment variable (which will be available through `$BASH_ENV` from that point onwards).
#
# Arguments:
# - `<name>`: The name of the environment variable. The generated setter function will be
# `setPublicVar_<name>`.
# - `<code>`: The code to run to compute the value for the variable. Since this code should be
# executed lazily, it must be properly escaped. For example:
# ```sh
# # DO NOT do this:
# createPublicVarSetter MY_VAR "$(whoami)"; # `whoami` will be evaluated eagerly
#
# # DO this isntead:
# createPublicVarSetter MY_VAR "\$(whoami)"; # `whoami` will NOT be evaluated eagerly
# ```
#
# Usage: `createPublicVarSetter <name> <code>`
#
# Example:
# ```sh
# createPublicVarSetter MY_VAR 'echo "FOO"';
# echo $MY_VAR; # Not defined
#
# setPublicVar_MY_VAR;
# source $BASH_ENV;
# echo $MY_VAR; # FOO
# ```
function createPublicVarSetter() {
echo "setPublicVar_$1() { setPublicVar $1 \"$2\"; }" >> $BASH_ENV;
}

View File

@ -1,11 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Variables
readonly projectDir=$(realpath "$(dirname ${BASH_SOURCE[0]})/..")
readonly envHelpersPath="$projectDir/.circleci/env-helpers.inc.sh";
readonly bashEnvCachePath="$projectDir/.circleci/bash_env_cache";
# Load helpers and make them available everywhere (through `$BASH_ENV`). # Load helpers and make them available everywhere (through `$BASH_ENV`).
readonly envHelpersPath="`dirname $0`/env-helpers.inc.sh";
source $envHelpersPath; source $envHelpersPath;
echo "source $envHelpersPath;" >> $BASH_ENV; echo "source $envHelpersPath;" >> $BASH_ENV;
@ -13,32 +9,17 @@ echo "source $envHelpersPath;" >> $BASH_ENV;
#################################################################################################### ####################################################################################################
# Define PUBLIC environment variables for CircleCI. # Define PUBLIC environment variables for CircleCI.
#################################################################################################### ####################################################################################################
# See https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables for more info. setPublicVar PROJECT_ROOT "$(pwd)";
#################################################################################################### setPublicVar CI_AIO_MIN_PWA_SCORE "95";
setPublicVar CI "$CI"
setPublicVar PROJECT_ROOT "$projectDir";
setPublicVar CI_AIO_MIN_PWA_SCORE "62";
# This is the branch being built; e.g. `pull/12345` for PR builds. # This is the branch being built; e.g. `pull/12345` for PR builds.
setPublicVar CI_BRANCH "$CIRCLE_BRANCH"; setPublicVar CI_BRANCH "$CIRCLE_BRANCH";
setPublicVar CI_BUILD_URL "$CIRCLE_BUILD_URL";
setPublicVar CI_COMMIT "$CIRCLE_SHA1"; setPublicVar CI_COMMIT "$CIRCLE_SHA1";
# `CI_COMMIT_RANGE` is only used on push builds (a.k.a. non-PR, non-scheduled builds and rerun # `CI_COMMIT_RANGE` will only be available when `CIRCLE_COMPARE_URL` is also available,
# workflows of such builds). # i.e. on push builds (a.k.a. non-PR builds). That is fine, since we only need it in push builds.
setPublicVar CI_GIT_BASE_REVISION "${CIRCLE_GIT_BASE_REVISION}"; setPublicVar CI_COMMIT_RANGE "$(sed -r 's|^.*/([0-9a-f]+\.\.\.[0-9a-f]+)$|\1|i' <<< ${CIRCLE_COMPARE_URL:-})";
setPublicVar CI_GIT_REVISION "${CIRCLE_GIT_REVISION}";
setPublicVar CI_COMMIT_RANGE "$CIRCLE_GIT_BASE_REVISION..$CIRCLE_GIT_REVISION";
setPublicVar CI_PULL_REQUEST "${CIRCLE_PR_NUMBER:-false}"; setPublicVar CI_PULL_REQUEST "${CIRCLE_PR_NUMBER:-false}";
setPublicVar CI_REPO_NAME "$CIRCLE_PROJECT_REPONAME"; setPublicVar CI_REPO_NAME "$CIRCLE_PROJECT_REPONAME";
setPublicVar CI_REPO_OWNER "$CIRCLE_PROJECT_USERNAME"; setPublicVar CI_REPO_OWNER "$CIRCLE_PROJECT_USERNAME";
setPublicVar CI_PR_REPONAME "$CIRCLE_PR_REPONAME";
setPublicVar CI_PR_USERNAME "$CIRCLE_PR_USERNAME";
####################################################################################################
# Define "lazy" PUBLIC environment variables for CircleCI.
# (I.e. functions to set an environment variable when called.)
####################################################################################################
createPublicVarSetter CI_STABLE_BRANCH "\$(npm info @angular/core dist-tags.latest | sed -r 's/^\\s*([0-9]+\\.[0-9]+)\\.[0-9]+.*$/\\1.x/')";
#################################################################################################### ####################################################################################################
@ -46,68 +27,9 @@ createPublicVarSetter CI_STABLE_BRANCH "\$(npm info @angular/core dist-tags.late
#################################################################################################### ####################################################################################################
setSecretVar CI_SECRET_AIO_DEPLOY_FIREBASE_TOKEN "$AIO_DEPLOY_TOKEN"; setSecretVar CI_SECRET_AIO_DEPLOY_FIREBASE_TOKEN "$AIO_DEPLOY_TOKEN";
setSecretVar CI_SECRET_PAYLOAD_FIREBASE_TOKEN "$ANGULAR_PAYLOAD_TOKEN"; setSecretVar CI_SECRET_PAYLOAD_FIREBASE_TOKEN "$ANGULAR_PAYLOAD_TOKEN";
# Defined in https://angular-team.slack.com/apps/A0F7VRE7N-circleci.
setSecretVar CI_SECRET_SLACK_CARETAKER_WEBHOOK_URL "$SLACK_CARETAKER_WEBHOOK_URL";
#################################################################################################### # Source `$BASH_ENV` to make the variables available immediately.
# Define SauceLabs environment variables for CircleCI.
####################################################################################################
setPublicVar SAUCE_USERNAME "angular-framework";
setSecretVar SAUCE_ACCESS_KEY "0c731274ed5f-cbc9-16f4-021a-9835e39f";
# TODO(josephperrott): Remove environment variables once all saucelabs tests are via bazel method.
setPublicVar SAUCE_LOG_FILE /tmp/angular/sauce-connect.log
setPublicVar SAUCE_READY_FILE /tmp/angular/sauce-connect-ready-file.lock
setPublicVar SAUCE_PID_FILE /tmp/angular/sauce-connect-pid-file.lock
setPublicVar SAUCE_TUNNEL_IDENTIFIER "angular-framework-${CIRCLE_BUILD_NUM}-${CIRCLE_NODE_INDEX}"
# Amount of seconds we wait for sauceconnect to establish a tunnel instance. In order to not
# acquire CircleCI instances for too long if sauceconnect failed, we need a connect timeout.
setPublicVar SAUCE_READY_FILE_TIMEOUT 120
####################################################################################################
# Define environment variables for the `angular/components` repo unit tests job.
####################################################################################################
# We specifically use a directory within "/tmp" here because we want the cloned repo to be
# completely isolated from angular/angular in order to avoid any bad interactions between
# their separate build setups. **NOTE**: When updating the temporary directory, also update
# the `save_cache` path configuration in `config.yml`
setPublicVar COMPONENTS_REPO_TMP_DIR "/tmp/angular-components-repo"
setPublicVar COMPONENTS_REPO_URL "https://github.com/angular/components.git"
setPublicVar COMPONENTS_REPO_BRANCH "master"
# **NOTE**: When updating the commit SHA, also update the cache key in the CircleCI `config.yml`.
setPublicVar COMPONENTS_REPO_COMMIT "09e68db8ed5b1253f2fe38ff954ef0df019fc25a"
####################################################################################################
# Decrypt GCP Credentials and store them as the Google default credentials.
####################################################################################################
mkdir -p "$HOME/.config/gcloud";
openssl aes-256-cbc -d -in "${projectDir}/.circleci/gcp_token" \
-md md5 -k "$CIRCLE_PROJECT_REPONAME" -out "$HOME/.config/gcloud/application_default_credentials.json"
####################################################################################################
# Set bazel configuration for CircleCI runs.
####################################################################################################
cp "${projectDir}/.circleci/bazel.linux.rc" "$HOME/.bazelrc";
####################################################################################################
# Create shell script in /tmp for Bazel actions to access CI envs without
# busting the cache. Used by payload-size.sh script in integration tests.
####################################################################################################
readonly bazelVarEnv="/tmp/bazel-ci-env.sh"
echo "# Setup by /.circle/env.sh" > $bazelVarEnv
echo "export PROJECT_ROOT=\"${PROJECT_ROOT}\";" >> $bazelVarEnv
echo "export CI_BRANCH=\"${CI_BRANCH}\";" >> $bazelVarEnv
echo "export CI_BUILD_URL=\"${CI_BUILD_URL}\";" >> $bazelVarEnv
echo "export CI_COMMIT=\"${CI_COMMIT}\";" >> $bazelVarEnv
echo "export CI_COMMIT_RANGE=\"${CI_COMMIT_RANGE}\";" >> $bazelVarEnv
echo "export CI_PULL_REQUEST=\"${CI_PULL_REQUEST}\";" >> $bazelVarEnv
echo "export CI_REPO_NAME=\"${CI_REPO_NAME}\";" >> $bazelVarEnv
echo "export CI_REPO_OWNER=\"${CI_REPO_OWNER}\";" >> $bazelVarEnv
echo "export CI_SECRET_PAYLOAD_FIREBASE_TOKEN=\"${CI_SECRET_PAYLOAD_FIREBASE_TOKEN}\";" >> $bazelVarEnv
####################################################################################################
####################################################################################################
## Source `$BASH_ENV` to make the variables available immediately. ##
## ***NOTE: This must remain the the last action in this script*** ##
####################################################################################################
####################################################################################################
source $BASH_ENV; source $BASH_ENV;

Binary file not shown.

View File

@ -60,15 +60,14 @@ if (require.resolve === module) {
// Helpers // Helpers
function _main(args) { function _main(args) {
triggerWebhook(...args) triggerWebhook(...args).
.then( then(({statusCode, responseText}) => (200 <= statusCode && statusCode < 400) ?
({statusCode, responseText}) => (200 <= statusCode && statusCode < 400) ? console.log(`Status: ${statusCode}\n${responseText}`) :
console.log(`Status: ${statusCode}\n${responseText}`) : Promise.reject(new Error(`Request failed (status: ${statusCode}): ${responseText}`))).
Promise.reject(new Error(`Request failed (status: ${statusCode}): ${responseText}`))) catch(err => {
.catch(err => { console.error(err);
console.error(err); process.exit(1);
process.exit(1); });
});
} }
function postJson(url, data) { function postJson(url, data) {
@ -78,12 +77,15 @@ function postJson(url, data) {
const statusCode = res.statusCode || -1; const statusCode = res.statusCode || -1;
let responseText = ''; let responseText = '';
res.on('error', reject) res.
.on('data', d => responseText += d) on('error', reject).
.on('end', () => resolve({statusCode, responseText})); on('data', d => responseText += d).
on('end', () => resolve({statusCode, responseText}));
}; };
request(url, opts, onResponse).on('error', reject).end(JSON.stringify(data)); request(url, opts, onResponse).
on('error', reject).
end(JSON.stringify(data));
}); });
} }

View File

@ -1,56 +0,0 @@
# Install Bazel pre-reqs on Windows
# https://docs.bazel.build/versions/master/install-windows.html
# https://docs.bazel.build/versions/master/windows.html
# Install MSYS2 and packages
choco install msys2 --version 20180531.0.0 --no-progress --package-parameters "/NoUpdate"
C:\tools\msys64\usr\bin\bash.exe -l -c "pacman --needed --noconfirm -S zip unzip patch diffutils git"
# Add PATH modifications to the Powershell profile. This is the win equivalent of .bash_profile.
# https://docs.microsoft.com/en-us/previous-versions//bb613488(v=vs.85)
new-item -path $profile -itemtype file -force
# Paths for nodejs, npm, yarn, and msys2. Use single quotes to prevent interpolation.
# Add before the original path to use msys2 instead of the installed gitbash.
Add-Content $profile '$Env:path = "${Env:ProgramFiles}\nodejs\;C:\Users\circleci\AppData\Roaming\npm\;${Env:ProgramFiles(x86)}\Yarn\bin\;C:\Users\circleci\AppData\Local\Yarn\bin\;C:\tools\msys64\usr\bin\;" + $Env:path'
# Environment variables for Bazel
Add-Content $profile '$Env:BAZEL_SH = "C:\tools\msys64\usr\bin\bash.exe"'
# Get the bazelisk version devdep and store it in a global var for use in the circleci job.
$bazeliskVersion = & ${Env:ProgramFiles}\nodejs\node.exe -e "console.log(require('./package.json').devDependencies['@bazel/bazelisk'])"
# This is a tricky situation: we want $bazeliskVersion to be evaluated but not $Env:BAZELISK_VERSION.
# Formatting works https://stackoverflow.com/questions/32127583/expand-variable-inside-single-quotes
$bazeliskVersionGlobalVar = '$Env:BAZELISK_VERSION = "{0}"' -f $bazeliskVersion
Add-Content $profile $bazeliskVersionGlobalVar
# Remove the CircleCI checkout SSH override, because it breaks cloning repositories through Bazel.
# See https://circleci.com/gh/angular/angular/401454 for an example.
# TODO: is this really needed? Maybe there's a better way. It doesn't happen on Linux or on Codefresh.
git config --global --unset url.ssh://git@github.com.insteadOf
####################################################################################################
# Decrypt GCP Credentials and store them as the Google default credentials.
####################################################################################################
mkdir ${env:APPDATA}\gcloud
openssl aes-256-cbc -d -in .circleci\gcp_token -md md5 -out "$env:APPDATA\gcloud\application_default_credentials.json" -k "$env:CIRCLE_PROJECT_REPONAME"
####################################################################################################
# Set bazel configuration for CircleCI runs.
####################################################################################################
copy .circleci\bazel.windows.rc ${Env:USERPROFILE}\.bazelrc
####################################################################################################
# Install specific version of node.
####################################################################################################
choco install nodejs --version 12.14.1 --no-progress
# These Bazel prereqs aren't needed because the CircleCI image already includes them.
# choco install yarn --version 1.16.0 --no-progress
# choco install vcredist2015 --version 14.0.24215.20170201
# We don't need VS Build Tools for the tested bazel targets.
# If it's needed again, uncomment these lines.
# VS Build Tools are needed for Bazel C++ targets (like com_google_protobuf)
# choco install visualstudio2019buildtools --version 16.1.2.0 --no-progress --package-parameters "--add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Component.VC.Tools.x86.x64 --add Microsoft.Component.VC.Runtime.UCRTSDK --add Microsoft.VisualStudio.Component.Windows10SDK.17763"
# Add-Content $profile '$Env:BAZEL_VC = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\2019\BuildTools\VC\"'
# Python is needed for Bazel Python targets
# choco install python --version 3.5.1 --no-progress

View File

@ -1,31 +0,0 @@
# VSCode Remote Development - Developing inside a Containers
This folder contains configuration files that can be used to opt into working on this repository in a [Docker container](https://www.docker.com/resources/what-container) via [VSCode](https://code.visualstudio.com/)'s Remote Development feature (see below).
Info on remote development and developing inside a container with VSCode:
- [VSCode: Remote Development](https://code.visualstudio.com/docs/remote/remote-overview)
- [VSCode: Developing inside a Container](https://code.visualstudio.com/docs/remote/containers)
- [VSCode: Remote Development FAQ](https://code.visualstudio.com/docs/remote/faq)
## Usage
_Prerequisite: [Install Docker](https://docs.docker.com/install) on your local environment._
To get started, read and follow the instuctions in [Developing inside a Container](https://code.visualstudio.com/docs/remote/containers). The [.devcontainer/](.) directory contains pre-configured `devcontainer.json` and `Dockerfile` files, which you can use to set up remote development with a docker container.
In a nutshell, you need to:
- Install the [Remote - Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) extension.
- Copy [recommended-Dockerfile](./recommended-Dockerfile) to `Dockerfile` (and optionally tweak to suit your needs).
- Copy [recommended-devcontainer.json](./recommended-devcontainer.json) to `devcontainer.json` (and optionally tweak to suit your needs).
- Open VSCode and bring up the [Command Palette](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette).
- Type `Remote-Containers: Open Folder in Container` and choose your local clone of [angular/angular](https://github.com/angular/angular).
The `.devcontainer/devcontainer.json` and `.devcontainer/Dockerfile` files are ignored by git, so you can have your own local versions. We may occasionally update the template files ([recommended-devcontainer.json](./recommended-devcontainer.json), [recommended-Dockerfile](./recommended-Dockerfile)), in which case you will need to manually update your local copies (if desired).
## Updating `recommended-devcontainer.json` and `recommended-Dockerfile`
You can update and commit the recommended config files (which people use as basis for their local configs), if you find that something is broken, out-of-date or can be improved.
Please, keep in mind that any changes you make will potentially be used by many people on different environments. Try to keep these config files cross-platform compatible and free of personal preferences.

View File

@ -1,24 +0,0 @@
# Image metadata and config.
FROM circleci/node:10-browsers # Ideally, the image version should be what we use on CI.
# See `executors > browsers-executor` in `.circleci/config.yml`.
LABEL name="Angular dev environment" \
description="This image can be used to create a dev environment for building Angular." \
vendor="angular" \
version="1.0"
EXPOSE 4000 4200 4433 5000 8080 9876
# Switch to `root` (CircleCI images use `circleci` as the user).
USER root
# Configure `Node.js`/`npm` and install utilities.
RUN npm config --global set user root
RUN npm install --global yarn@latest # Ideally, the version should be what we use on CI.
# See `commands > overwrite_yarn` in `.circleci/config.yml`.
# Go! (And keep going.)
CMD ["tail", "--follow", "/dev/null"]

View File

@ -1,16 +0,0 @@
// Reference: https://code.visualstudio.com/docs/remote/containers#_devcontainerjson-reference
{
"name": "Angular dev container",
"dockerFile": "Dockerfile",
"appPort": [4000, 4200, 4433, 5000, 8080, 9876],
"postCreateCommand": "yarn install",
"extensions": [
"devondcarew.bazel-code",
"gkalpak.aio-docs-utils",
"ms-vscode.vscode-typescript-tslint-plugin",
"xaver.clang-format",
// The following extensions are useful when working on angular.io (i.e. inside the `aio/` directory).
//"angular.ng-template",
//"dbaeumer.vscode-eslint",
],
}

3
.gitattributes vendored
View File

@ -5,8 +5,5 @@
*.js eol=lf *.js eol=lf
*.ts eol=lf *.ts eol=lf
# API guardian patch must always use LF for tests to work
*.patch eol=lf
# Must keep Windows line ending to be parsed correctly # Must keep Windows line ending to be parsed correctly
scripts/windows/packages.txt eol=crlf scripts/windows/packages.txt eol=crlf

67
.github/ISSUE_TEMPLATE/1-bug-report.md vendored Normal file
View File

@ -0,0 +1,67 @@
---
name: "\U0001F41EBug report"
about: Report a bug in the Angular Framework
---
<!--🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅
Oh hi there! 😄
To expedite issue processing please search open and closed issues before submitting a new one.
Existing issues often contain information about workarounds, resolution, or progress updates.
🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅-->
# 🐞 bug report
### Affected Package
<!-- Can you pin-point one or more @angular/* packages as the source of the bug? -->
<!-- ✍edit: --> The issue is caused by package @angular/....
### Is this a regression?
<!-- Did this behavior use to work in the previous version? -->
<!-- ✍️--> Yes, the previous version in which this bug was not present was: ....
### Description
<!-- ✍️--> A clear and concise description of the problem...
## 🔬 Minimal Reproduction
<!--
Please create and share minimal reproduction of the issue starting with this template: https://stackblitz.com/fork/angular-issue-repro2
-->
<!-- ✍️--> https://stackblitz.com/...
<!--
If StackBlitz is not suitable for reproduction of your issue, please create a minimal GitHub repository with the reproduction of the issue. Share the link to the repo below along with step-by-step instructions to reproduce the problem, as well as expected and actual behavior.
Issues that don't have enough info and can't be reproduced will be closed.
You can read more about issue submission guidelines here: https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-submitting-an-issue
-->
## 🔥 Exception or Error
<pre><code>
<!-- If the issue is accompanied by an exception or an error, please share it below: -->
<!-- ✍️-->
</code></pre>
## 🌍 Your Environment
**Angular Version:**
<pre><code>
<!-- run `ng version` and paste output below -->
<!-- ✍️-->
</code></pre>
**Anything else relevant?**
<!--Is this a browser specific issue? If so, please specify the browser and version. -->
<!--Do any of these matter: operating system, IDE, package manager, HTTP server, ...? If so, please mention it below. -->

View File

@ -0,0 +1,32 @@
---
name: "\U0001F680Feature request"
about: Suggest a feature for Angular Framework
---
<!--🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅
Oh hi there! 😄
To expedite issue processing please search open and closed issues before submitting a new one.
Existing issues often contain information about workarounds, resolution, or progress updates.
🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅-->
# 🚀 feature request
### Relevant Package
<!-- Can you pin-point one or more @angular/* packages the are relevant for this feature request? -->
<!-- ✍edit: --> This feature request is for @angular/....
### Description
<!-- ✍️--> A clear and concise description of the problem or missing capability...
### Describe the solution you'd like
<!-- ✍️--> If you have a solution in mind, please describe it.
### Describe alternatives you've considered
<!-- ✍️--> Have you considered any alternative solutions or workarounds?

55
.github/ISSUE_TEMPLATE/3-docs-bug.md vendored Normal file
View File

@ -0,0 +1,55 @@
---
name: "📚 Docs or angular.io issue report"
about: Report an issue in Angular's documentation or angular.io application
---
<!--🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅
Oh hi there! 😄
To expedite issue processing please search open and closed issues before submitting a new one.
Existing issues often contain information about workarounds, resolution, or progress updates.
🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅-->
# 📚 Docs or angular.io bug report
### Description
<!--edit:--> A clear and concise description of the problem...
## 🔬 Minimal Reproduction
### What's the affected URL?**
<!--edit:--> https://angular.io/...
### Reproduction Steps**
<!-- If applicable please list the steps to take to reproduce the issue -->
<!--edit:-->
### Expected vs Actual Behavior**
<!-- If applicable please describe the difference between the expected and actual behavior after following the repro steps. -->
<!--edit:-->
## 📷Screenshot
<!-- Often a screenshot can help to capture the issue better than a long description. -->
<!--upload a screenshot:-->
## 🔥 Exception or Error
<pre><code>
<!-- If the issue is accompanied by an exception or an error, please share it below: -->
<!-- ✍️-->
</code></pre>
## 🌍 Your Environment
### Browser info
<!--Is this a browser specific issue? If so, please specify the device, browser, and version. -->
### Anything else relevant?
<!--Please provide additional info if necessary. -->

View File

@ -0,0 +1,11 @@
---
name: ⚠️ Security issue disclosure
about: Report a security issue in Angular Framework, Material, or CLI
---
🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑
Please read https://angular.io/guide/security#report-issues on how to disclose security related issues.
🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑

View File

@ -0,0 +1,16 @@
---
name: "❓Support request"
about: Questions and requests for support
---
🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑
Please do not file questions or support requests on the GitHub issues tracker.
You can get your questions answered using other communication channels. Please see:
https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
Thank you!
🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑

13
.github/ISSUE_TEMPLATE/6-angular-cli.md vendored Normal file
View File

@ -0,0 +1,13 @@
---
name: "\U0001F6E0Angular CLI"
about: Issues and feature requests for Angular CLI
---
🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑
Please file any Angular CLI issues at: https://github.com/angular/angular-cli/issues/new
For the time being, we keep Angular CLI issues in a separate repository.
🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑

View File

@ -0,0 +1,13 @@
---
name: "\U0001F48EAngular Material"
about: Issues and feature requests for Angular Material
---
🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑
Please file any Angular Material issues at: https://github.com/angular/material2/issues/new
For the time being, we keep Angular Material issues in a separate repository.
🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑

View File

@ -1,22 +0,0 @@
---
name: "📚Traducir doc al español"
about: Solicitud para traducir ciertos docs al español
---
📚Traducir: <!-- ✍️ editar: --> creating-libraries.md
<!--🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅
Traducción de la documentación oficial de Angular a español
🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅🔅-->
## Nombre del archivo:
<!-- ✍️ editar: --> creating-libraries.md
## Ruta donde se encuentra el archivo dentro del proyecto de Angular
<!-- ✍️ editar: --> https://github.com/angular-hispano/angular/blob/master/aio/content/guide/creating-libraries.md

View File

@ -1,35 +1,43 @@
## Lista de Verificación del PR ## PR Checklist
Comprueba si tu PR cumple los siguientes requisitos: Please check if your PR fulfills the following requirements:
- [ ] El mensaje de commit esta conforme con [nuestras reglas](https://github.com/angular-hispano/angular/blob/master/CONTRIBUTING.md#-formato-para-el-mensaje-de-los-commits) - [ ] The commit message follows our guidelines: https://github.com/angular/angular/blob/master/CONTRIBUTING.md#commit
- [ ] Probe los cambios que agregué (arreglo de bugs / funcionalidades) - [ ] Tests for the changes have been added (for bug fixes / features)
- [ ] Revisé previamente las traducciones o cambios de contenido - [ ] Docs have been added / updated (for bug fixes / features)
- [ ] Consulté el [diccionario de términos](https://github.com/angular-hispano/angular/blob/master/aio/diccionario-de-términos.md) en español
- [ ] He creado dos archivos con la extensión correspondiente(.en.md para el archivo en inglés y .md para el Archivo en español)
- [ ] He enlazado el commit con el issue correspondiente <!-- ejemplo Fixes #X -->
## Tipo de PR ## PR Type
¿Qué tipo de cambio introduce este PR? What kind of change does this PR introduce?
<!-- Marca con una "x" las opciones que aplican. --> <!-- Please check the one that applies to this PR using "x". -->
- [ ] Bugfix - [ ] Bugfix
- [ ] Funcionalidad - [ ] Feature
- [ ] Actualización de el estilo del código (formato, variables locales) - [ ] Code style update (formatting, local variables)
- [ ] Refactorización (no cambios en la funcionalidad, no cambios en el api) - [ ] Refactoring (no functional changes, no api changes)
- [ ] Cambios relacionados al build - [ ] Build related changes
- [ ] Cambios relacionados al CI (Integración continua) - [ ] CI related changes
- [ ] Cambios en el contenido de la documentación - [ ] Documentation content changes
- [ ] Cambios en la aplicación / infraestructura de angular.io - [ ] angular.io application / infrastructure changes
- [ ] Otro... Por favor describe la: - [ ] Other... Please describe:
## ¿Cuál es el comportamiento actual?
<!-- Describe el comportamiento actual que está modificando o vincule a un problema relevante.
-->
## ¿Cuál es el nuevo comportamiento? ## What is the current behavior?
<!-- <!-- Please describe the current behavior that you are modifying, or link to a relevant issue. -->
Ejemplo: Archivo en inglés traducido al español
--> Issue Number: N/A
## What is the new behavior?
## Does this PR introduce a breaking change?
- [ ] Yes
- [ ] No
<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. -->
## Other information

View File

@ -30,36 +30,32 @@ merge:
# text to show when the status is success # text to show when the status is success
successDesc: "Does not affect google3" successDesc: "Does not affect google3"
# link to use for the details # link to use for the details
url: "http://go/angular/g3sync" url: "http://go/angular-g3sync"
# list of patterns to check for the files changed by the PR # list of patterns to check for the files changed by the PR
# this list must be manually kept in sync with google3/third_party/javascript/angular2/copy.bara.sky # this list must be manually kept in sync with google3/third_party/javascript/angular2/copy.bara.sky
include: include:
- "LICENSE" - "LICENSE"
- "modules/benchmarks/**" - "modules/**"
- "modules/system.d.ts"
- "packages/**" - "packages/**"
# list of patterns to ignore for the files changed by the PR # list of patterns to ignore for the files changed by the PR
exclude: exclude:
- "packages/*" - "packages/*"
- "packages/bazel/*" - "packages/bazel/*"
- "packages/bazel/src/api-extractor/**"
- "packages/bazel/src/builders/**" - "packages/bazel/src/builders/**"
- "packages/bazel/src/ng_package/**" - "packages/bazel/src/ng_package/**"
- "packages/bazel/src/protractor/**" - "packages/bazel/src/protractor/**"
- "packages/bazel/src/schematics/**" - "packages/bazel/src/schematics/**"
- "packages/compiler-cli/ngcc/**" - "packages/compiler-cli/src/ngcc/**"
- "packages/docs/**" - "packages/docs/**"
- "packages/elements/schematics/**" - "packages/elements/schematics/**"
- "packages/examples/**" - "packages/examples/**"
- "packages/language-service/**" - "packages/language-service/**"
- "packages/localize/**"
- "packages/private/**" - "packages/private/**"
- "packages/service-worker/**" - "packages/service-worker/**"
- "**/.gitignore" - "**/.gitignore"
- "**/.gitkeep" - "**/.gitkeep"
- "**/yarn.lock" - "**/yarn.lock"
- "**/package.json" - "**/package.json"
- "**/third_party/**"
- "**/tsconfig-build.json" - "**/tsconfig-build.json"
- "**/tsconfig.json" - "**/tsconfig.json"
- "**/rollup.config.js" - "**/rollup.config.js"
@ -67,10 +63,6 @@ merge:
- "**/*.md" - "**/*.md"
- "packages/**/integrationtest/**" - "packages/**/integrationtest/**"
- "packages/**/test/**" - "packages/**/test/**"
- "packages/zone.js/*"
- "packages/zone.js/doc/**"
- "packages/zone.js/example/**"
- "packages/zone.js/scripts/**"
# comment that will be added to a PR when there is a conflict, leave empty or set to false to disable # comment that will be added to a PR when there is a conflict, leave empty or set to false to disable
mergeConflictComment: "Hi @{{PRAuthor}}! This PR has merge conflicts due to recent upstream merges. mergeConflictComment: "Hi @{{PRAuthor}}! This PR has merge conflicts due to recent upstream merges.
@ -89,7 +81,7 @@ merge:
# require that the PR has reviews from all requested reviewers # require that the PR has reviews from all requested reviewers
# #
# This enables us to request reviews from both eng and tech writers, or multiple eng folks, and prevents accidental merges. # This enables us to request reviews from both eng and tech writers, or multiple eng folks, and prevents accidental merges.
# Rather than merging PRs with pending reviews, if all approvals are obtained and additional reviews are not needed, any pending reviewers should be removed via GitHub UI (this also leaves an audit trail behind these decisions). # Rather than merging PRs with pending reviews, if all PullApprove requirements are satisfied and additional reviews are not needed pending reviewers should be removed via GitHub UI (this also leaves an audit trail behind these decisions).
requireReviews: true, requireReviews: true,
# whether the PR shouldn't have a conflict with the base branch # whether the PR shouldn't have a conflict with the base branch
@ -109,14 +101,10 @@ merge:
# list of PR statuses that need to be successful # list of PR statuses that need to be successful
requiredStatuses: requiredStatuses:
- "continuous-integration/travis-ci/pr"
- "code-review/pullapprove"
- "ci/circleci: build" - "ci/circleci: build"
- "ci/circleci: lint" - "ci/circleci: lint"
- "ci/circleci: publish_snapshot"
- "ci/angular: size"
- "cla/google"
- "google3"
- "pullapprove"
# the comment that will be added when the merge label is added despite failing checks, leave empty or set to false to disable # the comment that will be added when the merge label is added despite failing checks, leave empty or set to false to disable
# {{MERGE_LABEL}} will be replaced by the value of the mergeLabel option # {{MERGE_LABEL}} will be replaced by the value of the mergeLabel option
@ -154,12 +142,6 @@ triage:
- -
- "type: RFC / Discussion / question" - "type: RFC / Discussion / question"
- "comp: *" - "comp: *"
-
- "type: confusing"
- "comp: *"
-
- "type: use-case"
- "comp: *"
# options for the triage PR plugin # options for the triage PR plugin
triagePR: triagePR:
@ -180,10 +162,3 @@ triagePR:
- "effort*" - "effort*"
- "risk*" - "risk*"
- "comp: *" - "comp: *"
# options for rerunning CI
rerunCircleCI:
# set to true to disable
disabled: false
# the label which when added triggers a rerun of the default CircleCI workflow
triggerRerunLabel: "PR action: rerun CI at HEAD"

View File

@ -1,15 +0,0 @@
name: Lock closed inactive issues
on:
schedule:
# Run at 16:00 every day
- cron: '0 16 * * *'
jobs:
lock_closed:
if: github.repository == 'angular/angular'
runs-on: ubuntu-latest
steps:
- uses: angular/dev-infra/github-actions/lock-closed@66462f6
with:
lock-bot-key: ${{ secrets.LOCK_BOT_PRIVATE_KEY }}

21
.gitignore vendored
View File

@ -1,28 +1,22 @@
.DS_STORE .DS_STORE
/dist/ /dist/
/bazel-out /bazel-*
/integration/bazel/bazel-* /integration/bazel/bazel-*
*.log e2e_test.*
node_modules node_modules
bower_components
tools/gulp-tasks/cldr/cldr-data/
# Include when developing application packages. # Include when developing application packages.
pubspec.lock pubspec.lock
.c9 .c9
.idea/ .idea/
.devcontainer/*
!.devcontainer/README.md
!.devcontainer/recommended-devcontainer.json
!.devcontainer/recommended-Dockerfile
.settings/ .settings/
.vscode/launch.json
.vscode/settings.json
.vscode/tasks.json
*.swo *.swo
modules/.settings modules/.settings
.vscode
modules/.vscode modules/.vscode
.vimrc
.nvimrc
# Don't check in secret files # Don't check in secret files
*secret.js *secret.js
@ -40,8 +34,3 @@ yarn-error.log
# User specific bazel settings # User specific bazel settings
.bazelrc.user .bazelrc.user
.notes.md
baseline.json
# Ignore .history for the xyz.local-history VSCode extension
.history

View File

@ -1,145 +0,0 @@
<type>(<scope>): <summary>
<Describe the motivation behind this change - explain WHY you are making this change. Wrap all lines
at 100 characters.>
Fixes #<issue number>
# ────────────────────────────────────────── 100 chars ────────────────────────────────────────────┤
# Example Commit Messages
# =======================
# ─── Example: Simple refactor ────────────────────────────────────────────────────────────────────┤
# refactor(core): rename refreshDynamicEmbeddedViews to refreshEmbeddedViews
#
# Improve code readability. The original name no longer matches how the function is used.
# ─────────────────────────────────────────────────────────────────────────────────────────────────┤
# ─── Example: Simple docs change ─────────────────────────────────────────────────────────────────┤
# docs: clarify the service limitation in providers.md guide
#
# Fixes #36332
# ─────────────────────────────────────────────────────────────────────────────────────────────────┤
# ─── Example: A bug fix ──────────────────────────────────────────────────────────────────────────┤
# fix(ngcc): ensure lockfile is removed when `analyzeFn` fails
#
# Previously an error thrown in the `analyzeFn` would cause the ngcc process to exit immediately
# without removing the lockfile, and potentially before the unlocker process had been successfully
# spawned resulting in the lockfile being orphaned and left behind.
#
# Now we catch these errors and remove the lockfile as needed.
# ─────────────────────────────────────────────────────────────────────────────────────────────────┤
# ─── Example: Breaking change ────────────────────────────────────────────────────────────────────┤
# feat(bazel): simplify ng_package by dropping esm5 and fesm5
#
# esm5 and fesm5 distributions are no longer needed and have been deprecated in the past.
#
# https://v9.angular.io/guide/deprecations#esm5-and-fesm5-code-formats-in-angular-npm-packages
#
# This commit modifies ng_package to no longer distribute these two formats in npm packages built by
# ng_package (e.g. @angular/core).
#
# This commit intentionally doesn't fully clean up the ng_package rule to remove all traces of esm5
# and fems5 build artifacts as that is a bigger cleanup and currently we are narrowing down the
# scope of this change to the MVP needed for v10, which in this case is 'do not put esm5 and fesm5'
# into the npm packages.
#
# More cleanup to follow: https://angular-team.atlassian.net/browse/FW-2143
#
# BREAKING CHANGE: esm5 and fesm5 format is no longer distributed in Angular's npm packages e.g.
# @angular/core
#
# Angular CLI will automatically downlevel the code to es5 if differential loading is enabled in the
# Angular project, so no action is required from Angular CLI users.
#
# If you are not using Angular CLI to build your application or library, and you need to be able to
# build es5 artifacts, then you will need to downlevel the distributed Angular code to es5 on your
# own.
#
#
# Fixes #1234
# ─────────────────────────────────────────────────────────────────────────────────────────────────┤
# Angular Commit Message Format
# =============================
#
# The full specification of the Angular Commit Message Format can be found at
# https://github.com/angular/angular/blob/master/CONTRIBUTING.md#commit
#
# The following is an excerpt of the specification with the most commonly needed info.
#
# Each commit message consists of a *header*, a *body*, and a *footer*.
#
# <header>
# <BLANK LINE>
# <body>
# <BLANK LINE>
# <footer>
#
# The header is mandatory.
#
# The body is mandatory for all commits except for those of scope "docs". When the body is required
# it must be at least 20 characters long.
#
# The footer is optional.
#
# Any line of the commit message cannot be longer than 100 characters.
#
#
# Commit Message Header
# ---------------------
#
# <type>(<scope>): <short summary>
# │ │ │
# │ │ └─⫸ Summary in present tense. Not capitalized. No period at the end.
# │ │
# │ └─⫸ Commit Scope: animations|bazel|benchpress|common|compiler|compiler-cli|core|
# │ elements|forms|http|language-service|localize|platform-browser|
# │ platform-browser-dynamic|platform-server|platform-webworker|
# │ platform-webworker-dynamic|router|service-worker|upgrade|zone.js|
# │ packaging|changelog|dev-infra|docs-infra|migrations|ngcc|ve
# │ https://github.com/angular/angular/blob/master/CONTRIBUTING.md#scope
# │
# └─⫸ Commit Type: build|ci|docs|feat|fix|perf|refactor|style|test
# https://github.com/angular/angular/blob/master/CONTRIBUTING.md#type
#
#
# Commit Message Body
# ---------------------
#
# Just as in the summary, use the imperative, present tense: "fix" not "fixed" nor "fixes".
#
# Explain the motivation for the change in the commit message body. This commit message should
# explain WHY you are making the change. You can include a comparison of the previous behavior with
# the new behavior in order to illustrate the impact of the change.
#
#
# Commit Message Footer
# ---------------------
#
# The footer can contain information about breaking changes and is also the place to reference
# GitHub issues, Jira tickets, and other PRs that this commit closes or is related to.
#
# ```
# BREAKING CHANGE: <breaking change summary>
# <BLANK LINE>
# <breaking change description + migration instructions>
# <BLANK LINE>
# <BLANK LINE>
# Fixes #<issue number>
# ```
#
# Breaking Change section should start with the phrase "BREAKING CHANGE: " followed by a summary of
# the breaking change, a blank line, and a detailed description of the breaking change that also
# includes migration instructions.
#

View File

@ -1,53 +0,0 @@
import {CommitMessageConfig} from '../dev-infra/commit-message/config';
/**
* The configuration for `ng-dev commit-message` commands.
*/
export const commitMessage: CommitMessageConfig = {
maxLineLength: 120,
minBodyLength: 20,
minBodyLengthTypeExcludes: ['docs', 'upstream'],
types: [
'build',
'ci',
'docs',
'feat',
'fix',
'perf',
'refactor',
'release',
'style',
'test',
'upstream',
],
scopes: [
'animations',
'bazel',
'benchpress',
'changelog',
'common',
'compiler',
'compiler-cli',
'core',
'dev-infra',
'docs-infra',
'elements',
'forms',
'http',
'language-service',
'localize',
'migrations',
'ngcc',
'packaging',
'platform-browser',
'platform-browser-dynamic',
'platform-server',
'platform-webworker',
'platform-webworker-dynamic',
'router',
'service-worker',
'upgrade',
've',
'zone.js',
]
};

View File

@ -1,11 +0,0 @@
import {commitMessage} from './commit-message';
import {format} from './format';
import {github} from './github';
import {merge} from './merge';
module.exports = {
commitMessage,
format,
github,
merge,
};

View File

@ -1,22 +0,0 @@
import {FormatConfig} from '../dev-infra/format/config';
/**
* Configuration for the `ng-dev format` command.
*/
export const format: FormatConfig = {
'clang-format': {
'matchers': [
'**/*.{js,ts}',
// TODO: burn down format failures and remove aio and integration exceptions.
'!aio/**',
'!integration/**',
// Both third_party and .yarn are directories containing copied code which should
// not be modified.
'!third_party/**',
'!.yarn/**',
// Do not format d.ts files as they are generated
'!**/*.d.ts',
]
},
'buildifier': true
};

View File

@ -1,15 +0,0 @@
# The file is inert unless it's explicitly included into the local git config via:
#
# ```
# git config --add include.path '../.ng-dev/gitconfig'
# ```
#
# Calling that command will append the following into `.git/config` of the current git workspace
# (i.e. $GIT_DIR, typically `angular/.git/config`):
#
# ```
# [include]
# path = ../.ng-dev/gitconfig
# ```
[commit]
template = .gitmessage

View File

@ -1,11 +0,0 @@
import {GithubConfig} from '../dev-infra/utils/config';
/**
* Github configuration for the `ng-dev` command. This repository is used as
* remote for the merge script and other utilities like `ng-dev pr rebase`.
*/
export const github: GithubConfig = {
owner: 'angular',
name: 'angular'
};

View File

@ -1,38 +0,0 @@
import {MergeConfig} from '../dev-infra/pr/merge/config';
/**
* Configuration for the merge tool in `ng-dev`. This sets up the labels which
* are respected by the merge script (e.g. the target labels).
*/
export const merge = (): MergeConfig => {
// TODO: resume dynamically determining patch branch
const patch = '10.0.x';
return {
githubApiMerge: false,
claSignedLabel: 'cla: yes',
mergeReadyLabel: /^PR action: merge(-assistance)?/,
caretakerNoteLabel: 'PR action: merge-assistance',
commitMessageFixupLabel: 'commit message fixup',
labels: [
{
pattern: 'PR target: master-only',
branches: ['master'],
},
{
pattern: 'PR target: patch-only',
branches: [patch],
},
{
pattern: 'PR target: master & patch',
branches: ['master', patch],
},
],
requiredBaseCommits: {
// PRs that target either `master` or the patch branch, need to be rebased
// on top of the latest commit message validation fix.
// These SHAs are the commits that update the required license text in the header.
'master': '5aeb9a4124922d8ac08eb73b8f322905a32b0b3a',
[patch]: '27b95ba64a5d99757f4042073fd1860e20e3ed24'
},
};
};

2
.nvmrc
View File

@ -1 +1 @@
12.14.1 10.9.0

File diff suppressed because it is too large Load Diff

66
.travis.yml Normal file
View File

@ -0,0 +1,66 @@
language: node_js
sudo: false
dist: trusty
node_js:
- '10.9.0'
addons:
# firefox: "38.0"
apt:
sources:
# needed to install g++ that is used by npms's native modules
- ubuntu-toolchain-r-test
packages:
# needed to install g++ that is used by npms's native modules
- g++-4.8
branches:
except:
- g3
cache:
yarn: true
directories:
- ./node_modules
- ./.chrome/chromium
- ./aio/node_modules
env:
global:
# GITHUB_TOKEN_ANGULAR=<github token, a personal access token of the angular-builds account, account access in valentine>
# This is needed for the e2e Travis matrix task to publish packages to github for continuous packages delivery.
- secure: "aCdHveZuY8AT4Jr1JoJB4LxZsnGWRe/KseZh1YXYe5UtufFCtTVHvUcLn0j2aLBF0KpdyS+hWf0i4np9jthKu2xPKriefoPgCMpisYeC0MFkwbmv+XlgkUbgkgVZMGiVyX7DCYXVahxIoOUjVMEDCbNiHTIrfEuyq24U3ok2tHc="
matrix:
# Order: a slower build first, so that we don't occupy an idle travis worker waiting for others to complete.
- CI_MODE=e2e
- CI_MODE=js
- CI_MODE=saucelabs_required
# deactivated, see #19768
# - CI_MODE=browserstack_required
# We disable these optional jobs because those acquire tunnel and browser instances which
# could lead to rate limit excess while those are failing most of the time and nobody pays
# attention anyway.
# - CI_MODE=saucelabs_optional
# - CI_MODE=browserstack_optional
matrix:
fast_finish: true
allow_failures:
- env: "CI_MODE=saucelabs_optional"
- env: "CI_MODE=browserstack_optional"
before_install:
# source the env.sh script so that the exported variables are available to other scripts later on
- source ./scripts/ci/env.sh print
install:
- ./scripts/ci/install.sh
script:
- ./scripts/ci/build.sh
- ./scripts/ci/test.sh
- ./scripts/ci/angular.sh
# all the scripts under this line will not quickly abort in case ${TRAVIS_TEST_RESULT} is 1 (job failure)
- ./scripts/ci/cleanup.sh
- ./scripts/ci/print-logs.sh

25
.vscode/README.md vendored
View File

@ -1,25 +0,0 @@
# VSCode Configuration
This folder contains opt-in [Workspace Settings](https://code.visualstudio.com/docs/getstarted/settings), [Tasks](https://code.visualstudio.com/docs/editor/tasks), [Launch Configurations](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations) and [Extension Recommendations](https://code.visualstudio.com/docs/editor/extension-gallery#_workspace-recommended-extensions) that the Angular team recommends using when working on this repository.
## Usage
To use the recommended configurations follow the steps below:
- install the recommneded extensions in `.vscode/extensions.json`
- copy (or link) `.vscode/recommended-settings.json` to `.vscode/settings.json`
- copy (or link) `.vscode/recommended-launch.json` to `.vscode/launch.json`
- copy (or link) `.vscode/recommended-tasks.json` to `.vscode/tasks.json`
- restart the editor
If you already have your custom workspace settings you should instead manually merge the file contents.
This isn't an automatic process so you will need to repeat it when settings are updated.
To see the recommended extensions select "Extensions: Show Recommended Extensions" in the [Command Palette](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette).
## Editing `.vscode/recommended-*.json` files
If you wish to add extra configuration items please keep in mind any modifications you make here will be used by many users.
Try to keep these settings/configuations to things that help facilitate the development process and avoid altering the user workflow whenever possible.

View File

@ -1,15 +0,0 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"devondcarew.bazel-code",
"gkalpak.aio-docs-utils",
"ms-vscode.vscode-typescript-tslint-plugin",
"xaver.clang-format",
// The following extensions are useful when working on angular.io (i.e. inside the `aio/` directory).
//"angular.ng-template",
//"dbaeumer.vscode-eslint",
],
}

View File

@ -1,85 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Attach to bazel test ... --config=debug",
"type": "node",
"request": "attach",
"port": 9229,
"address": "localhost",
"restart": false,
"sourceMaps": true,
"localRoot": "${workspaceRoot}",
"remoteRoot": "${workspaceRoot}",
"stopOnEntry": false,
"timeout": 600000,
},
{
"name": "Attach to bazel test ... --config=debug (no source maps)",
"type": "node",
"request": "attach",
"port": 9229,
"address": "localhost",
"restart": false,
"sourceMaps": false,
"localRoot": "${workspaceRoot}",
"remoteRoot": "${workspaceRoot}",
"stopOnEntry": false,
"timeout": 600000,
},
{
"name": "IVY:packages/core/test/acceptance",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"--config=ivy",
"packages/core/test/acceptance",
"--config=debug"
],
"port": 9229,
"address": "localhost",
"restart": true,
"sourceMaps": true,
"timeout": 600000,
},
{
"name": "IVY:packages/core/test/render3",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"--config=ivy",
"packages/core/test/render3",
"--config=debug"
],
"port": 9229,
"address": "localhost",
"restart": true,
"sourceMaps": true,
"timeout": 600000,
},
{
"name": "IVY:packages/core/test",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"--config=ivy",
"packages/core/test",
"--config=debug"
],
"port": 9229,
"address": "localhost",
"restart": true,
"sourceMaps": true,
"timeout": 600000,
},
]
}

View File

@ -1,32 +0,0 @@
{
// Format js and ts files on save with `clang-format.executable`
// If `clang-format.executable` is not being used, these two settings should be removed otherwise it will break existing formatting.
// You can instead run `yarn gulp format` to manually format your code.
"[javascript]": {
"editor.formatOnSave": true,
},
"[typescript]": {
"editor.formatOnSave": true,
},
// Please install https://marketplace.visualstudio.com/items?itemName=xaver.clang-format to take advantage of `clang-format` in VSCode.
// (See https://clang.llvm.org/docs/ClangFormat.html for more info `clang-format`.)
"clang-format.executable": "${workspaceRoot}/node_modules/.bin/clang-format",
// Exclude third party modules and build artifacts from the editor watchers/searches.
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/**": true,
"**/bazel-out/**": true,
"**/dist/**": true,
"**/aio/src/generated/**": true,
},
"search.exclude": {
"**/node_modules": true,
"**/bower_components": true,
"**/bazel-out": true,
"**/dist": true,
"**/aio/src/generated": true,
".history": true,
},
"git.ignoreLimitWarning": true,
}

View File

@ -1,113 +0,0 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "IVY:packages/core/test/...",
"type": "shell",
"command": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"--config=ivy",
"packages/core/test",
"packages/core/test/acceptance",
"packages/core/test/render3",
],
"group": "test",
"presentation": {
"reveal": "always",
"panel": "dedicated",
},
},
{
"label": "VE:packages/core/test/...",
"type": "shell",
"command": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"packages/core/test",
"packages/core/test/acceptance",
"packages/core/test/render3",
],
"group": "test",
"presentation": {
"reveal": "always",
"panel": "dedicated",
},
},
{
"label": "IVY:packages/core/test/acceptance",
"type": "shell",
"command": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"--config=ivy",
"packages/core/test/acceptance",
],
"group": "test",
"presentation": {
"reveal": "always",
"panel": "dedicated",
},
},
{
"label": "VE:packages/core/test/acceptance",
"type": "shell",
"command": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"packages/core/test/acceptance",
],
"group": "test",
"presentation": {
"reveal": "always",
"panel": "dedicated",
},
},
{
"label": "IVY:packages/core/test",
"type": "shell",
"command": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"--config=ivy",
"packages/core/test",
],
"group": "test",
"presentation": {
"reveal": "always",
"panel": "dedicated",
},
},
{
"label": "VE:packages/core/test",
"type": "shell",
"command": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"packages/core/test",
],
"group": "test",
"presentation": {
"reveal": "always",
"panel": "dedicated",
},
},
{
"label": "IVY:packages/core/test/render3",
"type": "shell",
"command": "${workspaceFolder}/node_modules/.bin/bazelisk",
"args": [
"test",
"--config=ivy",
"packages/core/test/render3",
],
"group": "test",
"presentation": {
"reveal": "always",
"panel": "dedicated",
},
},
],
}

View File

@ -1,13 +0,0 @@
# Yarn Vendoring
We utilize Yarn's `yarn-path` configuration in a shared `.yarnrc` file to enforce
everyone using the same version of Yarn. Yarn checks the `.yarnrc` file to
determine if yarn should delegate the command to a vendored version at the
provided path.
## How to update
To update to the latest version of Yarn as our vendored version:
- Run this command
```sh
yarn policies set-version latest
```
- Remove the previous version

File diff suppressed because one or more lines are too long

View File

@ -1,5 +0,0 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
yarn-path ".yarn/releases/yarn-1.22.4.js"

View File

@ -1,33 +1,22 @@
package(default_visibility = ["//visibility:public"]) package(default_visibility = ["//visibility:public"])
exports_files([ load("@build_bazel_rules_nodejs//:defs.bzl", "node_modules_filegroup")
"LICENSE",
"karma-js.conf.js",
"browser-providers.conf.js",
"scripts/ci/track-payload-size.sh",
"scripts/ci/payload-size.sh",
"scripts/ci/payload-size.js",
"package.json",
])
alias( exports_files([
name = "tsconfig.json", "tsconfig.json",
actual = "//packages:tsconfig-build.json", "LICENSE",
) "protractor-perf.conf.js",
])
filegroup( filegroup(
name = "web_test_bootstrap_scripts", name = "web_test_bootstrap_scripts",
# do not sort # do not sort
srcs = [ srcs = [
"@npm//:node_modules/core-js/client/core.js", "@ngdeps//node_modules/reflect-metadata:Reflect.js",
"//packages/zone.js/bundles:zone.umd.js", "@ngdeps//node_modules/zone.js:dist/zone.js",
"//packages/zone.js/bundles:zone-testing.umd.js", "@ngdeps//node_modules/zone.js:dist/zone-testing.js",
"//packages/zone.js/bundles:task-tracking.umd.js", "@ngdeps//node_modules/zone.js:dist/task-tracking.js",
"//:test-events.js", "//:test-events.js",
"//:third_party/shims_for_IE.js",
# Including systemjs because it defines `__eval`, which produces correct stack traces.
"@npm//:node_modules/systemjs/dist/system.src.js",
"@npm//:node_modules/reflect-metadata/Reflect.js",
], ],
) )
@ -36,14 +25,32 @@ filegroup(
srcs = [ srcs = [
# We also declare the unminfied AngularJS files since these can be used for # We also declare the unminfied AngularJS files since these can be used for
# local debugging (e.g. see: packages/upgrade/test/common/test_helpers.ts) # local debugging (e.g. see: packages/upgrade/test/common/test_helpers.ts)
"@npm//:node_modules/angular/angular.js", "@ngdeps//node_modules/angular:angular.js",
"@npm//:node_modules/angular/angular.min.js", "@ngdeps//node_modules/angular:angular.min.js",
"@npm//:node_modules/angular-1.5/angular.js", "@ngdeps//node_modules/angular-1.5:angular.js",
"@npm//:node_modules/angular-1.5/angular.min.js", "@ngdeps//node_modules/angular-1.5:angular.min.js",
"@npm//:node_modules/angular-1.6/angular.js", "@ngdeps//node_modules/angular-1.6:angular.js",
"@npm//:node_modules/angular-1.6/angular.min.js", "@ngdeps//node_modules/angular-1.6:angular.min.js",
"@npm//:node_modules/angular-mocks/angular-mocks.js", "@ngdeps//node_modules/angular-mocks:angular-mocks.js",
"@npm//:node_modules/angular-mocks-1.5/angular-mocks.js", "@ngdeps//node_modules/angular-mocks-1.5:angular-mocks.js",
"@npm//:node_modules/angular-mocks-1.6/angular-mocks.js", "@ngdeps//node_modules/angular-mocks-1.6:angular-mocks.js",
], ],
) )
load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary")
# A nodejs_binary for @angular/bazel/ngc-wrapped to use by default in
# ng_module that depends on @npm//@angular/bazel instead of the
# output of the //packages/bazel/src/ngc-wrapped ts_library rule. This
# default is for downstream users that depend on the @angular/bazel npm
# package. The generated @npm//@angular/bazel/ngc-wrapped target
# does not work because it does not have the node `--expose-gc` flag
# set which is required to support the call to `global.gc()`.
nodejs_binary(
name = "@angular/bazel/ngc-wrapped",
configuration_env_vars = ["compile"],
data = ["@npm//@angular/bazel"],
entry_point = "@angular/bazel/src/ngc-wrapped/index.js",
install_source_map_support = False,
templated_args = ["--node_options=--expose-gc"],
)

File diff suppressed because it is too large Load Diff

View File

@ -1,72 +1,12 @@
# Código de Conducta # Contributor Code of Conduct
## Version 0.3b-angular
## 1. Propósito As contributors and maintainers of the Angular project, we pledge to respect everyone who contributes by posting issues, updating documentation, submitting pull requests, providing feedback in comments, and any other activities.
“Prometemos brindar cortesía y respeto a cualquier persona involucrada en esta comunidad, sin importar el género con el que se identifique, su orientación sexual, limitación física, edad, raza, etnia, religión o nivel de conocimiento. Esperamos que cualquiera que desee contribuir en este proyecto brinde el mismo comportamiento” Communication through any of Angular's channels (GitHub, Gitter, IRC, mailing lists, Google+, Twitter, etc.) must be constructive and never resort to personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
Bajo ese principio queremos enfocar esta comunidad, una comunidad de respeto por el otro, donde cualquiera que sienta pasión por Angular y desee involucrarse con cualquier tipo de actividad deberá ayudar a mantener una atmósfera de cortesía por el otro, respetando los pensamientos, acciones, ideales y propuestas del otro. We promise to extend courtesy and respect to everyone involved in this project regardless of gender, gender identity, sexual orientation, disability, age, race, ethnicity, religion, or level of experience. We expect anyone contributing to the Angular project to do the same.
## 2. Comportamiento esperado If any member of the community violates this code of conduct, the maintainers of the Angular project may take action, removing issues, comments, and PRs or blocking accounts as deemed appropriate.
- Evitar usar expresiones o gestos insultantes, humillantes o intimidatorios para referirnos a otros. If you are subject to or witness unacceptable behavior, or have any other concerns, please email us at [conduct@angular.io](mailto:conduct@angular.io).
- Ejercita la consideración y el respeto en tus comunicaciones y acciones.
- Absténte de adoptar una conducta y un lenguaje degradantes, discriminatorios, abusivos o acosadores.
- Evitar comportamientos que agredan las expresiones de identidad, género, creencias religiosas, acciones que lastimen o los aíslen a otros.
- Evitar comentarios sobre ideas políticas.
- No se toleran conductas físicas y actitudes dirigidas al descrédito personal, físico o emocional de cualquier persona.
- No se toleran chistes y comentarios excluyentes, sexistas y racistas.
- Se rechaza actitudes de hostigamiento.
- Se rechaza el acoso: este se entiende como cualquier tipo de comentario verbal que refuerce discriminación por género, identidad y expresión de género, orientación sexual, discapacidad, apariencia física, tamaño corporal, raza, edad o religión en contextos laborales o sociales.
- No se tolera el contacto físico y/o la atención sexual no deseada.
- Promover la igualdad de oportunidades de formación, educación, intercambio y retroalimentación antes, durante y después de los eventos.
- Intenta colaborar en lugar de generar conflicto.
- Sé consciente de tu entorno y de tus compañeros participantes. Alerta a líderes de la comunidad si notas una situación peligrosa, alguien en apuros, o violaciones de este Código de Conducta, incluso si parecen intrascendentes.
## 3. Comportamiento inaceptable
Comportamientos inaceptables incluyen: intimidación, acoso, abuso, discriminación, comunicación despectiva o degradante o acciones por cualquier participante en nuestra comunidad ya sea virtual, o en las comunicaciones uno-a-uno que se realizan en el contexto de la comunidad. Por favor ser respetuoso con todos.
El acoso incluye: comentarios nocivos o perjudiciales, verbales o escritos relacionados con el género, la orientación sexual, raza, religión, discapacidad; uso inadecuado de desnudos y / o imágenes sexuales en espacios públicos (incluyendo la presentación diapositivas); intimidación deliberada, acecho o seguimiento; fotografías o grabaciones acosadoras; interrupción sostenida de charlas y otros eventos; contacto físico inapropiado, y atención sexual no deseada.
## 4. Consecuencias de comportamiento inaceptable
Se espera que personas a quienes se les solicite que detengan su comportamiento inaceptable lo hagan de manera inmediata esto será válido para cualquier miembro de la comunidad.
En caso de presentarse una violación al código de conducta de manera repetida se tendrá cero tolerancia a este comportamiento por parte de los organizadores.
Si un miembro de la comunidad participa en una conducta inaceptable, los organizadores pueden tomar cualquier acción que consideren apropiada, hasta e incluyendo una prohibición temporal o expulsión permanente de la comunidad, sin previo aviso.
Priorizamos la seguridad de las personas marginadas sobre la comodidad de las personas privilegiadas. Nos reservamos el derecho de no actuar sobre las quejas relacionadas con:
- El "racismo inverso", "sexismo inverso" y "cisfobia".
- Comunicación razonable de límites, como "déjame en paz", "vete" o "no estoy discutiendo esto contigo".
- Al comunicarse en un "tono", no se encuentra agradable.
- Identificando comportamientos o suposiciones racistas, sexistas, cissexistas u opresivas.
## 5. ¿Qué hacer si se incumple el código de conducta?
Si eres víctima o testigo de una conducta inaceptable, o tienes cualquier inquietud, por favor comunícate con el equipo organizador lo antes posible:
- Mensaje directo: Michael Prentice (@splaktar)
- Mensaje directo: Jorge Cano (@jorgeucano)
- Mensaje directo: Andrés Villanueva (@villanuevand)
- Email: [soporte@angular.lat](mailto:soporte@angular.lat)
### ¿Qué pasa después?
- Una vez haya sido notificada el no cumplimiento de la norma, el equipo de liderazgo se reunirán y analizarán el caso.
- Los incidentes presentados se manejarán con discreción.
- Los organizadores se comunicarán con la persona que incumplió la norma y tomarán las medidas respectivas.
- Se realizará un acompañamiento a la persona agredida y se apoyará.
- Si el incidente se hace público, Angular Hispano no se hace responsable de los perjuicios que esto pueda ocasionar en el agresor o el agredido.
## 6. Alcance
Esperamos que todos los participantes de la comunidad (organizadores, voluntarios, contribuyentes pagados o de otro modo; patrocinadores; y otros invitados) se atengan a este Código de Conducta en todos los espacios virtuales y presenciales, así como en todas las comunicaciones de uno-a-uno pertinentes la comunidad.
### Colaboradores
- Alejandra Giraldo
- Vanessa Marely
- Mariano Alvarez
- Andrés Villanueva
- Michael Prentice
- javascript&friends
- Angular
- She Codes Angular
- Colombia dev

View File

@ -1,359 +0,0 @@
# Contributing to Angular
We would love for you to contribute to Angular and help make it even better than it is today!
As a contributor, here are the guidelines we would like you to follow:
- [Code of Conduct](#coc)
- [Question or Problem?](#question)
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submission Guidelines](#submit)
- [Coding Rules](#rules)
- [Commit Message Guidelines](#commit)
- [Signing the CLA](#cla)
## <a name="coc"></a> Code of Conduct
Help us keep Angular open and inclusive.
Please read and follow our [Code of Conduct][coc].
## <a name="question"></a> Got a Question or Problem?
Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests.
Instead, we recommend using [Stack Overflow](https://stackoverflow.com/questions/tagged/angular) to ask support-related questions. When creating a new question on Stack Overflow, make sure to add the `angular` tag.
Stack Overflow is a much better place to ask questions since:
- there are thousands of people willing to help on Stack Overflow
- questions and answers stay available for public viewing so your question/answer might help someone else
- Stack Overflow's voting system assures that the best answers are prominently visible.
To save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow.
If you would like to chat about the question in real-time, you can reach out via [our gitter channel][gitter].
## <a name="issue"></a> Found a Bug?
If you find a bug in the source code, you can help us by [submitting an issue](#submit-issue) to our [GitHub Repository][github].
Even better, you can [submit a Pull Request](#submit-pr) with a fix.
## <a name="feature"></a> Missing a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to our GitHub Repository.
If you would like to *implement* a new feature, please consider the size of the change in order to determine the right steps to proceed:
* For a **Major Feature**, first open an issue and outline your proposal so that it can be discussed.
This process allows us to better coordinate our efforts, prevent duplication of work, and help you to craft the change so that it is successfully accepted into the project.
**Note**: Adding a new topic to the documentation, or significantly re-writing a topic, counts as a major feature.
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
## <a name="submit"></a> Submission Guidelines
### <a name="submit-issue"></a> Submitting an Issue
Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.
We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it.
In order to reproduce bugs, we require that you provide a minimal reproduction.
Having a minimal reproducible scenario gives us a wealth of important information without going back and forth to you with additional questions.
A minimal reproduction allows us to quickly confirm a bug (or point out a coding problem) as well as confirm that we are fixing the right problem.
We require a minimal reproduction to save maintainers' time and ultimately be able to fix more bugs.
Often, developers find coding problems themselves while preparing a minimal reproduction.
We understand that sometimes it might be hard to extract essential bits of code from a larger codebase but we really need to isolate the problem before we can fix it.
Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you, we are going to close an issue that doesn't have enough info to be reproduced.
You can file new issues by selecting from our [new issue templates](https://github.com/angular/angular/issues/new/choose) and filling out the issue template.
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
Before you submit your Pull Request (PR) consider the following guidelines:
1. Search [GitHub](https://github.com/angular/angular/pulls) for an open or closed PR that relates to your submission.
You don't want to duplicate existing efforts.
2. Be sure that an issue describes the problem you're fixing, or documents the design for the feature you'd like to add.
Discussing the design upfront helps to ensure that we're ready to accept your work.
3. Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.
We cannot accept code without a signed CLA.
Make sure you author all contributed Git commits with email address associated with your CLA signature.
4. Fork the angular/angular repo.
5. Make your changes in a new git branch:
```shell
git checkout -b my-fix-branch master
```
6. Create your patch, **including appropriate test cases**.
7. Follow our [Coding Rules](#rules).
8. Run the full Angular test suite, as described in the [developer documentation][dev-doc], and ensure that all tests pass.
9. Commit your changes using a descriptive commit message that follows our [commit message conventions](#commit).
Adherence to these conventions is necessary because release notes are automatically generated from these messages.
```shell
git commit -a
```
Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
10. Push your branch to GitHub:
```shell
git push origin my-fix-branch
```
11. In GitHub, send a pull request to `angular:master`.
If we ask for changes via code reviews then:
* Make the required updates.
* Re-run the Angular test suites to ensure tests are still passing.
* Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
```shell
git rebase master -i
git push -f
```
That's it! Thank you for your contribution!
#### After your pull request is merged
After your pull request is merged, you can safely delete your branch and pull the changes from the main (upstream) repository:
* Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:
```shell
git push origin --delete my-fix-branch
```
* Check out the master branch:
```shell
git checkout master -f
```
* Delete the local branch:
```shell
git branch -D my-fix-branch
```
* Update your master with the latest upstream version:
```shell
git pull --ff upstream master
```
## <a name="rules"></a> Coding Rules
To ensure consistency throughout the source code, keep these rules in mind as you are working:
* All features or bug fixes **must be tested** by one or more specs (unit-tests).
* All public API methods **must be documented**.
* We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at **100 characters**.
An automated formatter is available, see [DEVELOPER.md](docs/DEVELOPER.md#clang-format).
## <a name="commit"></a> Commit Message Format
*This specification is inspired and supersedes the [AngularJS commit message format][commit-message-format].*
We have very precise rules over how our Git commit messages must be formatted.
This format leads to **easier to read commit history**.
Each commit message consists of a **header**, a **body**, and a **footer**.
```
<header>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```
The `header` is mandatory and must conform to the [Commit Message Header](#commit-header) format.
The `body` is mandatory for all commits except for those of scope "docs".
When the body is required it must be at least 20 characters long.
The `footer` is optional.
Any line of the commit message cannot be longer than 100 characters.
#### <a href="commit-header"></a>Commit Message Header
```
<type>(<scope>): <short summary>
│ │ │
│ │ └─⫸ Summary in present tense. Not capitalized. No period at the end.
│ │
│ └─⫸ Commit Scope: animations|bazel|benchpress|common|compiler|compiler-cli|core|
│ elements|forms|http|language-service|localize|platform-browser|
│ platform-browser-dynamic|platform-server|platform-webworker|
│ platform-webworker-dynamic|router|service-worker|upgrade|zone.js|
│ packaging|changelog|dev-infra|docs-infra|migrations|ngcc|ve
└─⫸ Commit Type: build|ci|docs|feat|fix|perf|refactor|style|test
```
The `<type>` and `<summary>` fields are mandatory, the `(<scope>)` field is optional.
##### Type
Must be one of the following:
* **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
* **ci**: Changes to our CI configuration files and scripts (example scopes: Circle, BrowserStack, SauceLabs)
* **docs**: Documentation only changes
* **feat**: A new feature
* **fix**: A bug fix
* **perf**: A code change that improves performance
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
* **test**: Adding missing tests or correcting existing tests
##### Scope
The scope should be the name of the npm package affected (as perceived by the person reading the changelog generated from commit messages).
The following is the list of supported scopes:
* `animations`
* `bazel`
* `benchpress`
* `common`
* `compiler`
* `compiler-cli`
* `core`
* `elements`
* `forms`
* `http`
* `language-service`
* `localize`
* `platform-browser`
* `platform-browser-dynamic`
* `platform-server`
* `platform-webworker`
* `platform-webworker-dynamic`
* `router`
* `service-worker`
* `upgrade`
* `zone.js`
There are currently a few exceptions to the "use package name" rule:
* `packaging`: used for changes that change the npm package layout in all of our packages, e.g. public path changes, package.json changes done to all packages, d.ts file/format changes, changes to bundles, etc.
* `changelog`: used for updating the release notes in CHANGELOG.md
* `dev-infra`: used for dev-infra related changes within the directories /scripts, /tools and /dev-infra
* `docs-infra`: used for docs-app (angular.io) related changes within the /aio directory of the repo
* `migrations`: used for changes to the `ng update` migrations.
* `ngcc`: used for changes to the [Angular Compatibility Compiler](./packages/compiler-cli/ngcc/README.md)
* `ve`: used for changes specific to ViewEngine (legacy compiler/renderer).
* none/empty string: useful for `style`, `test` and `refactor` changes that are done across all packages (e.g. `style: add missing semicolons`) and for docs changes that are not related to a specific package (e.g. `docs: fix typo in tutorial`).
##### Summary
Use the summary field to provide a succinct description of the change:
* use the imperative, present tense: "change" not "changed" nor "changes"
* don't capitalize the first letter
* no dot (.) at the end
#### Commit Message Body
Just as in the summary, use the imperative, present tense: "fix" not "fixed" nor "fixes".
Explain the motivation for the change in the commit message body. This commit message should explain _why_ you are making the change.
You can include a comparison of the previous behavior with the new behavior in order to illustrate the impact of the change.
#### Commit Message Footer
The footer can contain information about breaking changes and is also the place to reference GitHub issues, Jira tickets, and other PRs that this commit closes or is related to.
```
BREAKING CHANGE: <breaking change summary>
<BLANK LINE>
<breaking change description + migration instructions>
<BLANK LINE>
<BLANK LINE>
Fixes #<issue number>
```
Breaking Change section should start with the phrase "BREAKING CHANGE: " followed by a summary of the breaking change, a blank line, and a detailed description of the breaking change that also includes migration instructions.
### Revert commits
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit.
The content of the commit message body should contain:
- information about the SHA of the commit being reverted in the following format: `This reverts commit <SHA>`,
- a clear description of the reason for reverting the commit message.
## <a name="cla"></a> Signing the CLA
Please sign our Contributor License Agreement (CLA) before sending pull requests. For any code
changes to be accepted, the CLA must be signed. It's a quick process, we promise!
* For individuals, we have a [simple click-through form][individual-cla].
* For corporations, we'll need you to
[print, sign and one of scan+email, fax or mail the form][corporate-cla].
If you have more than one GitHub accounts, or multiple email addresses associated with a single GitHub account, you must sign the CLA using the primary email address of the GitHub account used to author Git commits and send pull requests.
The following documents can help you sort out issues with GitHub accounts and multiple email addresses:
* https://help.github.com/articles/setting-your-commit-email-address-in-git/
* https://stackoverflow.com/questions/37245303/what-does-usera-committed-with-userb-13-days-ago-on-github-mean
* https://help.github.com/articles/about-commit-email-addresses/
* https://help.github.com/articles/blocking-command-line-pushes-that-expose-your-personal-email-address/
[angular-group]: https://groups.google.com/forum/#!forum/angular
[coc]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md
[commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#
[corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html
[dev-doc]: https://github.com/angular/angular/blob/master/docs/DEVELOPER.md
[github]: https://github.com/angular/angular
[gitter]: https://gitter.im/angular/angular
[individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html
[js-style-guide]: https://google.github.io/styleguide/jsguide.html
[jsfiddle]: http://jsfiddle.net
[plunker]: http://plnkr.co/edit
[runnable]: http://runnable.com
[stackoverflow]: http://stackoverflow.com/questions/tagged/angular

View File

@ -1,340 +1,280 @@
# Contribuye a Angular # Contributing to Angular
¡Nos encantaría que contribuyeras a Angular y que ayudaras a hacerlo aún mejor de lo que es hoy! We would love for you to contribute to Angular and help make it even better than it is
Como colaborador, estos son los lineamientos que nos gustaría que siguieras: today! As a contributor, here are the guidelines we would like you to follow:
- [Código de conducta](#coc) - [Code of Conduct](#coc)
- [¿Preguntas o problemas?](#question) - [Question or Problem?](#question)
- [_Issues_ y _bugs_](#issue) - [Issues and Bugs](#issue)
- [Solicitud de funcionalidades](#feature) - [Feature Requests](#feature)
- [Guía para la creación de issues y PRs](#submit) - [Submission Guidelines](#submit)
- [Reglas del código](#rules) - [Coding Rules](#rules)
- [Convención para el mensaje de los _commits_](#commit) - [Commit Message Guidelines](#commit)
- [Firma del Acuerdo de Licencia de Colaborador (CLA)](#cla) - [Signing the CLA](#cla)
## <a name="coc"></a> Code of Conduct
Help us keep Angular open and inclusive. Please read and follow our [Code of Conduct][coc].
## <a name="question"></a> Got a Question or Problem?
Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on [Stack Overflow](https://stackoverflow.com/questions/tagged/angular) where the questions should be tagged with tag `angular`.
Stack Overflow is a much better place to ask questions since:
- there are thousands of people willing to help on Stack Overflow
- questions and answers stay available for public viewing so your question / answer might help someone else
- Stack Overflow's voting system assures that the best answers are prominently visible.
To save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow.
If you would like to chat about the question in real-time, you can reach out via [our gitter channel][gitter].
## <a name="issue"></a> Found a Bug?
If you find a bug in the source code, you can help us by
[submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can
[submit a Pull Request](#submit-pr) with a fix.
## <a name="feature"></a> Missing a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to our GitHub
Repository. If you would like to *implement* a new feature, please submit an issue with
a proposal for your work first, to be sure that we can use it.
Please consider what kind of change it is:
* For a **Major Feature**, first open an issue and outline your proposal so that it can be
discussed. This will also allow us to better coordinate our efforts, prevent duplication of work,
and help you to craft the change so that it is successfully accepted into the project.
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
## <a name="submit"></a> Submission Guidelines
### <a name="submit-issue"></a> Submitting an Issue
Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.
We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs, we will systematically ask you to provide a minimal reproduction. Having a minimal reproducible scenario gives us a wealth of important information without going back & forth to you with additional questions.
A minimal reproduction allows us to quickly confirm a bug (or point out a coding problem) as well as confirm that we are fixing the right problem.
We will be insisting on a minimal reproduction scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal reproduction. We understand that sometimes it might be hard to extract essential bits of code from a larger code-base but we really need to isolate the problem before we can fix it.
Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that doesn't have enough info to be reproduced.
You can file new issues by selecting from our [new issue templates](https://github.com/angular/angular/issues/new/choose) and filling out the issue template.
## <a name="coc"></a> Código de conducta ### <a name="submit-pr"></a> Submitting a Pull Request (PR)
Before you submit your Pull Request (PR) consider the following guidelines:
Ayúdanos a mantener Angular abierto e inclusivo. 1. Search [GitHub](https://github.com/angular/angular/pulls) for an open or closed PR
Por favor lee y sigue nuestro [Código de conducta][coc]. that relates to your submission. You don't want to duplicate effort.
1. Be sure that an issue describes the problem you're fixing, or documents the design for the feature you'd like to add.
Discussing the design up front helps to ensure that we're ready to accept your work.
## <a name="question"></a> ¿Tienes alguna pregunta o problema? 1. Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.
We cannot accept code without this. Make sure you sign with the primary email address of the Git identity that has been granted access to the Angular repository.
No abras *issues* para preguntas de soporte general ya que queremos mantener los *issues* de GitHub para reporte de *bugs* y solicitud de funcionalidades. 1. Fork the angular/angular repo.
En su lugar, recomendamos utilizar [Stack Overflow](https://stackoverflow.com/questions/tagged/angular) para hacer preguntas relacionadas con soporte. Al crear una nueva pregunta en Stack Overflow, asegúrate de agregar el etiqueta (tag) de `angular`. 1. Make your changes in a new git branch:
Stack Overflow es mucho mejor para hacer preguntas ya que:
- Hay miles de personas dispuestas a ayudar en preguntas y respuestas de Stack Overflow
que permanecen disponibles para el público, por lo que tu pregunta o respuesta podría ayudar a otra persona.
- El sistema de votación de Stack Overflow asegura que las mejores respuestas sobresalgan y sean visibles.
Para ahorrar tu tiempo y el nuestro, cerraremos sistemáticamente todos los *issues* que sean solicitudes de soporte general y redirigiremos a las personas a Stack Overflow.
Si deseas chatear sobre alguna pregunta en tiempo real, puedes hacerlo a través de nuestro [canal de Gitter][gitter].
## <a name="issue"></a> ¿Encontraste un Bug?
Si encontraste un error en el código fuente, puedes ayudarnos [creando un *issue*](#submit-issue) en nuestro [repositorio de GitHub][github].
O incluso mejor, puedes [crear un *Pull Request*](#submit-pr) con la solución.
## <a name="feature"></a> ¿Falta alguna funcionalidad?
Puedes solicitar una nueva funcionalidad [creando un *issue*](#submit-issue) en nuestro repositorio de GitHub.
Si deseas implementar una nueva funcionalidad, por favor considera el tamaño del cambio para determinar los pasos correctos para continuar:
* Para un **cambio significativo**, primero abre un *issue* y describe tu propuesta para que pueda ser discutida.
Este proceso nos permite coordinar mejor nuestros esfuerzos, evitar trabajo duplicado y ayudarte a diseñar el cambio para que sea aceptado con éxito en el proyecto.
**Nota**: Agregar un nuevo tema a la documentación o reescribir significativamente un tema, también cuenta como *cambio significativo*.
* **Cambios pequeños** pueden ser elaborados y directamente [creados como un _pull request_](#submit-pr).
## <a name="submit"></a> Guía para la creación de issues y PRs
### <a name="submit-issue"></a> Creación de _issues_
Antes de crear un *issue*, por favor busca en el el *issue tracker*, quizá un *issue* para tu problema ya existe y la discusión puede informarte sobre soluciones alternativas disponibles.
Queremos solucionar todos los problemas lo antes posible, pero antes de corregir un bug necesitamos reproducirlo y confirmarlo.
Para reproducir errores, requerimos que proporciones una reproducción mínima.
Tener un escenario reproducible mínimo nos brinda una gran cantidad de información importante sin tener que ir y venir con preguntas adicionales.
Una reproducción mínima nos permite confirmar rápidamente un bug (o señalar un problema de código), así también confirmar que estamos solucionando el problema correcto.
Requerimos una reproducción mínima para ahorrar tiempo a los encargados del mantenimiento y en última instancia, poder corregir más bugs.
A menudo los desarrolladores encuentran problemas de código mientras preparan una reproducción mínima.
Entendemos que a veces puede ser difícil extraer porciones esenciales de código de un código más grande, pero realmente necesitamos aislar el problema antes de poder solucionarlo.
Desafortunadamente no podemos investigar/corregir errores sin una reproducción mínima, por lo que si no tenemos tu retroalimentación del bug, vamos a cerrar el *issue* ya que no tiene suficiente información para reproducirse.
Puedes presentar nuevos *issues* seleccionando nuestra [plantilla de _issues_](https://github.com/angular/angular/issues/new/choose) y complentando la plantilla.
### <a name="submit-pr"></a> Creación de un Pull Requests (PR)
Antes de crear tu Pull Request (PR) considera los siguientes lineamientos:
1. Busca en [GitHub](https://github.com/angular/angular/pulls) PRs que estén abiertos o cerrados y que estén relacionados con el que vas a crear.
No deseas duplicar los esfuerzos existentes.
2. Asegúrate de que el PR describa el problema que estás solucionando o que documente el diseño de la funcionalidad que deseas agregar.
Discutir el diseño por adelantado ayuda a garantizar que estemos listos para aceptar tu trabajo.
3. Por favor firma nuestro [Acuerdo de Licencia de Colaborador (CLA)](#cla) antes de crear PRs.
No podemos aceptar el código sin el Acuerdo de Licencia de Colaborador (CLA) firmado.
Asegúrate de crear todas las contribuciones de Git con la dirección de correo electrónico asociada con tu firma del Acuerdo de Licencia de Colaborador (CLA).
4. Haz *fork* del repositorio angular/angular.
5. Haz tus cambios en una nueva rama de Git:
```shell ```shell
git checkout -b my-fix-branch master git checkout -b my-fix-branch master
``` ```
6. Crea tu correción, **incluyendo casos de prueba apropiados**. 1. Create your patch, **including appropriate test cases**.
1. Follow our [Coding Rules](#rules).
7. Sigue nuestras [Reglas de código](#rules). 1. Run the full Angular test suite, as described in the [developer documentation][dev-doc],
and ensure that all tests pass.
8. Ejecuta todo el conjunto de pruebas de Angular, tal como está descrito en la [documentación del desarrollador][dev-doc], y asegúrate de que todas las pruebas pasen. 1. Commit your changes using a descriptive commit message that follows our
[commit message conventions](#commit). Adherence to these conventions
9. Crea un commit de tus cambios utilizando un mensaje de commit descriptivo que siga nuestra [convención para el mensaje de los commits](#commit). is necessary because release notes are automatically generated from these messages.
Es necesario cumplir con estas convenciones porque las notas de las versiones se generan automáticamente a partir de estos mensajes.
```shell ```shell
git commit -a git commit -a
``` ```
Nota: la opción de la línea de comandos de Git `-a` automaticamente hará "add" y "rm" a los archivos editados. Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
10. Haz push de tu rama a GitHub: 1. Push your branch to GitHub:
```shell ```shell
git push origin my-fix-branch git push origin my-fix-branch
``` ```
11. En GitHub, crea un pull request a `angular:master`. 1. In GitHub, send a pull request to `angular:master`.
* If we suggest changes then:
* Make the required updates.
* Re-run the Angular test suites to ensure tests are still passing.
* Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
Si solicitamos cambios a través de revisiones de código, sigue las siguientes indicaciones: ```shell
git rebase master -i
git push -f
```
* Haz los cambios requeridos. That's it! Thank you for your contribution!
* Ejecuta nuevamente el conjunto de pruebas de Angular para asegurar que todas las pruebas aún están pasando.
* Haz rebase de tu rama a la rama master y haz push con la opción `-f` a tu repositorio de Github (esto actualizará tu Pull Request):
```shell #### After your pull request is merged
git rebase master -i
git push -f
```
¡Es todo! ¡Muchas gracias por tu contribución! After your pull request is merged, you can safely delete your branch and pull the changes
from the main (upstream) repository:
* Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:
#### Después del merge de tu pull request
Después de que se hizo merge de tu pull request, puedes eliminar de forma segura tu rama y hacer pull de los cambios del repositorio principal (upstream):
* Elimina la rama remota en GitHub a través de la interfaz de usuario web de GitHub o en tu línea de comandos de la siguiente manera:
```shell ```shell
git push origin --delete my-fix-branch git push origin --delete my-fix-branch
``` ```
* Muévete a la rama master: * Check out the master branch:
```shell ```shell
git checkout master -f git checkout master -f
``` ```
* Elimina tu rama local: * Delete the local branch:
```shell ```shell
git branch -D my-fix-branch git branch -D my-fix-branch
``` ```
* Actualiza tu rama master con la última versión del fork (upstream): * Update your master with the latest upstream version:
```shell ```shell
git pull --ff upstream master git pull --ff upstream master
``` ```
## <a name="rules"></a> Coding Rules
To ensure consistency throughout the source code, keep these rules in mind as you are working:
## <a name="rules"></a> Reglas del código * All features or bug fixes **must be tested** by one or more specs (unit-tests).
Para garantizar la coherencia en todo el código fuente, ten en cuenta estas reglas mientras trabajas: * All public API methods **must be documented**. (Details TBC).
* We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at
**100 characters**. An automated formatter is available, see
[DEVELOPER.md](docs/DEVELOPER.md#clang-format).
* Todas las funcionalidades o solución de bugs **deben ser probadas** por una o más pruebas (pruebas unitarias). ## <a name="commit"></a> Commit Message Guidelines
* Todos los métodos públicos del API **deben ser documentados**.
* Seguimos la [guía de estilo JavaScript de Google][js-style-guide], pero cada línea no debe exceder **100 caracteres**.
Un formateador automatizado está disponible, revisar [DEVELOPER.md](docs/DEVELOPER.md#clang-format). We have very precise rules over how our git commit messages can be formatted. This leads to **more
readable messages** that are easy to follow when looking through the **project history**. But also,
we use the git commit messages to **generate the Angular change log**.
## <a name="commit"></a> Formato para el mensaje de los commits
*Esta especificación está inspirada y reemplaza el [Formato de mensaje de commits de AngularJS][commit-message-format].*
Tenemos reglas muy precisas sobre cómo deben formatearse nuestros mensajes de los commits de Git.
Este formato permite tener **un historial de commits más facil de leer**.
Cada mensaje de un commit consta del **header**, el **body**, y el **footer**.
### Commit Message Format
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special
format that includes a **type**, a **scope** and a **subject**:
``` ```
<header> <type>(<scope>): <subject>
<LINEA VACIA> <BLANK LINE>
<body> <body>
<LINEA VACIA> <BLANK LINE>
<footer> <footer>
``` ```
El `header` es obligatorio y debe ajustarse al formato del [mensaje del header del commit](#commit-header). The **header** is mandatory and the **scope** of the header is optional.
El `body` es obligatorio para todos los commits excepto los que tenga scope "docs". Any line of the commit message cannot be longer 100 characters! This allows the message to be easier
Cuando el body es requerido debe tener al menos 20 caracteres. to read on GitHub as well as in various git tools.
El `footer` es opcional. The footer should contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages/) if any.
Cualquier línea del mensaje del commit no puede tener más de 100 caracteres. Samples: (even more [samples](https://github.com/angular/angular/commits/master))
#### <a href="commit-header"></a>Mensaje del header del commit
``` ```
<tipo>(<alcance>): <resumen> docs(changelog): update changelog to beta.5
│ │ │ ```
│ │ └─⫸ Resumen corto escrito en modo imperativo, tiempo presente. Sin mayúsculas. Sin punto final. ```
│ │ fix(release): need to depend on latest rxjs and zone.js
│ └─⫸ Alcance del commit: animations|bazel|benchpress|common|compiler|compiler-cli|core|
│ elements|forms|http|language-service|localize|platform-browser| The version in our package.json gets copied to the one we publish, and users need the latest of these.
│ platform-browser-dynamic|platform-server|platform-webworker|
│ platform-webworker-dynamic|router|service-worker|upgrade|zone.js|
│ packaging|changelog|dev-infra|docs-infra|migrations|ngcc|ve
└─⫸ Tipo de commit: build|ci|docs|feat|fix|perf|refactor|style|test
``` ```
El `<tipo>` y `<resumen>` son obligatorios, el `(<alcance>)` es opcional. ### Revert
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.
### Type
Must be one of the following:
##### Tipo * **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
* **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
* **docs**: Documentation only changes
* **feat**: A new feature
* **fix**: A bug fix
* **perf**: A code change that improves performance
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
* **test**: Adding missing tests or correcting existing tests
El tipo debe ser uno de los siguientes: ### Scope
The scope should be the name of the npm package affected (as perceived by the person reading the changelog generated from commit messages.
* **build**: cambios que afectan el sistema de compilación o dependencias externas (ejemplos de scopes: gulp, broccoli, npm) The following is the list of supported scopes:
* **ci**: cambios en nuestros archivos y scripts de configuración de CI (ejemplos de scopes: Circle, BrowserStack, SauceLabs)
* **docs**: cambios en la documentación
* **feat**: una nueva funcionalidad
* **fix**: una solución de un bug
* **perf**: un cambio de código que mejora el rendimiento.
* **refactor**: un cambio de código que no corrige ningún error ni agrega ninguna funcionalidad
* **style**: cambios que no afectan el significado del código (espacios en blanco, formato, falta de punto y coma, etc.)
* **test**: se agregan pruebas faltantes o se corrigen pruebas existentes
* **animations**
* **common**
* **compiler**
* **compiler-cli**
* **core**
* **elements**
* **forms**
* **http**
* **language-service**
* **platform-browser**
* **platform-browser-dynamic**
* **platform-server**
* **platform-webworker**
* **platform-webworker-dynamic**
* **router**
* **service-worker**
* **upgrade**
##### Alcance There are currently a few exceptions to the "use package name" rule:
El alcance debe ser el nombre del paquete npm afectado (tal como lo percibe la persona que lee el registro de cambios generado a partir de los mensajes de commit).
La siguiente es la lista de alcances permitidos: * **packaging**: used for changes that change the npm package layout in all of our packages, e.g.
public path changes, package.json changes done to all packages, d.ts file/format changes, changes
to bundles, etc.
* **changelog**: used for updating the release notes in CHANGELOG.md
* **docs-infra**: used for docs-app (angular.io) related changes within the /aio directory of the
repo
* none/empty string: useful for `style`, `test` and `refactor` changes that are done across all
packages (e.g. `style: add missing semicolons`) and for docs changes that are not related to a
specific package (e.g. `docs: fix typo in tutorial`).
* `animations` ### Subject
* `bazel` The subject contains a succinct description of the change:
* `benchpress`
* `common`
* `compiler`
* `compiler-cli`
* `core`
* `elements`
* `forms`
* `http`
* `language-service`
* `localize`
* `platform-browser`
* `platform-browser-dynamic`
* `platform-server`
* `platform-webworker`
* `platform-webworker-dynamic`
* `router`
* `service-worker`
* `upgrade`
* `zone.js`
Actualmente hay algunas excepciones a la regla "usar el nombre de paquete": * use the imperative, present tense: "change" not "changed" nor "changes"
* don't capitalize the first letter
* no dot (.) at the end
* `packaging`: usado para cambios que cambian el diseño de los paquetes de npm en todos nuestros paquetes. Ejemplos: cambios de la ruta públic, package.json cambios hechos a todos los paquetes, cambios a archivos o formatos d.ts, cambios a bundles, etc. ### Body
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
The body should include the motivation for the change and contrast this with previous behavior.
* `changelog`: utilizado para actualizar las notas de la versión en CHANGELOG.md ### Footer
The footer should contain any information about **Breaking Changes** and is also the place to
reference GitHub issues that this commit **Closes**.
* `dev-infra`: utilizado para cambios relacionados con dev-infra dentro de los directorios /scripts, /tools y /dev-infra **Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
* `docs-infra`: utilizado para cambios relacionados con la documentación (angular.io) dentro del directorio /aio del repositorio A detailed explanation can be found in this [document][commit-message-format].
* `migrations`: utilizado para los cambios en las migraciones `ng update`. ## <a name="cla"></a> Signing the CLA
* `ngcc`: usado para los cambios del [Compilador de compatibilidad de Angular](./packages/compiler-cli/ngcc/README.md) Please sign our Contributor License Agreement (CLA) before sending pull requests. For any code
changes to be accepted, the CLA must be signed. It's a quick process, we promise!
* `ve`: utilizado para cambios específicos de ViewEngine (legacy compiler/renderer). * For individuals we have a [simple click-through form][individual-cla].
* For corporations we'll need you to
[print, sign and one of scan+email, fax or mail the form][corporate-cla].
* alcance vacío: útil para cambios de `style`, `test` y `refactor` que se realizan en todos los paquetes (ejemplo: `style: add missing semicolons`) y para cambios de la documentación que no están relacionados a un paquete en específico(ejemplo: `docs: corrige error gramatical en el tutorial`). <hr>
If you have more than one Git identity, you must make sure that you sign the CLA using the primary email address associated with the ID that has been granted access to the Angular repository. Git identities can be associated with more than one email address, and only one is primary. Here are some links to help you sort out multiple Git identities and email addresses:
##### Resumen
Usa el campo resumen para proporcionar una descripción breve del cambio:
* usa el modo imperativo, tiempo presente: "cambia" no "cambió" o "cambios"
* no debe de contener ninguna letra mayúscula
* no debe de conter punto (.) al final
#### Mensaje del cuerpo del commit
Tal como en el resumen, usa el modo imperativo, tiempo presente: "cambia" no "cambió" o "cambios".
Explica la razón del cambio en el el mensaje del cuerpo del commit. Este mensaje de confirmación debe explicar _por qué_ está realizando el cambio.
Puedes incluir una comparación del comportamiento anterior con el nuevo comportamiento para ilustrar el impacto del cambio.
#### Mensaje del footer del commit
El footer puede contener información sobre cambios significativos y también es el lugar para hacer referencia a issues de GitHub, tickets de Jira y otros PRs que están relacionados con el commit.
```
CAMBIO SIGNIFICATIVO: <resumen del cambio significativo>
<LINEA VACIA>
<descripción del cambio significativo + instrucciones para la migración>
<LINEA VACIA>
<LINEA VACIA>
Fix #<issue número>
```
La sección de cambios significativos debería comenzar con la frase "CAMBIO SIGNIFICATIVO: " seguido de un resumen del cambio significativo, una línea en blanco y una descripción detallada del cambio significativo que también incluya instrucciones de migración.
### Revirtiendo commits
Si el commit revierte un commit previo, el commit debería comenzar con `revert: `, seguido por el header del commit revertido.
El contenido del mensaje del commit debería contener:
- Información sobre el SHA del commit que se revierte en el siguiente formato: `Esto revierte el commit <SHA>`,
- Una descripción clara de la razón para revertir el mensaje del _commit_.
## <a name="cla"></a> Firma del Acuerdo de Licencia de Colaborador (CLA)
Por favor firma nuestro Acuerdo de Licencia de Colaborador (CLA) cuando creas tu primer pull request. Para que cualquier cambio de código sea aceptado, el Acuerdo de Licencia de Colaborador (CLA) debe ser firmado. Es un proceso rápido con nuestro CLA assistant que está integrado con nuestro CI.
Los siguientes documentos pueden ayudarte a resolver problemas con cuentas de GitHub y múltiples direcciones de correo electrónico:
* https://help.github.com/articles/setting-your-commit-email-address-in-git/ * https://help.github.com/articles/setting-your-commit-email-address-in-git/
* https://stackoverflow.com/questions/37245303/what-does-usera-committed-with-userb-13-days-ago-on-github-mean * https://stackoverflow.com/questions/37245303/what-does-usera-committed-with-userb-13-days-ago-on-github-mean
* https://help.github.com/articles/about-commit-email-addresses/ * https://help.github.com/articles/about-commit-email-addresses/
* https://help.github.com/articles/blocking-command-line-pushes-that-expose-your-personal-email-address/ * https://help.github.com/articles/blocking-command-line-pushes-that-expose-your-personal-email-address/
Note that if you have more than one Git identity, it is important to verify that you are logged in with the same ID with which you signed the CLA, before you commit changes. If not, your PR will fail the CLA check.
<hr>
[angular-group]: https://groups.google.com/forum/#!forum/angular [angular-group]: https://groups.google.com/forum/#!forum/angular

View File

@ -1,6 +1,6 @@
The MIT License The MIT License
Copyright (c) 2010-2020 Google LLC. http://angular.io/license Copyright (c) 2014-2018 Google, Inc. http://angular.io
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,26 +0,0 @@
[![CircleCI](https://circleci.com/gh/angular/angular/tree/master.svg?style=shield)](https://circleci.com/gh/angular/workflows/angular/tree/master)
[![Join the chat at https://gitter.im/angular/angular](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/angular/angular?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![npm version](https://badge.fury.io/js/%40angular%2Fcore.svg)](https://www.npmjs.com/@angular/core)
# Angular
Angular is a development platform for building mobile and desktop web applications using TypeScript/JavaScript and other languages.
## Quickstart
[Get started in 5 minutes][quickstart].
## Changelog
[Learn about the latest improvements][changelog].
## Want to help?
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on our
guidelines for [contributing][contributing] and then check out one of our issues in the [hotlist: community-help](https://github.com/angular/angular/labels/hotlist%3A%20community-help).
[contributing]: https://github.com/angular/angular/blob/master/CONTRIBUTING.md
[quickstart]: https://angular.io/start
[changelog]: https://github.com/angular/angular/blob/master/CHANGELOG.md
[ng]: https://angular.io

View File

@ -1,25 +1,29 @@
# Angular en español [![Build Status](https://travis-ci.org/angular/angular.svg?branch=master)](https://travis-ci.org/angular/angular)
[![CircleCI](https://circleci.com/gh/angular/angular/tree/master.svg?style=shield)](https://circleci.com/gh/angular/angular/tree/master)
[![BrowserStack Status](https://www.browserstack.com/automate/badge.svg?badge_key=LzF3RzBVVGt6VWE2S0hHaC9uYllOZz09LS1BVjNTclBKV0x4eVRlcjA4QVY1M0N3PT0=--eb4ce8c8dc2c1c5b2b5352d473ee12a73ac20e06)](https://www.browserstack.com/automate/public-build/LzF3RzBVVGt6VWE2S0hHaC9uYllOZz09LS1BVjNTclBKV0x4eVRlcjA4QVY1M0N3PT0=--eb4ce8c8dc2c1c5b2b5352d473ee12a73ac20e06)
[![Join the chat at https://gitter.im/angular/angular](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/angular/angular?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![npm version](https://badge.fury.io/js/%40angular%2Fcore.svg)](https://www.npmjs.com/@angular/core)
Angular es una plataforma de desarrollo para construir aplicaciones web y móviles que usa
TypeScript/JavaScript y otros lenguajes de programación.
## ¿Quieres ayudar? # Angular
### Documentación en español Angular is a development platform for building mobile and desktop web applications using Typescript/JavaScript and other languages.
¿Quieres mejorar la documentación? ¡Excelente! Lee nuestras pautas para ## Quickstart
[colaborar](CONTRIBUTING.md) y luego revisa algunos de nuestras
[issues](https://github.com/angular-hispano/angular/issues).
### El framework [Get started in 5 minutes][quickstart].
La colaboración para corregir errores y agregar funciones en el framework debe realizarse en inglés a través ## Changelog
del repositorio [angular/angular](https://github.com/angular/angular) upstream.
## Guía rápida [Learn about the latest improvements][changelog].
[Comienza a usarlo en 5 minutos](https://docs.angular.lat/start). ## Want to help?
## Registro de cambios (Changelog) Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on our
guidelines for [contributing][contributing] and then check out one of our issues in the [hotlist: community-help](https://github.com/angular/angular/labels/hotlist%3A%20community-help).
[Últimas mejoras realizadas](CHANGELOG.md). [browserstack]: https://www.browserstack.com/automate/public-build/LzF3RzBVVGt6VWE2S0hHaC9uYllOZz09LS1BVjNTclBKV0x4eVRlcjA4QVY1M0N3PT0=--eb4ce8c8dc2c1c5b2b5352d473ee12a73ac20e06
[contributing]: https://github.com/angular/angular/blob/master/CONTRIBUTING.md
[quickstart]: https://angular.io/guide/quickstart
[changelog]: https://github.com/angular/angular/blob/master/CHANGELOG.md
[ng]: https://angular.io

164
WORKSPACE
View File

@ -1,108 +1,116 @@
workspace( workspace(name = "angular")
name = "angular",
managed_directories = {"@npm": ["node_modules"]},
)
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load(
"//packages/bazel:package.bzl",
"rules_angular_dependencies",
"rules_angular_dev_dependencies",
)
# Fetch rules_nodejs so we can install our npm dependencies
http_archive( http_archive(
name = "build_bazel_rules_nodejs", name = "io_bazel_rules_go",
sha256 = "84abf7ac4234a70924628baa9a73a5a5cbad944c4358cf9abdb4aab29c9a5b77", sha256 = "b7a62250a3a73277ade0ce306d22f122365b513f5402222403e507f2f997d421",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/1.7.0/rules_nodejs-1.7.0.tar.gz"], url = "https://github.com/bazelbuild/rules_go/releases/download/0.16.3/rules_go-0.16.3.tar.gz",
) )
# Check the rules_nodejs version and download npm dependencies # Uncomment for local bazel rules development
# Note: bazel (version 2 and after) will check the .bazelversion file so we don't need to #local_repository(
# assert on that. # name = "build_bazel_rules_nodejs",
load("@build_bazel_rules_nodejs//:index.bzl", "check_rules_nodejs_version", "node_repositories", "yarn_install") # path = "../rules_nodejs",
#)
#local_repository(
# name = "build_bazel_rules_typescript",
# path = "../rules_typescript",
#)
check_rules_nodejs_version(minimum_version_string = "1.7.0") # Angular Bazel users will call this function
rules_angular_dependencies()
# Setup the Node.js toolchain # Install transitive deps of rules_nodejs
node_repositories( load("@build_bazel_rules_nodejs//:package.bzl", "rules_nodejs_dependencies")
node_repositories = {
"12.14.1-darwin_amd64": ("node-v12.14.1-darwin-x64.tar.gz", "node-v12.14.1-darwin-x64", "0be10a28737527a1e5e3784d3ad844d742fe8b0718acd701fd48f718fd3af78f"),
"12.14.1-linux_amd64": ("node-v12.14.1-linux-x64.tar.xz", "node-v12.14.1-linux-x64", "07cfcaa0aa9d0fcb6e99725408d9e0b07be03b844701588e3ab5dbc395b98e1b"),
"12.14.1-windows_amd64": ("node-v12.14.1-win-x64.zip", "node-v12.14.1-win-x64", "1f96ccce3ba045ecea3f458e189500adb90b8bc1a34de5d82fc10a5bf66ce7e3"),
},
node_version = "12.14.1",
package_json = ["//:package.json"],
)
load("//integration:angular_integration_test.bzl", "npm_package_archives") rules_nodejs_dependencies()
yarn_install(
name = "npm",
manual_build_file_contents = npm_package_archives(),
package_json = "//:package.json",
yarn_lock = "//:yarn.lock",
)
# Install all bazel dependencies of the @npm npm packages
load("@npm//:install_bazel_dependencies.bzl", "install_bazel_dependencies")
install_bazel_dependencies()
# Load angular dependencies
load("//packages/bazel:package.bzl", "rules_angular_dev_dependencies")
# These are the dependencies only for us
rules_angular_dev_dependencies() rules_angular_dev_dependencies()
# Load protractor dependencies # Install transitive deps of rules_typescript
load("@npm_bazel_protractor//:package.bzl", "npm_bazel_protractor_dependencies") load("@build_bazel_rules_typescript//:package.bzl", "rules_typescript_dependencies")
npm_bazel_protractor_dependencies() rules_typescript_dependencies()
# Load karma dependencies #
load("@npm_bazel_karma//:package.bzl", "npm_bazel_karma_dependencies") # Point Bazel to WORKSPACEs that live in subdirectories
#
http_archive(
name = "rxjs",
sha256 = "72b0b4e517f43358f554c125e40e39f67688cd2738a8998b4a266981ed32f403",
strip_prefix = "package/src",
url = "https://registry.yarnpkg.com/rxjs/-/rxjs-6.3.3.tgz",
)
npm_bazel_karma_dependencies() # Point to the integration test workspace just so that Bazel doesn't descend into it
# when expanding the //... pattern
local_repository(
name = "bazel_integration_test",
path = "integration/bazel",
)
# Setup the rules_webtesting toolchain #
load("@io_bazel_rules_webtesting//web:repositories.bzl", "web_test_repositories") # Load and install our dependencies downloaded above.
#
load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories", "yarn_install")
check_bazel_version("0.20.0", """
You no longer need to install Bazel on your machine.
Angular has a dependency on the @bazel/bazel package which supplies it.
Try running `yarn bazel` instead.
(If you did run that, check that you've got a fresh `yarn install`)
""")
node_repositories(
node_version = "10.9.0",
package_json = ["//:package.json"],
preserve_symlinks = True,
yarn_version = "1.12.1",
)
local_repository(
name = "npm",
path = "tools/npm_workspace",
)
load("@io_bazel_rules_go//go:def.bzl", "go_register_toolchains", "go_rules_dependencies")
go_rules_dependencies()
go_register_toolchains()
load("@io_bazel_rules_webtesting//web:repositories.bzl", "browser_repositories", "web_test_repositories")
web_test_repositories() web_test_repositories()
load("//dev-infra/browsers:browser_repositories.bzl", "browser_repositories") browser_repositories(
chromium = True,
firefox = True,
)
browser_repositories() load("@build_bazel_rules_typescript//:defs.bzl", "ts_setup_workspace")
# Setup the rules_typescript tooolchain
load("@npm_bazel_typescript//:index.bzl", "ts_setup_workspace")
ts_setup_workspace() ts_setup_workspace()
# Setup the rules_sass toolchain load("@angular//:index.bzl", "ng_setup_workspace")
ng_setup_workspace()
##################################
# Skylark documentation generation
load("@io_bazel_rules_sass//sass:sass_repositories.bzl", "sass_repositories") load("@io_bazel_rules_sass//sass:sass_repositories.bzl", "sass_repositories")
sass_repositories() sass_repositories()
# Setup the skydoc toolchain
load("@io_bazel_skydoc//skylark:skylark.bzl", "skydoc_repositories") load("@io_bazel_skydoc//skylark:skylark.bzl", "skydoc_repositories")
skydoc_repositories() skydoc_repositories()
load("@bazel_toolchains//rules:environments.bzl", "clang_env")
load("@bazel_toolchains//rules:rbe_repo.bzl", "rbe_autoconfig")
rbe_autoconfig(
name = "rbe_ubuntu1604_angular",
# Need to specify a base container digest in order to ensure that we can use the checked-in
# platform configurations for the "ubuntu16_04" image. Otherwise the autoconfig rule would
# need to pull the image and run it in order determine the toolchain configuration. See:
# https://github.com/bazelbuild/bazel-toolchains/blob/3.2.0/configs/ubuntu16_04_clang/versions.bzl
base_container_digest = "sha256:5e750dd878df9fcf4e185c6f52b9826090f6e532b097f286913a428290622332",
# Note that if you change the `digest`, you might also need to update the
# `base_container_digest` to make sure marketplace.gcr.io/google/rbe-ubuntu16-04-webtest:<digest>
# and marketplace.gcr.io/google/rbe-ubuntu16-04:<base_container_digest> have
# the same Clang and JDK installed. Clang is needed because of the dependency on
# @com_google_protobuf. Java is needed for the Bazel's test executor Java tool.
digest = "sha256:f743114235a43355bf8324e2ba0fa6a597236fe06f7bc99aaa9ac703631c306b",
env = clang_env(),
registry = "marketplace.gcr.io",
# We can't use the default "ubuntu16_04" RBE image provided by the autoconfig because we need
# a specific Linux kernel that comes with "libx11" in order to run headless browser tests.
repository = "google/rbe-ubuntu16-04-webtest",
use_checked_in_confs = "Force",
)

View File

@ -1,12 +0,0 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# Googlebot uses an older version of Chrome
# For additional information see: https://developers.google.com/search/docs/guides/rendering
> 0.5%
last 2 major versions
Firefox ESR
not dead
IE 11

2
aio/.gitignore vendored
View File

@ -26,13 +26,11 @@
!.vscode/extensions.json !.vscode/extensions.json
# misc # misc
/.firebase/
/.sass-cache /.sass-cache
/connect.lock /connect.lock
/coverage /coverage
/libpeerconnection.log /libpeerconnection.log
debug.log debug.log
firebase-debug.log
npm-debug.log npm-debug.log
testem.log testem.log
/typings /typings

View File

@ -1,131 +1,135 @@
# Proyecto de documentación Angular (https://docs.angular.lat) # Angular documentation project (https://angular.io)
Todo en esta carpeta es parte del proyecto de documentación. Esto incluye: Everything in this folder is part of the documentation project. This includes
* El sitio web para mostrar la documentación * the web site for displaying the documentation
* La configuración de dgeni para convertir los archivos de origen a archivos renderizados que se pueden vizualizar en el sitio web. * the dgeni configuration for converting source files to rendered files that can be viewed in the web site.
* Las herramientas para establecer ejemplos para el desarrollo; y generar archivos en tiempo real y archivos zip desde los ejemplos. * the tooling for setting up examples for development; and generating live-example and zip files from the examples.
## Tareas de desarrollador ## Developer tasks
Nosotros usamos [Yarn](https://yarnpkg.com) para gestionar las dependencias y crear tareas de compilación. We use [Yarn](https://yarnpkg.com) to manage the dependencies and to run build tasks.
Debes ejecutar todas estas tareas desde la carpeta `angular/aio`. You should run all these tasks from the `angular/aio` folder.
Aquí están las tareas más importantes que podrías necesitar usar: Here are the most important tasks you might need to use:
* `yarn` - instalar todas las dependencias. * `yarn` - install all the dependencies.
* `yarn setup` - instalar todas las dependencias, boilerplate, stackblitz, zips y ejecuta dgeni en los documentos. * `yarn setup` - install all the dependencies, boilerplate, stackblitz, zips and run dgeni on the docs.
* `yarn setup-local` - igual que `setup`, pero crea los paquetes de Angular a partir del código y usa estas versiones construidas localmente (en lugar de las recuperadas desde npm) para aio y ejemplos de documentos boilerplate. * `yarn setup-local` - same as `setup`, but use the locally built Angular packages for aio and docs examples boilerplate.
* `yarn build` - crear una compilación de producción de la aplicación (después de instalar dependencias, boilerplate, etc). * `yarn build` - create a production build of the application (after installing dependencies, boilerplate, etc).
* `yarn build-local` - igual que `build`, pero usa `setup-local` en lugar de `setup`. * `yarn build-local` - same as `build`, but use `setup-local` instead of `setup`.
* `yarn build-local-with-viewengine` - igual que `build-local`, pero además también enciende el modo `ViewEngine` (pre-Ivy) en aio.
(Nota: Encender el modo `ViewEngine` en ejemplos de documentos, ver `yarn boilerplate:add:viewengine` abajo.)
* `yarn start` - ejecutar un servidor web de desarrollo que observa los archivos; luego crea el doc-viewer y vuelve a cargar la página, según sea necesario. * `yarn start` - run a development web server that watches the files; then builds the doc-viewer and reloads the page, as necessary.
* `yarn serve-and-sync` - ejecutar ambos, el `docs-watch` y `start` en la misma consola. * `yarn serve-and-sync` - run both the `docs-watch` and `start` in the same console.
* `yarn lint` - comprobar que el código del doc-viewer sigue nuestras reglas de estilo. * `yarn lint` - check that the doc-viewer code follows our style rules.
* `yarn test` - observar todos los archivos de origen, para el doc-viewer, y ejecuta todas las pruebas unitarias cuando haya algún cambio. * `yarn test` - watch all the source files, for the doc-viewer, and run all the unit tests when any change.
* `yarn test --watch=false` -ejecutar todas las pruebas unitarias una sola vez. * `yarn test --watch=false` - run all the unit tests once.
* `yarn e2e` - ejecutar todas las pruebas de e2e para el doc-viewer. * `yarn e2e` - run all the e2e tests for the doc-viewer.
* `yarn docs` - generar toda la documentación desde los archivos fuente. * `yarn docs` - generate all the docs from the source files.
* `yarn docs-watch` - observar el código Angular, los archivos de documentación y ejecutar un 'doc-gen' en corto circuito para los documentos que fueron cambiados. * `yarn docs-watch` - watch the Angular source and the docs files and run a short-circuited doc-gen for the docs that changed.
* `yarn docs-lint` - comprobar que el código del documento generado sigue nuestras reglas de estilo. * `yarn docs-lint` - check that the doc gen code follows our style rules.
* `yarn docs-test` - ejecutar las pruebas unitarias para el código de generación de doc. * `yarn docs-test` - run the unit tests for the doc generation code.
* `yarn boilerplate:add` - generar todo el código boilerplate para los ejemplos, para que puedan ejecutarse localmente. * `yarn boilerplate:add` - generate all the boilerplate code for the examples, so that they can be run locally. Add the option `--local` to use your local version of Angular contained in the "dist" folder.
* `yarn boilerplate:add:viewengine` - igual que `boilerplate:add` pero también enciende el modo `ViewEngine` (pre-Ivy). * `yarn boilerplate:remove` - remove all the boilerplate code that was added via `yarn boilerplate:add`.
* `yarn generate-stackblitz` - generate the stackblitz files that are used by the `live-example` tags in the docs.
* `yarn generate-zips` - generate the zip files from the examples. Zip available via the `live-example` tags in the docs.
* `yarn boilerplate:remove` - eliminar todo el código boilerplate que fue añadido a través`yarn boilerplate:add`. * `yarn example-e2e` - run all e2e tests for examples
* `yarn generate-stackblitz` - generar los archivos stackblitz que están usados por la etiqueta `live-example` en documentos. - `yarn example-e2e --setup` - force webdriver update & other setup, then run tests
* `yarn generate-zips` - generar los archivos zip desde los ejemplos. Zip está disponible a través de la etiqueta `live-example` en los documentos. - `yarn example-e2e --filter=foo` - limit e2e tests to those containing the word "foo"
- `yarn example-e2e --setup --local` - run e2e tests with the local version of Angular contained in the "dist" folder
* `yarn example-e2e` - ejecutar todas las pruebas e2e para ejemplos. Opciones disponibles: ## Developing on Windows
- `--setup`: generar boilerplate, forzar la actualización del controlador web y otras configuraciones, luego ejecutar las pruebas. The `packages/` directory may contain Linux-specific symlinks, which are not recognized by Windows.
- `--local`: ejecutar pruebas e2e con la versión local de Angular contenida en la carpeta "dist". These unresolved links cause the docs generation process to fail because it cannot locate certain files.
_Requiere `--setup` para que surta efecto._
- `--viewengine`: ejecutar pruebas e2e en modo `ViewEngine` (pre-Ivy).
- `--filter=foo`: limitar pruebas e2e a las que contienen la palabra "foo".
> **Nota para usuarios Windows** > Hint: The following steps require administration rights or [Windows Developer Mode](https://docs.microsoft.com/en-us/windows/uwp/get-started/enable-your-device-for-development) enabled!
>
> Configurar los ejemplos implica crear algunos [enlaces simbólicos](https://es.wikipedia.org/wiki/Enlace_simb%C3%B3lico) (ver [Aquí](./tools/examples/README.md#symlinked-node_modules) para más detalles). En Windows, esto requiere tener [Habilitado el Modo de desarrollador ](https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10) (compatible con Windows 10 o más reciente) o ejecutar los comandos de configuración cómo administrador.
>
> Los comandos afectados son:
> - `yarn setup` / `yarn setup-*`
> - `yarn build` / `yarn build-*`
> - `yarn boilerplate:add`
> - `yarn example-e2e --setup`
## Usando ServiceWorker localmente To fix this problem, run `scripts/windows/create-symlinks.sh`. This command creates temporary files where the symlinks used to be. Make sure not to commit those files with your documentation changes.
When you are done making and testing your documentation changes, you can restore the original symlinks and delete the temporary files by running `scripts/windows/remove-symlinks.sh`.
Ejecutando `yarn start` (incluso cuando se apunta explícitamente al modo de producción) no configura el It's necessary to remove the temporary files, because otherwise they're displayed as local changes in your git working copy and certain operations are blocked.
ServiceWorker. Si quieres probar el ServiceWorker localmente, puedes usar `yarn build` y luego
ejecutar los archivos en `dist/` con `yarn http-server dist -p 4200`. ## Using ServiceWorker locally
Running `yarn start` (even when explicitly targeting production mode) does not set up the
ServiceWorker. If you want to test the ServiceWorker locally, you can use `yarn build` and then
serve the files in `dist/` with `yarn http-server dist -p 4200`.
## Guía de autoría ## Guide to authoring
Existen dos tipos de contenido en la documentación:
* **Documentación de API**: descripciones de los módulos, clases, interfaces, decoradores, etc que son parte de la plataforma Angular. There are two types of content in the documentation:
La documentacion de API está generada directamente desde el código fuente.
El código fuente está contenido en archivos TypeScript , almacenados en la carpeta `angular/packages`.
Cada elemento de la API puede tener un comentario anterior, el cual contiene etiquetas y contenido de estilos JSDoc.
El contenido está escrito en markdown.
* **Otro contenido**: guias, tutoriales, y otro material de marketing. * **API docs**: descriptions of the modules, classes, interfaces, decorators, etc that make up the Angular platform.
Todos los demás contenidos se escriben utilizando markdown en archivos de texto, ubicados en la carpeta `angular/aio/content`. API docs are generated directly from the source code.
Más específicamente, hay subcarpetas que contienen tipos particulares de contenido: guías, tutoriales y marketing. The source code is contained in TypeScript files, located in the `angular/packages` folder.
Each API item may have a preceding comment, which contains JSDoc style tags and content.
The content is written in markdown.
* **Ejempos de código**: los ejemplos de código deben ser comprobables para garantizar su precisión. * **Other content**: guides, tutorials, and other marketing material.
Además, nuestros ejemplos tienen un aspecto específico y permiten al usuario copiar el código fuente. Para mayor All other content is written using markdown in text files, located in the `angular/aio/content` folder.
ejemplos se representan en una interfaz con pestañas (e.g. template, HTML, y TypeScript en pestañas separadas). Adicionalmente, algunos son ejemplos en acción, que proporcionan enlaces donde se puede editar el código, ejecutar, y/o descargar. Para obtener más detalles sobre cómo trabajar con ejemplos de código, lea los [fragmentos de código](https://docs.angular.lat/guide/docs-style-guide#code-snippets), [código fuente de marcado ](https://docs.angular.lat/guide/docs-style-guide#source-code-markup), y [ ejemplos en acción ](https://docs.angular.lat/guide/docs-style-guide#live-examples) paginas de los [ autores de guías de estilo ](https://docs.angular.lat/guide/docs-style-guide). More specifically, there are sub-folders that contain particular types of content: guides, tutorial and marketing.
Usamos la herramienta [dgeni](https://github.com/angular/dgeni) para convertir estos archivos en docs que se pueden ver en el doc-viewer. * **Code examples**: code examples need to be testable to ensure their accuracy.
Las [guías de estilo para Autores](https://docs.angular.lat/guide/docs-style-guide) prescriben pautas para Also, our examples have a specific look and feel and allow the user to copy the source code. For larger
escribir páginas de guía, explica cómo usar la documentación de clases y componentes, y cómo marcar el código fuente para producir fragmentos de código. examples they are rendered in a tabbed interface (e.g. template, HTML, and TypeScript on separate
tabs). Additionally, some are live examples, which provide links where the code can be edited, executed, and/or downloaded. For details on working with code examples, please read the [Code snippets](https://angular.io/guide/docs-style-guide#code-snippets), [Source code markup](https://angular.io/guide/docs-style-guide#source-code-markup), and [Live examples](https://angular.io/guide/docs-style-guide#live-examples) pages of the [Authors Style Guide](https://angular.io/guide/docs-style-guide).
### Generando documentos completos We use the [dgeni](https://github.com/angular/dgeni) tool to convert these files into docs that can be viewed in the doc-viewer.
La principal tarea para generar los documentos es `yarn docs`. Esto procesará todos los archivos fuente (API y otros), extrayendo la documentación y generando archivos JSON que pueden ser consumidos por el doc-viewer. The [Authors Style Guide](https://angular.io/guide/docs-style-guide) prescribes guidelines for
writing guide pages, explains how to use the documentation classes and components, and how to markup sample source code to produce code snippets.
### Generación parcial de doc para editores ### Generating the complete docs
La generación completa de documentos puede llevar hasta un minuto. Eso es demasiado lento para la creación y edición eficiente de documentos. The main task for generating the docs is `yarn docs`. This will process all the source files (API and other),
extracting the documentation and generating JSON files that can be consumed by the doc-viewer.
Puedes ealizar pequeños cambios en un editor inteligente que muestre un markdown con formato: ### Partial doc generation for editors
>En VS Code, _Cmd-K, V_ abre la vista previa de markdown en el panel lateral; _Cmd-B_ alterna la barra izquierda
Puedes también mirar los cambios que se muestran correctamente en el doc-viewer Full doc generation can take up to one minute. That's too slow for efficient document creation and editing.
con un tiempo de ciclo rápido de edición / visualización.
Para este propósito, usa la tarea `yarn docs-watch`, que observa los cambios en los archivos de origen y solo vuelve a procesar los archivos necesarios para generar los documentos relacionados con el archivo que ha cambiado. You can make small changes in a smart editor that displays formatted markdown:
Dado que esta tarea tiene accesos directos, es mucho más rápido (a menudo menos de 1 segundo) pero no producirá contenido de fidelidad completa. Por ejemplo, los enlaces a otros documentoss y ejemplos de código pueden no mostrarse correctamente. Esto se nota especialmente en los enlaces a otros documentos y en los ejemplos incrustados, que no siempre se representan correctamente. >In VS Code, _Cmd-K, V_ opens markdown preview in side pane; _Cmd-B_ toggles left sidebar
La configuración general es la siguiente: You also want to see those changes displayed properly in the doc viewer
with a quick, edit/view cycle time.
* Abrir una terminal, estar seguro que las dependencias están instaladas; ejecutar una generación inicial del doc; luego iniciar el doc-viewer: For this purpose, use the `yarn docs-watch` task, which watches for changes to source files and only
re-processes the the files necessary to generate the docs that are related to the file that has changed.
Since this task takes shortcuts, it is much faster (often less than 1 second) but it won't produce full
fidelity content. For example, links to other docs and code examples may not render correctly. This is
most particularly noticed in links to other docs and in the embedded examples, which may not always render
correctly.
The general setup is as follows:
* Open a terminal, ensure the dependencies are installed; run an initial doc generation; then start the doc-viewer:
```bash ```bash
yarn setup yarn setup
yarn start yarn start
``` ```
* Abrir una segunda terminal e iniciar el observador de documentos. * Open a second terminal and start watching the docs
```bash ```bash
yarn docs-watch yarn docs-watch
``` ```
>Alternativamente, prueba el comando fusionado `serve-and-sync` que crea, observa y ejecuta en la misma ventana de la terminal >Alternatively, try the consolidated `serve-and-sync` command that builds, watches and serves in the same terminal window
```bash ```bash
yarn serve-and-sync yarn serve-and-sync
``` ```
* Abre un navegador con la siguiente dirección https://localhost:4200/ y navega hasta el documento en el que quieras trabajar. * Open a browser at https://localhost:4200/ and navigate to the document on which you want to work.
Puedes automáticamente abrir el navegador utilizando `yarn start -o` en la primera terminal. You can automatically open the browser by using `yarn start -o` in the first terminal.
* Realiza cambios en la página de documentación asociada o en los archivos de ejemplo. Cada vez que un archivo es guardado, la documentación se regenerará, la aplicación se reconstruirá y la página se volverá a cargar. * Make changes to the page's associated doc or example files. Every time a file is saved, the doc will
be regenerated, the app will rebuild and the page will reload.
*Si recibes un error de compilación acerca de los ejemplos o cualquier otro error, asegúrate de consultar las * If you get a build error complaining about examples or any other odd behavior, be sure to consult
[guías de estilo para Autores](https://angular.io/guide/docs-style-guide) para más información. the [Authors Style Guide](https://angular.io/guide/docs-style-guide).

View File

@ -1,5 +1,5 @@
# Image metadata and config # Image metadata and config
FROM debian:buster FROM debian:jessie
LABEL name="angular.io PR preview" \ LABEL name="angular.io PR preview" \
description="This image implements the PR preview functionality for angular.io." \ description="This image implements the PR preview functionality for angular.io." \
@ -26,8 +26,8 @@ ARG AIO_GITHUB_ORGANIZATION=angular
ARG TEST_AIO_GITHUB_ORGANIZATION=test-org ARG TEST_AIO_GITHUB_ORGANIZATION=test-org
ARG AIO_GITHUB_REPO=angular ARG AIO_GITHUB_REPO=angular
ARG TEST_AIO_GITHUB_REPO=test-repo ARG TEST_AIO_GITHUB_REPO=test-repo
ARG AIO_GITHUB_TEAM_SLUGS=aio-auto-previews,aio-contributors ARG AIO_GITHUB_TEAM_SLUGS=team,aio-contributors
ARG TEST_AIO_GITHUB_TEAM_SLUGS=test-team-1,test-team-2 ARG TEST_AIO_GITHUB_TEAM_SLUGS=team,aio-contributors
ARG AIO_NGINX_HOSTNAME=$AIO_DOMAIN_NAME ARG AIO_NGINX_HOSTNAME=$AIO_DOMAIN_NAME
ARG TEST_AIO_NGINX_HOSTNAME=$TEST_AIO_DOMAIN_NAME ARG TEST_AIO_NGINX_HOSTNAME=$TEST_AIO_DOMAIN_NAME
ARG AIO_NGINX_PORT_HTTP=80 ARG AIO_NGINX_PORT_HTTP=80
@ -37,10 +37,10 @@ ARG TEST_AIO_NGINX_PORT_HTTPS=4433
ARG AIO_SIGNIFICANT_FILES_PATTERN='^(?:aio|packages)/(?!.*[._]spec\\.[jt]s$)' ARG AIO_SIGNIFICANT_FILES_PATTERN='^(?:aio|packages)/(?!.*[._]spec\\.[jt]s$)'
ARG TEST_AIO_SIGNIFICANT_FILES_PATTERN=$AIO_SIGNIFICANT_FILES_PATTERN ARG TEST_AIO_SIGNIFICANT_FILES_PATTERN=$AIO_SIGNIFICANT_FILES_PATTERN
ARG AIO_TRUSTED_PR_LABEL="aio: preview" ARG AIO_TRUSTED_PR_LABEL="aio: preview"
ARG TEST_AIO_TRUSTED_PR_LABEL=$AIO_TRUSTED_PR_LABEL ARG TEST_AIO_TRUSTED_PR_LABEL="aio: preview"
ARG AIO_PREVIEW_SERVER_HOSTNAME=preview.localhost ARG AIO_PREVIEW_SERVER_HOSTNAME=preview.localhost
ARG TEST_AIO_PREVIEW_SERVER_HOSTNAME=$AIO_PREVIEW_SERVER_HOSTNAME ARG TEST_AIO_PREVIEW_SERVER_HOSTNAME=preview.localhost
ARG AIO_ARTIFACT_MAX_SIZE=26214400 ARG AIO_ARTIFACT_MAX_SIZE=20971520
ARG TEST_AIO_ARTIFACT_MAX_SIZE=200 ARG TEST_AIO_ARTIFACT_MAX_SIZE=200
ARG AIO_PREVIEW_SERVER_PORT=3000 ARG AIO_PREVIEW_SERVER_PORT=3000
ARG TEST_AIO_PREVIEW_SERVER_PORT=3001 ARG TEST_AIO_PREVIEW_SERVER_PORT=3001
@ -72,29 +72,25 @@ RUN mkdir /var/log/aio
# Add extra package sources # Add extra package sources
RUN apt-get update -y && apt-get install -y curl=7.64.0-4+deb10u1 RUN apt-get update -y && apt-get install -y curl
RUN curl --silent --show-error --location https://deb.nodesource.com/setup_12.x | bash - RUN curl --silent --show-error --location https://deb.nodesource.com/setup_10.x | bash -
RUN curl --silent --show-error https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - RUN curl --silent --show-error https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
RUN echo "deb http://ftp.debian.org/debian jessie-backports main" | tee /etc/apt/sources.list.d/backports.list
# Install packages # Install packages
# NOTE: Some packages (such as `nginx`, `nodejs`, `openssl`) make older versions unavailable on the
# repositories, so we cannot pin to specific versions for these packages :(
# See for example:
# - https://github.com/nodesource/distributions/issues/33
# - https://askubuntu.com/questions/715104/how-can-i-downgrade-openssl-via-apt-get
RUN apt-get update -y && apt-get install -y \ RUN apt-get update -y && apt-get install -y \
cron=3.0pl1-134+deb10u1 \ chkconfig \
dnsmasq=2.80-1 \ cron \
nano=3.2-3 \ dnsmasq \
nginx \ nano \
nodejs \ nodejs \
openssl \ openssl \
rsyslog=8.1901.0-1 \ rsyslog \
vim=2:8.1.0875-5 \ yarn
yarn=1.22.4-1 RUN apt-get install -t jessie-backports -y nginx
RUN yarn global add pm2@4.4.0 RUN yarn global add pm2@2
# Set up log rotation # Set up log rotation
@ -155,7 +151,8 @@ RUN sed -i "s|{{\$AIO_PREVIEW_SERVER_PORT}}|$TEST_AIO_PREVIEW_SERVER_PORT|g" /et
# Set up pm2 # Set up pm2
RUN pm2 startup --user root > /dev/null RUN pm2 startup systemv -u root > /dev/null
RUN chkconfig pm2-root on
# Set up the shell scripts # Set up the shell scripts
@ -167,7 +164,8 @@ RUN find $AIO_SCRIPTS_SH_DIR -maxdepth 1 -type f -printf "%P\n" \
# Set up the Node.js scripts # Set up the Node.js scripts
COPY scripts-js/ $AIO_SCRIPTS_JS_DIR/ COPY scripts-js/ $AIO_SCRIPTS_JS_DIR/
RUN yarn --cwd="$AIO_SCRIPTS_JS_DIR/" install --production --frozen-lockfile WORKDIR $AIO_SCRIPTS_JS_DIR/
RUN yarn install --production --frozen-lockfile
# Set up health check # Set up health check

View File

@ -35,7 +35,6 @@ export class BuildCleaner {
]); ]);
} catch (error) { } catch (error) {
this.logger.error('ERROR:', error); this.logger.error('ERROR:', error);
throw error;
} }
} }

View File

@ -1,4 +1,5 @@
import * as express from 'express'; import * as express from 'express';
import {promisify} from 'util';
import {PreviewServerError} from './preview-error'; import {PreviewServerError} from './preview-error';
/** /**
@ -12,7 +13,7 @@ export async function respondWithError(res: express.Response, err: any): Promise
} }
res.status(err.status); res.status(err.status);
return new Promise(resolve => res.end(err.message, resolve)); await promisify(res.end.bind(res))(err.message);
} }
/** /**

View File

@ -1,6 +1,7 @@
// Imports // Imports
import * as cp from 'child_process'; import * as cp from 'child_process';
import * as fs from 'fs'; import * as fs from 'fs';
import * as http from 'http';
import * as path from 'path'; import * as path from 'path';
import * as shell from 'shelljs'; import * as shell from 'shelljs';
import {AIO_DOWNLOADS_DIR, HIDDEN_DIR_PREFIX} from '../common/constants'; import {AIO_DOWNLOADS_DIR, HIDDEN_DIR_PREFIX} from '../common/constants';
@ -93,7 +94,7 @@ class Helper {
return fs.readFileSync(absFilePath, 'utf8'); return fs.readFileSync(absFilePath, 'utf8');
} }
public runCmd(cmd: string, opts: cp.ExecOptions = {}): Promise<CmdResult> { public runCmd(cmd: string, opts: cp.ExecFileOptions = {}): Promise<CmdResult> {
return new Promise(resolve => { return new Promise(resolve => {
const proc = cp.exec(cmd, opts, (err, stdout, stderr) => resolve({success: !err, err, stdout, stderr})); const proc = cp.exec(cmd, opts, (err, stdout, stderr) => resolve({success: !err, err, stdout, stderr}));
this.createCleanUpFn(() => proc.kill()); this.createCleanUpFn(() => proc.kill());
@ -101,10 +102,21 @@ class Helper {
} }
public runForAllSupportedSchemes(suiteFactory: TestSuiteFactory): void { public runForAllSupportedSchemes(suiteFactory: TestSuiteFactory): void {
Object.entries(this.portPerScheme).forEach(([scheme, port]) => suiteFactory(scheme, port)); Object.keys(this.portPerScheme).forEach(scheme => suiteFactory(scheme, this.portPerScheme[scheme]));
} }
public verifyResponse(status: number, regex: string | RegExp = /^/): VerifyCmdResultFn { public verifyResponse(status: number | [number, string], regex: string | RegExp = /^/): VerifyCmdResultFn {
let statusCode: number;
let statusText: string;
if (Array.isArray(status)) {
statusCode = status[0];
statusText = status[1];
} else {
statusCode = status;
statusText = http.STATUS_CODES[statusCode] || 'UNKNOWN_STATUS_CODE';
}
return (result: CmdResult) => { return (result: CmdResult) => {
const [headers, body] = result.stdout. const [headers, body] = result.stdout.
split(/(?:\r?\n){2,}/). split(/(?:\r?\n){2,}/).
@ -119,7 +131,7 @@ class Helper {
} }
expect(result.success).toBe(true); expect(result.success).toBe(true);
expect(headers).toMatch(new RegExp(`HTTP/(?:1\\.1|2) ${status} `)); expect(headers).toContain(`${statusCode} ${statusText}`);
expect(body).toMatch(regex); expect(body).toMatch(regex);
}; };
} }

View File

@ -15,7 +15,7 @@ describe(`nginx`, () => {
afterEach(() => h.cleanUp()); afterEach(() => h.cleanUp());
it('should redirect HTTP to HTTPS', async () => { it('should redirect HTTP to HTTPS', done => {
const httpHost = `${AIO_NGINX_HOSTNAME}:${AIO_NGINX_PORT_HTTP}`; const httpHost = `${AIO_NGINX_HOSTNAME}:${AIO_NGINX_PORT_HTTP}`;
const httpsHost = `${AIO_NGINX_HOSTNAME}:${AIO_NGINX_PORT_HTTPS}`; const httpsHost = `${AIO_NGINX_HOSTNAME}:${AIO_NGINX_PORT_HTTPS}`;
const urlMap = { const urlMap = {
@ -24,15 +24,16 @@ describe(`nginx`, () => {
[`http://foo.${httpHost}/`]: `https://foo.${httpsHost}/`, [`http://foo.${httpHost}/`]: `https://foo.${httpsHost}/`,
}; };
const verifyRedirection = async (fromUrl: string, toUrl: string) => { const verifyRedirection = (httpUrl: string) => h.runCmd(`curl -i ${httpUrl}`).then(result => {
const result = await h.runCmd(`curl -i ${fromUrl}`);
h.verifyResponse(307)(result); h.verifyResponse(307)(result);
const headers = result.stdout.split(/(?:\r?\n){2,}/)[0]; const headers = result.stdout.split(/(?:\r?\n){2,}/)[0];
expect(headers).toContain(`Location: ${toUrl}`); expect(headers).toContain(`Location: ${urlMap[httpUrl]}`);
}; });
await Promise.all(Object.entries(urlMap).map(urls => verifyRedirection(...urls))); Promise.
all(Object.keys(urlMap).map(verifyRedirection)).
then(done);
}); });
@ -61,15 +62,15 @@ describe(`nginx`, () => {
}); });
it('should return /index.html', async () => { it('should return /index.html', done => {
const origin = `${scheme}://pr${pr}-${shortSha9}.${host}`; const origin = `${scheme}://pr${pr}-${shortSha9}.${host}`;
const bodyRegex = new RegExp(`^PR: ${pr} | SHA: ${sha9} | File: /index\\.html$`); const bodyRegex = new RegExp(`^PR: ${pr} | SHA: ${sha9} | File: /index\\.html$`);
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${origin}/index.html`).then(h.verifyResponse(200, bodyRegex)), h.runCmd(`curl -iL ${origin}/index.html`).then(h.verifyResponse(200, bodyRegex)),
h.runCmd(`curl -iL ${origin}/`).then(h.verifyResponse(200, bodyRegex)), h.runCmd(`curl -iL ${origin}/`).then(h.verifyResponse(200, bodyRegex)),
h.runCmd(`curl -iL ${origin}`).then(h.verifyResponse(200, bodyRegex)), h.runCmd(`curl -iL ${origin}`).then(h.verifyResponse(200, bodyRegex)),
]); ]).then(done);
}); });
@ -89,11 +90,12 @@ describe(`nginx`, () => {
}); });
it('should return /foo/bar.js', async () => { it('should return /foo/bar.js', done => {
const bodyRegex = new RegExp(`^PR: ${pr} | SHA: ${sha9} | File: /foo/bar\\.js$`); const bodyRegex = new RegExp(`^PR: ${pr} | SHA: ${sha9} | File: /foo/bar\\.js$`);
await h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}/foo/bar.js`). h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}/foo/bar.js`).
then(h.verifyResponse(200, bodyRegex)); then(h.verifyResponse(200, bodyRegex)).
then(done);
}); });
@ -109,46 +111,47 @@ describe(`nginx`, () => {
}); });
it('should respond with 403 for directories', async () => { it('should respond with 403 for directories', done => {
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}/foo/`).then(h.verifyResponse(403)), h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}/foo/`).then(h.verifyResponse(403)),
h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}/foo`).then(h.verifyResponse(403)), h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}/foo`).then(h.verifyResponse(403)),
]); ]).then(done);
}); });
it('should respond with 404 for unknown paths to files', async () => { it('should respond with 404 for unknown paths to files', done => {
await h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}/foo/baz.css`). h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}/foo/baz.css`).
then(h.verifyResponse(404)); then(h.verifyResponse(404)).
then(done);
}); });
it('should rewrite to \'index.html\' for unknown paths that don\'t look like files', async () => { it('should rewrite to \'index.html\' for unknown paths that don\'t look like files', done => {
const origin = `${scheme}://pr${pr}-${shortSha9}.${host}`; const origin = `${scheme}://pr${pr}-${shortSha9}.${host}`;
const bodyRegex = new RegExp(`^PR: ${pr} | SHA: ${sha9} | File: /index\\.html$`); const bodyRegex = new RegExp(`^PR: ${pr} | SHA: ${sha9} | File: /index\\.html$`);
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${origin}/foo/baz`).then(h.verifyResponse(200, bodyRegex)), h.runCmd(`curl -iL ${origin}/foo/baz`).then(h.verifyResponse(200, bodyRegex)),
h.runCmd(`curl -iL ${origin}/foo/baz/`).then(h.verifyResponse(200, bodyRegex)), h.runCmd(`curl -iL ${origin}/foo/baz/`).then(h.verifyResponse(200, bodyRegex)),
]); ]).then(done);
}); });
it('should respond with 404 for unknown PRs/SHAs', async () => { it('should respond with 404 for unknown PRs/SHAs', done => {
const otherPr = 54321; const otherPr = 54321;
const otherShortSha = computeShortSha('8'.repeat(40)); const otherShortSha = computeShortSha('8'.repeat(40));
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${scheme}://pr${pr}9-${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://pr${pr}9-${shortSha9}.${host}`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://pr${otherPr}-${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://pr${otherPr}-${shortSha9}.${host}`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}9.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}9.${host}`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://pr${pr}-${otherShortSha}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://pr${pr}-${otherShortSha}.${host}`).then(h.verifyResponse(404)),
]); ]).then(done);
}); });
it('should respond with 404 if the subdomain format is wrong', async () => { it('should respond with 404 if the subdomain format is wrong', done => {
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${scheme}://xpr${pr}-${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://xpr${pr}-${shortSha9}.${host}`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://prx${pr}-${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://prx${pr}-${shortSha9}.${host}`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://xx${pr}-${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://xx${pr}-${shortSha9}.${host}`).then(h.verifyResponse(404)),
@ -157,25 +160,26 @@ describe(`nginx`, () => {
h.runCmd(`curl -iL ${scheme}://${pr}-${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://${pr}-${shortSha9}.${host}`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://pr${pr}${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://pr${pr}${shortSha9}.${host}`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://pr${pr}_${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://pr${pr}_${shortSha9}.${host}`).then(h.verifyResponse(404)),
]); ]).then(done);
}); });
it('should reject PRs with leading zeros', async () => { it('should reject PRs with leading zeros', done => {
await h.runCmd(`curl -iL ${scheme}://pr0${pr}-${shortSha9}.${host}`). h.runCmd(`curl -iL ${scheme}://pr0${pr}-${shortSha9}.${host}`).
then(h.verifyResponse(404)); then(h.verifyResponse(404)).
then(done);
}); });
it('should accept SHAs with leading zeros (but not trim the zeros)', async () => { it('should accept SHAs with leading zeros (but not trim the zeros)', done => {
const bodyRegex9 = new RegExp(`^PR: ${pr} | SHA: ${sha9} | File: /index\\.html$`); const bodyRegex9 = new RegExp(`^PR: ${pr} | SHA: ${sha9} | File: /index\\.html$`);
const bodyRegex0 = new RegExp(`^PR: ${pr} | SHA: ${sha0} | File: /index\\.html$`); const bodyRegex0 = new RegExp(`^PR: ${pr} | SHA: ${sha0} | File: /index\\.html$`);
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${scheme}://pr${pr}-0${shortSha9}.${host}`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://pr${pr}-0${shortSha9}.${host}`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}`).then(h.verifyResponse(200, bodyRegex9)), h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha9}.${host}`).then(h.verifyResponse(200, bodyRegex9)),
h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha0}.${host}`).then(h.verifyResponse(200, bodyRegex0)), h.runCmd(`curl -iL ${scheme}://pr${pr}-${shortSha0}.${host}`).then(h.verifyResponse(200, bodyRegex0)),
]); ]).then(done);
}); });
}); });
@ -227,23 +231,23 @@ describe(`nginx`, () => {
describe(`${host}/health-check`, () => { describe(`${host}/health-check`, () => {
it('should respond with 200', async () => { it('should respond with 200', done => {
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${scheme}://${host}/health-check`).then(h.verifyResponse(200)), h.runCmd(`curl -iL ${scheme}://${host}/health-check`).then(h.verifyResponse(200)),
h.runCmd(`curl -iL ${scheme}://${host}/health-check/`).then(h.verifyResponse(200)), h.runCmd(`curl -iL ${scheme}://${host}/health-check/`).then(h.verifyResponse(200)),
]); ]).then(done);
}); });
it('should respond with 404 if the path does not match exactly', async () => { it('should respond with 404 if the path does not match exactly', done => {
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${scheme}://${host}/health-check/foo`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://${host}/health-check/foo`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://${host}/health-check-foo`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://${host}/health-check-foo`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://${host}/health-checknfoo`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://${host}/health-checknfoo`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://${host}/foo/health-check`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://${host}/foo/health-check`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://${host}/foo-health-check`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://${host}/foo-health-check`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${scheme}://${host}/foonhealth-check`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${scheme}://${host}/foonhealth-check`).then(h.verifyResponse(404)),
]); ]).then(done);
}); });
}); });
@ -255,10 +259,10 @@ describe(`nginx`, () => {
it('should disallow non-GET requests', async () => { it('should disallow non-GET requests', async () => {
await Promise.all([ await Promise.all([
h.runCmd(`curl -iLX POST ${baseUrl}/42`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX POST ${baseUrl}/42`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX PUT ${baseUrl}/42`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX PUT ${baseUrl}/42`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX PATCH ${baseUrl}/42`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX PATCH ${baseUrl}/42`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX DELETE ${baseUrl}/42`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX DELETE ${baseUrl}/42`).then(h.verifyResponse([405, 'Not Allowed'])),
]); ]);
}); });
@ -287,28 +291,29 @@ describe(`nginx`, () => {
describe(`${host}/circle-build`, () => { describe(`${host}/circle-build`, () => {
it('should disallow non-POST requests', async () => { it('should disallow non-POST requests', done => {
const url = `${scheme}://${host}/circle-build`; const url = `${scheme}://${host}/circle-build`;
await Promise.all([ Promise.all([
h.runCmd(`curl -iLX GET ${url}`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX GET ${url}`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX PUT ${url}`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX PUT ${url}`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX PATCH ${url}`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX PATCH ${url}`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX DELETE ${url}`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX DELETE ${url}`).then(h.verifyResponse([405, 'Not Allowed'])),
]); ]).then(done);
}); });
it('should pass requests through to the preview server', async () => { it('should pass requests through to the preview server', done => {
await h.runCmd(`curl -iLX POST ${scheme}://${host}/circle-build`). h.runCmd(`curl -iLX POST ${scheme}://${host}/circle-build`).
then(h.verifyResponse(400, /Incorrect body content. Expected JSON/)); then(h.verifyResponse(400, /Incorrect body content. Expected JSON/)).
then(done);
}); });
it('should respond with 404 for unknown paths', async () => { it('should respond with 404 for unknown paths', done => {
const cmdPrefix = `curl -iLX POST ${scheme}://${host}`; const cmdPrefix = `curl -iLX POST ${scheme}://${host}`;
await Promise.all([ Promise.all([
h.runCmd(`${cmdPrefix}/foo/circle-build/`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/foo/circle-build/`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/foo-circle-build/`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/foo-circle-build/`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/fooncircle-build/`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/fooncircle-build/`).then(h.verifyResponse(404)),
@ -317,7 +322,7 @@ describe(`nginx`, () => {
h.runCmd(`${cmdPrefix}/circle-buildnfoo/`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/circle-buildnfoo/`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/circle-build/pr`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/circle-build/pr`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/circle-build/42`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/circle-build/42`).then(h.verifyResponse(404)),
]); ]).then(done);
}); });
}); });
@ -327,33 +332,38 @@ describe(`nginx`, () => {
const url = `${scheme}://${host}/pr-updated`; const url = `${scheme}://${host}/pr-updated`;
it('should disallow non-POST requests', async () => { it('should disallow non-POST requests', done => {
await Promise.all([ Promise.all([
h.runCmd(`curl -iLX GET ${url}`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX GET ${url}`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX PUT ${url}`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX PUT ${url}`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX PATCH ${url}`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX PATCH ${url}`).then(h.verifyResponse([405, 'Not Allowed'])),
h.runCmd(`curl -iLX DELETE ${url}`).then(h.verifyResponse(405)), h.runCmd(`curl -iLX DELETE ${url}`).then(h.verifyResponse([405, 'Not Allowed'])),
]); ]).then(done);
}); });
it('should pass requests through to the preview server', async () => { it('should pass requests through to the preview server', done => {
await h.runCmd(`curl -iLX POST --header "Content-Type: application/json" ${url}`). const cmdPrefix = `curl -iLX POST --header "Content-Type: application/json"`;
then(h.verifyResponse(400, /Missing or empty 'number' field/));
const cmd1 = `${cmdPrefix} ${url}`;
Promise.all([
h.runCmd(cmd1).then(h.verifyResponse(400, /Missing or empty 'number' field/)),
]).then(done);
}); });
it('should respond with 404 for unknown paths', async () => { it('should respond with 404 for unknown paths', done => {
const cmdPrefix = `curl -iLX POST ${scheme}://${host}`; const cmdPrefix = `curl -iLX POST ${scheme}://${host}`;
await Promise.all([ Promise.all([
h.runCmd(`${cmdPrefix}/foo/pr-updated`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/foo/pr-updated`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/foo-pr-updated`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/foo-pr-updated`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/foonpr-updated`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/foonpr-updated`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/pr-updated/foo`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/pr-updated/foo`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/pr-updated-foo`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/pr-updated-foo`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/pr-updatednfoo`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/pr-updatednfoo`).then(h.verifyResponse(404)),
]); ]).then(done);
}); });
}); });
@ -364,7 +374,7 @@ describe(`nginx`, () => {
beforeEach(() => { beforeEach(() => {
['index.html', 'foo.js', 'foo/index.html'].forEach(relFilePath => { ['index.html', 'foo.js', 'foo/index.html'].forEach(relFilePath => {
const absFilePath = path.join(AIO_BUILDS_DIR, relFilePath); const absFilePath = path.join(AIO_BUILDS_DIR, relFilePath);
h.writeFile(absFilePath, {content: `File: /${relFilePath}`}); return h.writeFile(absFilePath, {content: `File: /${relFilePath}`});
}); });
}); });

View File

@ -105,8 +105,8 @@ describe('preview-server', () => {
describe(`${host}/circle-build`, () => { describe(`${host}/circle-build`, () => {
const curl = makeCurl(`${host}/circle-build`);
const curl = makeCurl(`${host}/circle-build`);
it('should disallow non-POST requests', async () => { it('should disallow non-POST requests', async () => {
const bodyRegex = /^Unknown resource/; const bodyRegex = /^Unknown resource/;
@ -189,7 +189,8 @@ describe('preview-server', () => {
}); });
it('should respond with 201 if a new public build is created', async () => { it('should respond with 201 if a new public build is created', async () => {
await curl(payload(BuildNums.TRUST_CHECK_ACTIVE_TRUSTED_USER)).then(h.verifyResponse(201)); await curl(payload(BuildNums.TRUST_CHECK_ACTIVE_TRUSTED_USER))
.then(h.verifyResponse(201));
expect({ prNum: PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER }).toExistAsABuild(); expect({ prNum: PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER }).toExistAsABuild();
}); });
@ -198,7 +199,7 @@ describe('preview-server', () => {
expect({ prNum: PrNums.TRUST_CHECK_UNTRUSTED, isPublic: false }).toExistAsABuild(); expect({ prNum: PrNums.TRUST_CHECK_UNTRUSTED, isPublic: false }).toExistAsABuild();
}); });
[true, false].forEach(isPublic => { [true].forEach(isPublic => {
const build = isPublic ? BuildNums.TRUST_CHECK_ACTIVE_TRUSTED_USER : BuildNums.TRUST_CHECK_UNTRUSTED; const build = isPublic ? BuildNums.TRUST_CHECK_ACTIVE_TRUSTED_USER : BuildNums.TRUST_CHECK_UNTRUSTED;
const prNum = isPublic ? PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER : PrNums.TRUST_CHECK_UNTRUSTED; const prNum = isPublic ? PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER : PrNums.TRUST_CHECK_UNTRUSTED;
const label = isPublic ? 'public' : 'non-public'; const label = isPublic ? 'public' : 'non-public';
@ -363,23 +364,23 @@ describe('preview-server', () => {
describe(`${host}/health-check`, () => { describe(`${host}/health-check`, () => {
it('should respond with 200', async () => { it('should respond with 200', done => {
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${host}/health-check`).then(h.verifyResponse(200)), h.runCmd(`curl -iL ${host}/health-check`).then(h.verifyResponse(200)),
h.runCmd(`curl -iL ${host}/health-check/`).then(h.verifyResponse(200)), h.runCmd(`curl -iL ${host}/health-check/`).then(h.verifyResponse(200)),
]); ]).then(done);
}); });
it('should respond with 404 if the path does not match exactly', async () => { it('should respond with 404 if the path does not match exactly', done => {
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${host}/health-check/foo`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${host}/health-check/foo`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${host}/health-check-foo`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${host}/health-check-foo`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${host}/health-checknfoo`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${host}/health-checknfoo`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${host}/foo/health-check`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${host}/foo/health-check`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${host}/foo-health-check`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${host}/foo-health-check`).then(h.verifyResponse(404)),
h.runCmd(`curl -iL ${host}/foonhealth-check`).then(h.verifyResponse(404)), h.runCmd(`curl -iL ${host}/foonhealth-check`).then(h.verifyResponse(404)),
]); ]).then(done);
}); });
}); });
@ -425,18 +426,18 @@ describe('preview-server', () => {
}); });
it('should respond with 404 for unknown paths', async () => { it('should respond with 404 for unknown paths', done => {
const mockPayload = JSON.stringify({number: 1}); // MockExternalApiFlags.TRUST_CHECK_ACTIVE_TRUSTED_USER }); const mockPayload = JSON.stringify({number: 1}); // MockExternalApiFlags.TRUST_CHECK_ACTIVE_TRUSTED_USER });
const cmdPrefix = `curl -iLX POST --data "${mockPayload}" ${host}`; const cmdPrefix = `curl -iLX POST --data "${mockPayload}" ${host}`;
await Promise.all([ Promise.all([
h.runCmd(`${cmdPrefix}/foo/pr-updated`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/foo/pr-updated`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/foo-pr-updated`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/foo-pr-updated`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/foonpr-updated`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/foonpr-updated`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/pr-updated/foo`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/pr-updated/foo`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/pr-updated-foo`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/pr-updated-foo`).then(h.verifyResponse(404)),
h.runCmd(`${cmdPrefix}/pr-updatednfoo`).then(h.verifyResponse(404)), h.runCmd(`${cmdPrefix}/pr-updatednfoo`).then(h.verifyResponse(404)),
]); ]).then(done);
}); });
@ -550,10 +551,10 @@ describe('preview-server', () => {
describe(`${host}/*`, () => { describe(`${host}/*`, () => {
it('should respond with 404 for requests to unknown URLs', async () => { it('should respond with 404 for requests to unknown URLs', done => {
const bodyRegex = /^Unknown resource/; const bodyRegex = /^Unknown resource/;
await Promise.all([ Promise.all([
h.runCmd(`curl -iL ${host}/index.html`).then(h.verifyResponse(404, bodyRegex)), h.runCmd(`curl -iL ${host}/index.html`).then(h.verifyResponse(404, bodyRegex)),
h.runCmd(`curl -iL ${host}/`).then(h.verifyResponse(404, bodyRegex)), h.runCmd(`curl -iL ${host}/`).then(h.verifyResponse(404, bodyRegex)),
h.runCmd(`curl -iL ${host}`).then(h.verifyResponse(404, bodyRegex)), h.runCmd(`curl -iL ${host}`).then(h.verifyResponse(404, bodyRegex)),
@ -561,7 +562,7 @@ describe('preview-server', () => {
h.runCmd(`curl -iLX POST ${host}`).then(h.verifyResponse(404, bodyRegex)), h.runCmd(`curl -iLX POST ${host}`).then(h.verifyResponse(404, bodyRegex)),
h.runCmd(`curl -iLX PATCH ${host}`).then(h.verifyResponse(404, bodyRegex)), h.runCmd(`curl -iLX PATCH ${host}`).then(h.verifyResponse(404, bodyRegex)),
h.runCmd(`curl -iLX DELETE ${host}`).then(h.verifyResponse(404, bodyRegex)), h.runCmd(`curl -iLX DELETE ${host}`).then(h.verifyResponse(404, bodyRegex)),
]); ]).then(done);
}); });
}); });

View File

@ -14,41 +14,42 @@
"predev": "yarn build || true", "predev": "yarn build || true",
"dev": "run-p ~~build-watch ~~test-watch", "dev": "run-p ~~build-watch ~~test-watch",
"lint": "tslint --project tsconfig.json", "lint": "tslint --project tsconfig.json",
"pretest": "run-s build lint", "pretest": "yarn build",
"test": "yarn ~~test-only", "test": "yarn ~~test-only",
"pretest-watch": "yarn pretest", "pretest-watch": "yarn pretest",
"test-watch": "yarn ~~test-watch", "test-watch": "yarn ~~test-watch",
"~~build": "tsc", "~~build": "tsc",
"~~build-watch": "yarn ~~build --watch", "~~build-watch": "yarn ~~build --watch",
"pre~~test-only": "yarn lint",
"~~test-only": "node dist/test", "~~test-only": "node dist/test",
"~~test-watch": "nodemon --delay 1 --exec \"yarn ~~test-only\" --watch dist" "~~test-watch": "nodemon --delay 1 --exec \"yarn ~~test-only\" --watch dist"
}, },
"dependencies": { "dependencies": {
"body-parser": "^1.19.0", "body-parser": "^1.18.3",
"delete-empty": "^3.0.0", "delete-empty": "^2.0.0",
"express": "^4.17.1", "express": "^4.16.3",
"jasmine": "^3.5.0", "jasmine": "^3.2.0",
"nock": "^12.0.3", "nock": "^9.6.1",
"node-fetch": "^2.6.0", "node-fetch": "^2.2.0",
"shelljs": "^0.8.4", "shelljs": "^0.8.2",
"source-map-support": "^0.5.19", "source-map-support": "^0.5.9",
"tar-stream": "^2.1.2", "tar-stream": "^1.6.1",
"tslib": "^1.11.1" "tslib": "^1.9.3"
}, },
"devDependencies": { "devDependencies": {
"@types/body-parser": "^1.19.0", "@types/body-parser": "^1.17.0",
"@types/express": "^4.17.6", "@types/express": "^4.16.0",
"@types/jasmine": "^3.5.10", "@types/jasmine": "^2.8.8",
"@types/nock": "^11.1.0", "@types/nock": "^9.3.0",
"@types/node": "^13.13.2", "@types/node": "^10.9.2",
"@types/node-fetch": "^2.5.7", "@types/node-fetch": "^2.1.2",
"@types/shelljs": "^0.8.7", "@types/shelljs": "^0.8.0",
"@types/supertest": "^2.0.8", "@types/supertest": "^2.0.5",
"nodemon": "^2.0.3", "nodemon": "^1.18.3",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"supertest": "^4.0.2", "supertest": "^3.1.0",
"tslint": "^6.1.1", "tslint": "^5.11.0",
"tslint-jasmine-noSkipOrFocus": "^1.0.9", "tslint-jasmine-noSkipOrFocus": "^1.0.9",
"typescript": "^3.8.3" "typescript": "^3.0.1"
} }
} }

View File

@ -15,6 +15,7 @@ const EXISTING_DOWNLOADS = [
'20-1234567-build.zip', '20-1234567-build.zip',
]; ];
const OPEN_PRS = [10, 40]; const OPEN_PRS = [10, 40];
const ANY_DATE = jasmine.any(String);
// Tests // Tests
describe('BuildCleaner', () => { describe('BuildCleaner', () => {
@ -76,18 +77,22 @@ describe('BuildCleaner', () => {
let cleanerRemoveUnnecessaryDownloadsSpy: jasmine.Spy; let cleanerRemoveUnnecessaryDownloadsSpy: jasmine.Spy;
beforeEach(() => { beforeEach(() => {
cleanerGetExistingBuildNumbersSpy = spyOn(cleaner, 'getExistingBuildNumbers').and.resolveTo(EXISTING_BUILDS); cleanerGetExistingBuildNumbersSpy = spyOn(cleaner, 'getExistingBuildNumbers')
cleanerGetOpenPrNumbersSpy = spyOn(cleaner, 'getOpenPrNumbers').and.resolveTo(OPEN_PRS); .and.callFake(() => Promise.resolve(EXISTING_BUILDS));
cleanerGetExistingDownloadsSpy = spyOn(cleaner, 'getExistingDownloads').and.resolveTo(EXISTING_DOWNLOADS); cleanerGetOpenPrNumbersSpy = spyOn(cleaner, 'getOpenPrNumbers')
.and.callFake(() => Promise.resolve(OPEN_PRS));
cleanerGetExistingDownloadsSpy = spyOn(cleaner, 'getExistingDownloads')
.and.callFake(() => Promise.resolve(EXISTING_DOWNLOADS));
cleanerRemoveUnnecessaryBuildsSpy = spyOn(cleaner, 'removeUnnecessaryBuilds'); cleanerRemoveUnnecessaryBuildsSpy = spyOn(cleaner, 'removeUnnecessaryBuilds');
cleanerRemoveUnnecessaryDownloadsSpy = spyOn(cleaner, 'removeUnnecessaryDownloads'); cleanerRemoveUnnecessaryDownloadsSpy = spyOn(cleaner, 'removeUnnecessaryDownloads');
}); });
it('should return a promise', async () => { it('should return a promise', async () => {
const promise = cleaner.cleanUp(); const promise = cleaner.cleanUp();
expect(promise).toBeInstanceOf(Promise); expect(promise).toEqual(jasmine.any(Promise));
// Do not complete the test and release the spies synchronously, to avoid running the actual implementations. // Do not complete the test and release the spies synchronously, to avoid running the actual implementations.
await promise; await promise;
@ -125,32 +130,52 @@ describe('BuildCleaner', () => {
it('should reject if \'getOpenPrNumbers()\' rejects', async () => { it('should reject if \'getOpenPrNumbers()\' rejects', async () => {
cleanerGetOpenPrNumbersSpy.and.rejectWith('Test'); try {
await expectAsync(cleaner.cleanUp()).toBeRejectedWith('Test'); cleanerGetOpenPrNumbersSpy.and.callFake(() => Promise.reject('Test'));
await cleaner.cleanUp();
} catch (err) {
expect(err).toBe('Test');
}
}); });
it('should reject if \'getExistingBuildNumbers()\' rejects', async () => { it('should reject if \'getExistingBuildNumbers()\' rejects', async () => {
cleanerGetExistingBuildNumbersSpy.and.rejectWith('Test'); try {
await expectAsync(cleaner.cleanUp()).toBeRejectedWith('Test'); cleanerGetExistingBuildNumbersSpy.and.callFake(() => Promise.reject('Test'));
await cleaner.cleanUp();
} catch (err) {
expect(err).toBe('Test');
}
}); });
it('should reject if \'getExistingDownloads()\' rejects', async () => { it('should reject if \'getExistingDownloads()\' rejects', async () => {
cleanerGetExistingDownloadsSpy.and.rejectWith('Test'); try {
await expectAsync(cleaner.cleanUp()).toBeRejectedWith('Test'); cleanerGetExistingDownloadsSpy.and.callFake(() => Promise.reject('Test'));
await cleaner.cleanUp();
} catch (err) {
expect(err).toBe('Test');
}
}); });
it('should reject if \'removeUnnecessaryBuilds()\' rejects', async () => { it('should reject if \'removeUnnecessaryBuilds()\' rejects', async () => {
cleanerRemoveUnnecessaryBuildsSpy.and.rejectWith('Test'); try {
await expectAsync(cleaner.cleanUp()).toBeRejectedWith('Test'); cleanerRemoveUnnecessaryBuildsSpy.and.callFake(() => Promise.reject('Test'));
await cleaner.cleanUp();
} catch (err) {
expect(err).toBe('Test');
}
}); });
it('should reject if \'removeUnnecessaryDownloads()\' rejects', async () => { it('should reject if \'removeUnnecessaryDownloads()\' rejects', async () => {
cleanerRemoveUnnecessaryDownloadsSpy.and.rejectWith('Test'); try {
await expectAsync(cleaner.cleanUp()).toBeRejectedWith('Test'); cleanerRemoveUnnecessaryDownloadsSpy.and.callFake(() => Promise.reject('Test'));
await cleaner.cleanUp();
} catch (err) {
expect(err).toBe('Test');
}
}); });
}); });
@ -162,15 +187,13 @@ describe('BuildCleaner', () => {
let promise: Promise<number[]>; let promise: Promise<number[]>;
beforeEach(() => { beforeEach(() => {
fsReaddirSpy = spyOn(fs, 'readdir').and.callFake( fsReaddirSpy = spyOn(fs, 'readdir').and.callFake((_: string, cb: typeof readdirCb) => readdirCb = cb);
((_: string, cb: typeof readdirCb) => readdirCb = cb) as unknown as typeof fs.readdir,
);
promise = cleaner.getExistingBuildNumbers(); promise = cleaner.getExistingBuildNumbers();
}); });
it('should return a promise', () => { it('should return a promise', () => {
expect(promise).toBeInstanceOf(Promise); expect(promise).toEqual(jasmine.any(Promise));
}); });
@ -180,27 +203,43 @@ describe('BuildCleaner', () => {
}); });
it('should reject if an error occurs while getting the files', async () => { it('should reject if an error occurs while getting the files', done => {
promise.catch(err => {
expect(err).toBe('Test');
done();
});
readdirCb('Test'); readdirCb('Test');
await expectAsync(promise).toBeRejectedWith('Test');
}); });
it('should resolve with the returned files (as numbers)', async () => { it('should resolve with the returned files (as numbers)', done => {
promise.then(result => {
expect(result).toEqual([12, 34, 56]);
done();
});
readdirCb(null, ['12', '34', '56']); readdirCb(null, ['12', '34', '56']);
await expectAsync(promise).toBeResolvedTo([12, 34, 56]);
}); });
it('should remove `HIDDEN_DIR_PREFIX` from the filenames', async () => { it('should remove `HIDDEN_DIR_PREFIX` from the filenames', done => {
promise.then(result => {
expect(result).toEqual([12, 34, 56]);
done();
});
readdirCb(null, [`${HIDDEN_DIR_PREFIX}12`, '34', `${HIDDEN_DIR_PREFIX}56`]); readdirCb(null, [`${HIDDEN_DIR_PREFIX}12`, '34', `${HIDDEN_DIR_PREFIX}56`]);
await expectAsync(promise).toBeResolvedTo([12, 34, 56]);
}); });
it('should ignore files with non-numeric (or zero) names', async () => { it('should ignore files with non-numeric (or zero) names', done => {
promise.then(result => {
expect(result).toEqual([12, 34, 56]);
done();
});
readdirCb(null, ['12', 'foo', '34', 'bar', '56', '000']); readdirCb(null, ['12', 'foo', '34', 'bar', '56', '000']);
await expectAsync(promise).toBeResolvedTo([12, 34, 56]);
}); });
}); });
@ -220,7 +259,7 @@ describe('BuildCleaner', () => {
it('should return a promise', () => { it('should return a promise', () => {
expect(promise).toBeInstanceOf(Promise); expect(promise).toEqual(jasmine.any(Promise));
}); });
@ -229,15 +268,31 @@ describe('BuildCleaner', () => {
}); });
it('should reject if an error occurs while fetching PRs', async () => { it('should reject if an error occurs while fetching PRs', done => {
promise.catch(err => {
expect(err).toBe('Test');
done();
});
prDeferred.reject('Test'); prDeferred.reject('Test');
await expectAsync(promise).toBeRejectedWith('Test');
}); });
it('should resolve with the numbers of the fetched PRs', async () => { it('should resolve with the numbers of the fetched PRs', done => {
promise.then(prNumbers => {
expect(prNumbers).toEqual([1, 2, 3]);
done();
});
prDeferred.resolve([{id: 0, number: 1}, {id: 1, number: 2}, {id: 2, number: 3}]); prDeferred.resolve([{id: 0, number: 1}, {id: 1, number: 2}, {id: 2, number: 3}]);
await expectAsync(promise).toBeResolvedTo([1, 2, 3]); });
it('should log the number of open PRs', () => {
promise.then(prNumbers => {
expect(loggerLogSpy).toHaveBeenCalledWith(
ANY_DATE, 'BuildCleaner: ', `Open pull requests: ${prNumbers}`);
});
}); });
}); });
@ -249,15 +304,13 @@ describe('BuildCleaner', () => {
let promise: Promise<string[]>; let promise: Promise<string[]>;
beforeEach(() => { beforeEach(() => {
fsReaddirSpy = spyOn(fs, 'readdir').and.callFake( fsReaddirSpy = spyOn(fs, 'readdir').and.callFake((_: string, cb: typeof readdirCb) => readdirCb = cb);
((_: string, cb: typeof readdirCb) => readdirCb = cb) as unknown as typeof fs.readdir,
);
promise = cleaner.getExistingDownloads(); promise = cleaner.getExistingDownloads();
}); });
it('should return a promise', () => { it('should return a promise', () => {
expect(promise).toBeInstanceOf(Promise); expect(promise).toEqual(jasmine.any(Promise));
}); });
@ -267,21 +320,33 @@ describe('BuildCleaner', () => {
}); });
it('should reject if an error occurs while getting the files', async () => { it('should reject if an error occurs while getting the files', done => {
promise.catch(err => {
expect(err).toBe('Test');
done();
});
readdirCb('Test'); readdirCb('Test');
await expectAsync(promise).toBeRejectedWith('Test');
}); });
it('should resolve with the returned file names', async () => { it('should resolve with the returned file names', done => {
promise.then(result => {
expect(result).toEqual(EXISTING_DOWNLOADS);
done();
});
readdirCb(null, EXISTING_DOWNLOADS); readdirCb(null, EXISTING_DOWNLOADS);
await expectAsync(promise).toBeResolvedTo(EXISTING_DOWNLOADS);
}); });
it('should ignore files that do not match the artifactPath', async () => { it('should ignore files that do not match the artifactPath', done => {
promise.then(result => {
expect(result).toEqual(['10-ABCDEF-build.zip', '30-FFFFFFF-build.zip']);
done();
});
readdirCb(null, ['10-ABCDEF-build.zip', '20-AAAAAAA-otherfile.zip', '30-FFFFFFF-build.zip']); readdirCb(null, ['10-ABCDEF-build.zip', '20-AAAAAAA-otherfile.zip', '30-FFFFFFF-build.zip']);
await expectAsync(promise).toBeResolvedTo(['10-ABCDEF-build.zip', '30-FFFFFFF-build.zip']);
}); });
}); });
@ -299,7 +364,7 @@ describe('BuildCleaner', () => {
}); });
it('should test if the directory exists (and return if it does not)', () => { it('should test if the directory exists (and return if is does not)', () => {
shellTestSpy.and.returnValue(false); shellTestSpy.and.returnValue(false);
cleaner.removeDir('/foo/bar'); cleaner.removeDir('/foo/bar');
@ -316,19 +381,22 @@ describe('BuildCleaner', () => {
it('should make the directory and its content writable before removing', () => { it('should make the directory and its content writable before removing', () => {
shellRmSpy.and.callFake(() => expect(shellChmodSpy).toHaveBeenCalledWith('-R', 'a+w', '/foo/bar'));
cleaner.removeDir('/foo/bar'); cleaner.removeDir('/foo/bar');
expect(shellChmodSpy).toHaveBeenCalledBefore(shellRmSpy);
expect(shellChmodSpy).toHaveBeenCalledWith('-R', 'a+w', '/foo/bar');
expect(shellRmSpy).toHaveBeenCalled(); expect(shellRmSpy).toHaveBeenCalled();
}); });
it('should catch errors and log them', () => { it('should catch errors and log them', () => {
shellRmSpy.and.throwError('Test'); shellRmSpy.and.callFake(() => {
// tslint:disable-next-line: no-string-throw
throw 'Test';
});
cleaner.removeDir('/foo/bar'); cleaner.removeDir('/foo/bar');
expect(loggerErrorSpy).toHaveBeenCalledWith('ERROR: Unable to remove \'/foo/bar\' due to:', new Error('Test')); expect(loggerErrorSpy).toHaveBeenCalledWith('ERROR: Unable to remove \'/foo/bar\' due to:', 'Test');
}); });
}); });
@ -381,7 +449,7 @@ describe('BuildCleaner', () => {
expect(cleanerRemoveDirSpy).toHaveBeenCalledTimes(0); expect(cleanerRemoveDirSpy).toHaveBeenCalledTimes(0);
cleanerRemoveDirSpy.calls.reset(); cleanerRemoveDirSpy.calls.reset();
cleaner.removeUnnecessaryBuilds([1, 2, 3, 4], []); (cleaner as any).removeUnnecessaryBuilds([1, 2, 3, 4], []);
expect(cleanerRemoveDirSpy).toHaveBeenCalledTimes(8); expect(cleanerRemoveDirSpy).toHaveBeenCalledTimes(8);
expect(cleanerRemoveDirSpy).toHaveBeenCalledWith(normalize('/foo/bar/1')); expect(cleanerRemoveDirSpy).toHaveBeenCalledWith(normalize('/foo/bar/1'));
expect(cleanerRemoveDirSpy).toHaveBeenCalledWith(normalize('/foo/bar/2')); expect(cleanerRemoveDirSpy).toHaveBeenCalledWith(normalize('/foo/bar/2'));

View File

@ -45,15 +45,25 @@ describe('CircleCIApi', () => {
const errorMessage = 'Invalid request'; const errorMessage = 'Invalid request';
const request = nock(BASE_URL).get(`/${buildNum}?circle-token=${TOKEN}`); const request = nock(BASE_URL).get(`/${buildNum}?circle-token=${TOKEN}`);
request.replyWithError(errorMessage); try {
await expectAsync(api.getBuildInfo(buildNum)).toBeRejectedWithError( request.replyWithError(errorMessage);
await api.getBuildInfo(buildNum);
throw new Error('Exception Expected');
} catch (err) {
expect(err.message).toEqual(
`CircleCI build info request failed ` + `CircleCI build info request failed ` +
`(request to ${BASE_URL}/${buildNum}?circle-token=${TOKEN} failed, reason: ${errorMessage})`); `(request to ${BASE_URL}/${buildNum}?circle-token=${TOKEN} failed, reason: ${errorMessage})`);
}
request.reply(404, errorMessage); try {
await expectAsync(api.getBuildInfo(buildNum)).toBeRejectedWithError( request.reply(404, errorMessage);
await api.getBuildInfo(buildNum);
throw new Error('Exception Expected');
} catch (err) {
expect(err.message).toEqual(
`CircleCI build info request failed ` + `CircleCI build info request failed ` +
`(request to ${BASE_URL}/${buildNum}?circle-token=${TOKEN} failed, reason: ${errorMessage})`); `(request to ${BASE_URL}/${buildNum}?circle-token=${TOKEN} failed, reason: ${errorMessage})`);
}
}); });
}); });
@ -68,7 +78,8 @@ describe('CircleCIApi', () => {
.get(`/${buildNum}/artifacts?circle-token=${TOKEN}`) .get(`/${buildNum}/artifacts?circle-token=${TOKEN}`)
.reply(200, [artifact0, artifact1, artifact2]); .reply(200, [artifact0, artifact1, artifact2]);
await expectAsync(api.getBuildArtifactUrl(buildNum, 'some/path/1')).toBeResolvedTo('https://url/1'); const artifactUrl = await api.getBuildArtifactUrl(buildNum, 'some/path/1');
expect(artifactUrl).toEqual('https://url/1');
request.done(); request.done();
}); });
@ -79,15 +90,25 @@ describe('CircleCIApi', () => {
const errorMessage = 'Invalid request'; const errorMessage = 'Invalid request';
const request = nock(BASE_URL).get(`/${buildNum}/artifacts?circle-token=${TOKEN}`); const request = nock(BASE_URL).get(`/${buildNum}/artifacts?circle-token=${TOKEN}`);
request.replyWithError(errorMessage); try {
await expectAsync(api.getBuildArtifactUrl(buildNum, 'some/path/1')).toBeRejectedWithError( request.replyWithError(errorMessage);
await api.getBuildArtifactUrl(buildNum, 'some/path/1');
throw new Error('Exception Expected');
} catch (err) {
expect(err.message).toEqual(
`CircleCI artifact URL request failed ` + `CircleCI artifact URL request failed ` +
`(request to ${BASE_URL}/${buildNum}/artifacts?circle-token=${TOKEN} failed, reason: ${errorMessage})`); `(request to ${BASE_URL}/${buildNum}/artifacts?circle-token=${TOKEN} failed, reason: ${errorMessage})`);
}
request.reply(404, errorMessage); try {
await expectAsync(api.getBuildArtifactUrl(buildNum, 'some/path/1')).toBeRejectedWithError( request.reply(404, errorMessage);
await api.getBuildArtifactUrl(buildNum, 'some/path/1');
throw new Error('Exception Expected');
} catch (err) {
expect(err.message).toEqual(
`CircleCI artifact URL request failed ` + `CircleCI artifact URL request failed ` +
`(request to ${BASE_URL}/${buildNum}/artifacts?circle-token=${TOKEN} failed, reason: ${errorMessage})`); `(request to ${BASE_URL}/${buildNum}/artifacts?circle-token=${TOKEN} failed, reason: ${errorMessage})`);
}
}); });
it('should throw an error if the response does not contain the specified artifact', async () => { it('should throw an error if the response does not contain the specified artifact', async () => {
@ -100,9 +121,14 @@ describe('CircleCIApi', () => {
.get(`/${buildNum}/artifacts?circle-token=${TOKEN}`) .get(`/${buildNum}/artifacts?circle-token=${TOKEN}`)
.reply(200, [artifact0, artifact1, artifact2]); .reply(200, [artifact0, artifact1, artifact2]);
await expectAsync(api.getBuildArtifactUrl(buildNum, 'some/path/3')).toBeRejectedWithError( try {
await api.getBuildArtifactUrl(buildNum, 'some/path/3');
throw new Error('Exception Expected');
} catch (err) {
expect(err.message).toEqual(
`CircleCI artifact URL request failed ` + `CircleCI artifact URL request failed ` +
`(Missing artifact (some/path/3) for CircleCI build: ${buildNum})`); `(Missing artifact (some/path/3) for CircleCI build: ${buildNum})`);
}
}); });
}); });
}); });

View File

@ -118,7 +118,7 @@ describe('GithubApi', () => {
it('should return a promise', () => { it('should return a promise', () => {
expect((api as any).getPaginated()).toBeInstanceOf(Promise); expect((api as any).getPaginated()).toEqual(jasmine.any(Promise));
}); });
@ -131,30 +131,45 @@ describe('GithubApi', () => {
}); });
it('should reject if the request fails', async () => { it('should reject if the request fails', done => {
const responsePromise = (api as any).getPaginated('/foo/bar'); (api as any).getPaginated('/foo/bar').catch((err: any) => {
expect(err).toBe('Test');
done();
});
deferreds[0].reject('Test'); deferreds[0].reject('Test');
await expectAsync(responsePromise).toBeRejectedWith('Test');
}); });
it('should resolve with the returned items', async () => { it('should resolve with the returned items', done => {
const items = [{id: 1}, {id: 2}]; const items = [{id: 1}, {id: 2}];
const responsePromise = (api as any).getPaginated('/foo/bar');
deferreds[0].resolve(items);
await expectAsync(responsePromise).toBeResolvedTo(items); (api as any).getPaginated('/foo/bar').then((data: any) => {
expect(data).toEqual(items);
done();
});
deferreds[0].resolve(items);
}); });
it('should iteratively call \'get()\' to fetch all items', async () => { it('should iteratively call \'get()\' to fetch all items', done => {
// Create an array or 250 objects. // Create an array or 250 objects.
const allItems = new Array(250).fill(null).map((_, i) => ({id: i})); const allItems = '.'.repeat(250).split('').map((_, i) => ({id: i}));
const apiGetSpy = api.get as jasmine.Spy; const apiGetSpy = api.get as jasmine.Spy;
const paramsForPage = (page: number) => ({baz: 'qux', page, per_page: 100});
const responsePromise = (api as any).getPaginated('/foo/bar', {baz: 'qux'}); (api as any).getPaginated('/foo/bar', {baz: 'qux'}).then((data: any) => {
const paramsForPage = (page: number) => ({baz: 'qux', page, per_page: 100});
expect(apiGetSpy).toHaveBeenCalledTimes(3);
expect(apiGetSpy.calls.argsFor(0)).toEqual(['/foo/bar', paramsForPage(1)]);
expect(apiGetSpy.calls.argsFor(1)).toEqual(['/foo/bar', paramsForPage(2)]);
expect(apiGetSpy.calls.argsFor(2)).toEqual(['/foo/bar', paramsForPage(3)]);
expect(data).toEqual(allItems);
done();
});
deferreds[0].resolve(allItems.slice(0, 100)); deferreds[0].resolve(allItems.slice(0, 100));
setTimeout(() => { setTimeout(() => {
@ -163,13 +178,6 @@ describe('GithubApi', () => {
deferreds[2].resolve(allItems.slice(200)); deferreds[2].resolve(allItems.slice(200));
}, 0); }, 0);
}, 0); }, 0);
await expectAsync(responsePromise).toBeResolvedTo(allItems);
expect(apiGetSpy).toHaveBeenCalledTimes(3);
expect(apiGetSpy.calls.argsFor(0)).toEqual(['/foo/bar', paramsForPage(1)]);
expect(apiGetSpy.calls.argsFor(1)).toEqual(['/foo/bar', paramsForPage(2)]);
expect(apiGetSpy.calls.argsFor(2)).toEqual(['/foo/bar', paramsForPage(3)]);
}); });
}); });
@ -209,8 +217,8 @@ describe('GithubApi', () => {
describe('request()', () => { describe('request()', () => {
it('should return a promise', () => { it('should return a promise', () => {
nock('https://api.github.com').get('/').reply(200); nock('https://api.github.com').get('').reply(200);
expect((api as any).request()).toBeInstanceOf(Promise); expect((api as any).request()).toEqual(jasmine.any(Promise));
}); });
@ -239,8 +247,9 @@ describe('GithubApi', () => {
nock('https://api.github.com') nock('https://api.github.com')
.intercept('/path', 'method') .intercept('/path', 'method')
.replyWithError('Test'); .replyWithError('Test');
let message = 'Failed to reject error';
await expectAsync((api as any).request('method', '/path')).toBeRejectedWithError('Test'); await (api as any).request('method', '/path').catch((err: any) => message = err.message);
expect(message).toEqual('Test');
}); });
@ -254,69 +263,81 @@ describe('GithubApi', () => {
}); });
it('should reject if response statusCode is <200', async () => { it('should reject if response statusCode is <200', done => {
const requestHandler = nock('https://api.github.com') const requestHandler = nock('https://api.github.com')
.intercept('/path', 'method') .intercept('/path', 'method')
.reply(199); .reply(199);
const responsePromise = (api as any).request('method', '/path');
await expectAsync(responsePromise).toBeRejectedWith(jasmine.stringMatching('failed'));
await expectAsync(responsePromise).toBeRejectedWith(jasmine.stringMatching('status: 199'));
(api as any).request('method', '/path')
.catch((err: string) => {
expect(err).toContain('failed');
expect(err).toContain('status: 199');
done();
});
requestHandler.done(); requestHandler.done();
}); });
it('should reject if response statusCode is >=400', async () => { it('should reject if response statusCode is >=400', done => {
const requestHandler = nock('https://api.github.com') const requestHandler = nock('https://api.github.com')
.intercept('/path', 'method') .intercept('/path', 'method')
.reply(400); .reply(400);
const responsePromise = (api as any).request('method', '/path');
await expectAsync(responsePromise).toBeRejectedWith(jasmine.stringMatching('failed'));
await expectAsync(responsePromise).toBeRejectedWith(jasmine.stringMatching('status: 400'));
(api as any).request('method', '/path')
.catch((err: string) => {
expect(err).toContain('failed');
expect(err).toContain('status: 400');
done();
});
requestHandler.done(); requestHandler.done();
}); });
it('should include the response text in the rejection message', async () => { it('should include the response text in the rejection message', done => {
const requestHandler = nock('https://api.github.com') const requestHandler = nock('https://api.github.com')
.intercept('/path', 'method') .intercept('/path', 'method')
.reply(500, 'Test'); .reply(500, 'Test');
const responsePromise = (api as any).request('method', '/path');
await expectAsync(responsePromise).toBeRejectedWith(jasmine.stringMatching('Test'));
(api as any).request('method', '/path')
.catch((err: string) => {
expect(err).toContain('Test');
done();
});
requestHandler.done(); requestHandler.done();
}); });
it('should resolve if returned statusCode is >=200 and <400', async () => { it('should resolve if returned statusCode is >=200 and <400', done => {
const requestHandler = nock('https://api.github.com') const requestHandler = nock('https://api.github.com')
.intercept('/path', 'method') .intercept('/path', 'method')
.reply(200); .reply(200);
await expectAsync((api as any).request('method', '/path')).toBeResolved(); (api as any).request('method', '/path').then(done);
requestHandler.done(); requestHandler.done();
}); });
it('should parse the response body into an object using \'JSON.parse\'', async () => { it('should parse the response body into an object using \'JSON.parse\'', done => {
const requestHandler = nock('https://api.github.com') const requestHandler = nock('https://api.github.com')
.intercept('/path', 'method') .intercept('/path', 'method')
.reply(300, '{"foo": "bar"}'); .reply(300, '{"foo": "bar"}');
await expectAsync((api as any).request('method', '/path')).toBeResolvedTo({foo: 'bar'}); (api as any).request('method', '/path').then((data: any) => {
expect(data).toEqual({foo: 'bar'});
done();
});
requestHandler.done(); requestHandler.done();
}); });
it('should reject if the response text is malformed JSON', async () => { it('should reject if the response text is malformed JSON', done => {
const requestHandler = nock('https://api.github.com') const requestHandler = nock('https://api.github.com')
.intercept('/path', 'method') .intercept('/path', 'method')
.reply(300, '}'); .reply(300, '}');
await expectAsync((api as any).request('method', '/path')).toBeRejectedWithError(SyntaxError); (api as any).request('method', '/path').catch((err: any) => {
expect(err).toEqual(jasmine.any(SyntaxError));
done();
});
requestHandler.done(); requestHandler.done();
}); });

View File

@ -1,6 +1,6 @@
// Imports // Imports
import {GithubApi} from '../../lib/common/github-api'; import {GithubApi} from '../../lib/common/github-api';
import {GithubPullRequests, PullRequest} from '../../lib/common/github-pull-requests'; import {GithubPullRequests} from '../../lib/common/github-pull-requests';
// Tests // Tests
describe('GithubPullRequests', () => { describe('GithubPullRequests', () => {
@ -47,21 +47,27 @@ describe('GithubPullRequests', () => {
it('should make a POST request to Github with the correct pathname, params and data', () => { it('should make a POST request to Github with the correct pathname, params and data', () => {
githubApi.post.and.resolveTo(); githubApi.post.and.callFake(() => Promise.resolve());
prs.addComment(42, 'body'); prs.addComment(42, 'body');
expect(githubApi.post).toHaveBeenCalledWith('/repos/foo/bar/issues/42/comments', null, {body: 'body'}); expect(githubApi.post).toHaveBeenCalledWith('/repos/foo/bar/issues/42/comments', null, {body: 'body'});
}); });
it('should reject if the request fails', async () => { it('should reject if the request fails', done => {
githubApi.post.and.rejectWith('Test'); githubApi.post.and.callFake(() => Promise.reject('Test'));
await expectAsync(prs.addComment(42, 'body')).toBeRejectedWith('Test'); prs.addComment(42, 'body').catch(err => {
expect(err).toBe('Test');
done();
});
}); });
it('should resolve with the data from the Github POST', async () => { it('should resolve with the data from the Github POST', done => {
githubApi.post.and.resolveTo('Test'); githubApi.post.and.callFake(() => Promise.resolve('Test'));
await expectAsync(prs.addComment(42, 'body')).toBeResolvedTo('Test'); prs.addComment(42, 'body').then(data => {
expect(data).toBe('Test');
done();
});
}); });
}); });
@ -81,11 +87,13 @@ describe('GithubPullRequests', () => {
}); });
it('should resolve with the data returned from GitHub', async () => { it('should resolve with the data returned from GitHub', done => {
const expected: any = {number: 42}; const expected: any = {number: 42};
githubApi.get.and.resolveTo(expected); githubApi.get.and.callFake(() => Promise.resolve(expected));
prs.fetch(42).then(data => {
await expectAsync(prs.fetch(42)).toBeResolvedTo(expected); expect(data).toEqual(expected);
done();
});
}); });
}); });
@ -117,14 +125,9 @@ describe('GithubPullRequests', () => {
}); });
it('should forward the value returned by \'getPaginated()\'', async () => { it('should forward the value returned by \'getPaginated()\'', () => {
const mockPrs: PullRequest[] = [ githubApi.getPaginated.and.returnValue('Test');
{number: 1, user: {login: 'foo'}, labels: []}, expect(prs.fetchAll() as any).toBe('Test');
{number: 2, user: {login: 'bar'}, labels: []},
];
githubApi.getPaginated.and.resolveTo(mockPrs);
expect(await prs.fetchAll()).toBe(mockPrs);
}); });
}); });
@ -144,11 +147,13 @@ describe('GithubPullRequests', () => {
}); });
it('should resolve with the data returned from GitHub', async () => { it('should resolve with the data returned from GitHub', done => {
const expected: any = [{sha: 'ABCDE', filename: 'a/b/c'}, {sha: '12345', filename: 'x/y/z'}]; const expected: any = [{sha: 'ABCDE', filename: 'a/b/c'}, {sha: '12345', filename: 'x/y/z'}];
githubApi.getPaginated.and.resolveTo(expected); githubApi.getPaginated.and.callFake(() => Promise.resolve(expected));
prs.fetchFiles(42).then(data => {
await expectAsync(prs.fetchFiles(42)).toBeResolvedTo(expected); expect(data).toEqual(expected);
done();
});
}); });
}); });

View File

@ -1,5 +1,5 @@
import {GithubApi} from '../../lib/common/github-api'; import {GithubApi} from '../../lib/common/github-api';
import {GithubTeams, Team} from '../../lib/common/github-teams'; import {GithubTeams} from '../../lib/common/github-teams';
// Tests // Tests
describe('GithubTeams', () => { describe('GithubTeams', () => {
@ -16,7 +16,6 @@ describe('GithubTeams', () => {
expect(() => new GithubTeams(githubApi, '')). expect(() => new GithubTeams(githubApi, '')).
toThrowError('Missing or empty required parameter \'githubOrg\'!'); toThrowError('Missing or empty required parameter \'githubOrg\'!');
}); });
}); });
@ -34,14 +33,9 @@ describe('GithubTeams', () => {
}); });
it('should forward the value returned by \'getPaginated()\'', async () => { it('should forward the value returned by \'getPaginated()\'', () => {
const mockTeams: Team[] = [ githubApi.getPaginated.and.returnValue('Test');
{id: 1, slug: 'foo'}, expect(teams.fetchAll() as any).toBe('Test');
{id: 2, slug: 'bar'},
];
githubApi.getPaginated.and.resolveTo(mockTeams);
expect(await teams.fetchAll()).toBe(mockTeams);
}); });
}); });
@ -56,77 +50,100 @@ describe('GithubTeams', () => {
it('should return a promise', () => { it('should return a promise', () => {
githubApi.get.and.resolveTo(); githubApi.get.and.callFake(() => Promise.resolve());
const promise = teams.isMemberById('user', [1]); const promise = teams.isMemberById('user', [1]);
expect(promise).toBeInstanceOf(Promise); expect(promise).toEqual(jasmine.any(Promise));
}); });
it('should resolve with false if called with an empty array', async () => { it('should resolve with false if called with an empty array', done => {
await expectAsync(teams.isMemberById('user', [])).toBeResolvedTo(false); teams.isMemberById('user', []).then(isMember => {
expect(githubApi.get).not.toHaveBeenCalled(); expect(isMember).toBe(false);
expect(githubApi.get).not.toHaveBeenCalled();
done();
});
}); });
it('should call \'get()\' with the correct pathname', async () => { it('should call \'get()\' with the correct pathname', done => {
githubApi.get.and.resolveTo(); githubApi.get.and.callFake(() => Promise.resolve());
await teams.isMemberById('user', [1]); teams.isMemberById('user', [1]).then(() => {
expect(githubApi.get).toHaveBeenCalledWith('/teams/1/memberships/user');
expect(githubApi.get).toHaveBeenCalledWith('/teams/1/memberships/user'); done();
});
}); });
it('should resolve with false if \'get()\' rejects', async () => { it('should resolve with false if \'get()\' rejects', done => {
githubApi.get.and.rejectWith(null); githubApi.get.and.callFake(() => Promise.reject(null));
teams.isMemberById('user', [1]).then(isMember => {
await expectAsync(teams.isMemberById('user', [1])).toBeResolvedTo(false); expect(isMember).toBe(false);
expect(githubApi.get).toHaveBeenCalled(); expect(githubApi.get).toHaveBeenCalled();
done();
});
}); });
it('should resolve with false if the membership is not active', async () => { it('should resolve with false if the membership is not active', done => {
githubApi.get.and.resolveTo({state: 'pending'}); githubApi.get.and.callFake(() => Promise.resolve({state: 'pending'}));
teams.isMemberById('user', [1]).then(isMember => {
await expectAsync(teams.isMemberById('user', [1])).toBeResolvedTo(false); expect(isMember).toBe(false);
expect(githubApi.get).toHaveBeenCalled(); expect(githubApi.get).toHaveBeenCalled();
done();
});
}); });
it('should resolve with true if the membership is active', async () => { it('should resolve with true if the membership is active', done => {
githubApi.get.and.resolveTo({state: 'active'}); githubApi.get.and.callFake(() => Promise.resolve({state: 'active'}));
await expectAsync(teams.isMemberById('user', [1])).toBeResolvedTo(true); teams.isMemberById('user', [1]).then(isMember => {
expect(isMember).toBe(true);
done();
});
}); });
it('should sequentially call \'get()\' until an active membership is found', async () => { it('should sequentially call \'get()\' until an active membership is found', done => {
githubApi.get. const trainedResponses: {[pathname: string]: Promise<{state: string}>} = {
withArgs('/teams/1/memberships/user').and.resolveTo({state: 'pending'}). '/teams/1/memberships/user': Promise.resolve({state: 'pending'}),
withArgs('/teams/2/memberships/user').and.rejectWith(null). '/teams/2/memberships/user': Promise.reject(null),
withArgs('/teams/3/memberships/user').and.resolveTo({state: 'active'}); '/teams/3/memberships/user': Promise.resolve({state: 'active'}),
};
githubApi.get.and.callFake((pathname: string) => trainedResponses[pathname]);
await expectAsync(teams.isMemberById('user', [1, 2, 3, 4])).toBeResolvedTo(true); teams.isMemberById('user', [1, 2, 3, 4]).then(isMember => {
expect(isMember).toBe(true);
expect(githubApi.get).toHaveBeenCalledTimes(3); expect(githubApi.get).toHaveBeenCalledTimes(3);
expect(githubApi.get.calls.argsFor(0)[0]).toBe('/teams/1/memberships/user'); expect(githubApi.get.calls.argsFor(0)[0]).toBe('/teams/1/memberships/user');
expect(githubApi.get.calls.argsFor(1)[0]).toBe('/teams/2/memberships/user'); expect(githubApi.get.calls.argsFor(1)[0]).toBe('/teams/2/memberships/user');
expect(githubApi.get.calls.argsFor(2)[0]).toBe('/teams/3/memberships/user'); expect(githubApi.get.calls.argsFor(2)[0]).toBe('/teams/3/memberships/user');
done();
});
}); });
it('should resolve with false if no active membership is found', async () => { it('should resolve with false if no active membership is found', done => {
githubApi.get. const trainedResponses: {[pathname: string]: Promise<{state: string}>} = {
withArgs('/teams/1/memberships/user').and.resolveTo({state: 'pending'}). '/teams/1/memberships/user': Promise.resolve({state: 'pending'}),
withArgs('/teams/2/memberships/user').and.rejectWith(null). '/teams/2/memberships/user': Promise.reject(null),
withArgs('/teams/3/memberships/user').and.resolveTo({state: 'not active'}). '/teams/3/memberships/user': Promise.resolve({state: 'not active'}),
withArgs('/teams/4/memberships/user').and.rejectWith(null); '/teams/4/memberships/user': Promise.reject(null),
};
githubApi.get.and.callFake((pathname: string) => trainedResponses[pathname]);
await expectAsync(teams.isMemberById('user', [1, 2, 3, 4])).toBeResolvedTo(false); teams.isMemberById('user', [1, 2, 3, 4]).then(isMember => {
expect(isMember).toBe(false);
expect(githubApi.get).toHaveBeenCalledTimes(4); expect(githubApi.get).toHaveBeenCalledTimes(4);
expect(githubApi.get.calls.argsFor(0)[0]).toBe('/teams/1/memberships/user'); expect(githubApi.get.calls.argsFor(0)[0]).toBe('/teams/1/memberships/user');
expect(githubApi.get.calls.argsFor(1)[0]).toBe('/teams/2/memberships/user'); expect(githubApi.get.calls.argsFor(1)[0]).toBe('/teams/2/memberships/user');
expect(githubApi.get.calls.argsFor(2)[0]).toBe('/teams/3/memberships/user'); expect(githubApi.get.calls.argsFor(2)[0]).toBe('/teams/3/memberships/user');
expect(githubApi.get.calls.argsFor(3)[0]).toBe('/teams/4/memberships/user'); expect(githubApi.get.calls.argsFor(3)[0]).toBe('/teams/4/memberships/user');
done();
});
}); });
}); });
@ -140,13 +157,14 @@ describe('GithubTeams', () => {
beforeEach(() => { beforeEach(() => {
teams = new GithubTeams(githubApi, 'foo'); teams = new GithubTeams(githubApi, 'foo');
teamsFetchAllSpy = spyOn(teams, 'fetchAll').and.resolveTo([{id: 1, slug: 'team1'}, {id: 2, slug: 'team2'}]); const mockResponse = Promise.resolve([{id: 1, slug: 'team1'}, {id: 2, slug: 'team2'}]);
teamsFetchAllSpy = spyOn(teams, 'fetchAll').and.returnValue(mockResponse);
teamsIsMemberByIdSpy = spyOn(teams, 'isMemberById'); teamsIsMemberByIdSpy = spyOn(teams, 'isMemberById');
}); });
it('should return a promise', () => { it('should return a promise', () => {
expect(teams.isMemberBySlug('user', ['team-slug'])).toBeInstanceOf(Promise); expect(teams.isMemberBySlug('user', ['team-slug'])).toEqual(jasmine.any(Promise));
}); });
@ -156,46 +174,55 @@ describe('GithubTeams', () => {
}); });
it('should resolve with false if \'fetchAll()\' rejects', async () => { it('should resolve with false if \'fetchAll()\' rejects', done => {
teamsFetchAllSpy.and.rejectWith(null); teamsFetchAllSpy.and.callFake(() => Promise.reject(null));
await expectAsync(teams.isMemberBySlug('user', ['team-slug'])).toBeResolvedTo(false); teams.isMemberBySlug('user', ['team-slug']).then(isMember => {
expect(isMember).toBe(false);
done();
});
}); });
it('should call \'isMemberById()\' with the correct params if no team is found', async () => { it('should call \'isMemberById()\' with the correct params if no team is found', done => {
await teams.isMemberBySlug('user', ['no-match']); teams.isMemberBySlug('user', ['no-match']).then(() => {
expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('user', []); expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('user', []);
done();
});
}); });
it('should call \'isMemberById()\' with the correct params if teams are found', async () => { it('should call \'isMemberById()\' with the correct params if teams are found', done => {
await teams.isMemberBySlug('userA', ['team1']); const spy = teamsIsMemberByIdSpy;
expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('userA', [1]);
await teams.isMemberBySlug('userB', ['team2']); Promise.all([
expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('userB', [2]); teams.isMemberBySlug('user', ['team1']).then(() => expect(spy).toHaveBeenCalledWith('user', [1])),
teams.isMemberBySlug('user', ['team2']).then(() => expect(spy).toHaveBeenCalledWith('user', [2])),
await teams.isMemberBySlug('userC', ['team1', 'team2']); teams.isMemberBySlug('user', ['team1', 'team2']).then(() => expect(spy).toHaveBeenCalledWith('user', [1, 2])),
expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('userC', [1, 2]); ]).then(done);
}); });
it('should resolve with false if \'isMemberById()\' rejects', async () => { it('should resolve with false if \'isMemberById()\' rejects', done => {
teamsIsMemberByIdSpy.and.rejectWith(null); teamsIsMemberByIdSpy.and.callFake(() => Promise.reject(null));
teams.isMemberBySlug('user', ['team1']).then(isMember => {
await expectAsync(teams.isMemberBySlug('user', ['team1'])).toBeResolvedTo(false); expect(isMember).toBe(false);
expect(teamsIsMemberByIdSpy).toHaveBeenCalled(); expect(teamsIsMemberByIdSpy).toHaveBeenCalled();
done();
});
}); });
it('should resolve with the value \'isMemberById()\' resolves with', async () => { it('should resolve with the value \'isMemberById()\' resolves with', async () => {
teamsIsMemberByIdSpy.and.resolveTo(true);
await expectAsync(teams.isMemberBySlug('userA', ['team1'])).toBeResolvedTo(true);
expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('userA', [1]);
teamsIsMemberByIdSpy.and.resolveTo(false); teamsIsMemberByIdSpy.and.callFake(() => Promise.resolve(true));
await expectAsync(teams.isMemberBySlug('userB', ['team1'])).toBeResolvedTo(false); const isMember1 = await teams.isMemberBySlug('user', ['team1']);
expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('userB', [1]); expect(isMember1).toBe(true);
expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('user', [1]);
teamsIsMemberByIdSpy.and.callFake(() => Promise.resolve(false));
const isMember2 = await teams.isMemberBySlug('user', ['team1']);
expect(isMember2).toBe(false);
expect(teamsIsMemberByIdSpy).toHaveBeenCalledWith('user', [1]);
}); });
}); });

View File

@ -9,8 +9,7 @@ import {Logger} from '../../lib/common/utils';
import {BuildCreator} from '../../lib/preview-server/build-creator'; import {BuildCreator} from '../../lib/preview-server/build-creator';
import {ChangedPrVisibilityEvent, CreatedBuildEvent} from '../../lib/preview-server/build-events'; import {ChangedPrVisibilityEvent, CreatedBuildEvent} from '../../lib/preview-server/build-events';
import {PreviewServerError} from '../../lib/preview-server/preview-error'; import {PreviewServerError} from '../../lib/preview-server/preview-error';
import {customAsyncMatchers} from './jasmine-custom-async-matchers'; import {expectToBePreviewServerError} from './helpers';
// Tests // Tests
describe('BuildCreator', () => { describe('BuildCreator', () => {
@ -25,7 +24,6 @@ describe('BuildCreator', () => {
const publicShaDir = path.join(publicPrDir, shortSha); const publicShaDir = path.join(publicPrDir, shortSha);
let bc: BuildCreator; let bc: BuildCreator;
beforeEach(() => jasmine.addAsyncMatchers(customAsyncMatchers));
beforeEach(() => bc = new BuildCreator(buildsDir)); beforeEach(() => bc = new BuildCreator(buildsDir));
@ -37,8 +35,8 @@ describe('BuildCreator', () => {
it('should extend EventEmitter', () => { it('should extend EventEmitter', () => {
expect(bc).toBeInstanceOf(BuildCreator); expect(bc).toEqual(jasmine.any(BuildCreator));
expect(bc).toBeInstanceOf(EventEmitter); expect(bc).toEqual(jasmine.any(EventEmitter));
expect(Object.getPrototypeOf(bc)).toBe(BuildCreator.prototype); expect(Object.getPrototypeOf(bc)).toBe(BuildCreator.prototype);
}); });
@ -69,43 +67,47 @@ describe('BuildCreator', () => {
const shaDir = isPublic ? publicShaDir : hiddenShaDir; const shaDir = isPublic ? publicShaDir : hiddenShaDir;
it('should return a promise', async () => { it('should return a promise', done => {
const promise = bc.create(pr, sha, archive, isPublic); const promise = bc.create(pr, sha, archive, isPublic);
expect(promise).toBeInstanceOf(Promise); promise.then(done); // Do not complete the test (and release the spies) synchronously
// to avoid running the actual `extractArchive()`.
// Do not complete the test (and release the spies) synchronously to avoid running the actual expect(promise).toEqual(jasmine.any(Promise));
// `extractArchive()`.
await promise;
}); });
it('should update the PR\'s visibility first if necessary', async () => { it('should update the PR\'s visibility first if necessary', done => {
await bc.create(pr, sha, archive, isPublic); bcUpdatePrVisibilitySpy.and.callFake(() => expect(shellMkdirSpy).not.toHaveBeenCalled());
expect(bcUpdatePrVisibilitySpy).toHaveBeenCalledBefore(shellMkdirSpy); bc.create(pr, sha, archive, isPublic).
expect(bcUpdatePrVisibilitySpy).toHaveBeenCalledWith(pr, isPublic); then(() => {
expect(shellMkdirSpy).toHaveBeenCalled(); expect(bcUpdatePrVisibilitySpy).toHaveBeenCalledWith(pr, isPublic);
expect(shellMkdirSpy).toHaveBeenCalled();
}).
then(done);
}); });
it('should create the build directory (and any parent directories)', async () => { it('should create the build directory (and any parent directories)', done => {
await bc.create(pr, sha, archive, isPublic); bc.create(pr, sha, archive, isPublic).
expect(shellMkdirSpy).toHaveBeenCalledWith('-p', shaDir); then(() => expect(shellMkdirSpy).toHaveBeenCalledWith('-p', shaDir)).
then(done);
}); });
it('should extract the archive contents into the build directory', async () => { it('should extract the archive contents into the build directory', done => {
await bc.create(pr, sha, archive, isPublic); bc.create(pr, sha, archive, isPublic).
expect(bcExtractArchiveSpy).toHaveBeenCalledWith(archive, shaDir); then(() => expect(bcExtractArchiveSpy).toHaveBeenCalledWith(archive, shaDir)).
then(done);
}); });
it('should emit a CreatedBuildEvent on success', async () => { it('should emit a CreatedBuildEvent on success', done => {
let emitted = false; let emitted = false;
bcEmitSpy.and.callFake((type: string, evt: CreatedBuildEvent) => { bcEmitSpy.and.callFake((type: string, evt: CreatedBuildEvent) => {
expect(type).toBe(CreatedBuildEvent.type); expect(type).toBe(CreatedBuildEvent.type);
expect(evt).toBeInstanceOf(CreatedBuildEvent); expect(evt).toEqual(jasmine.any(CreatedBuildEvent));
expect(evt.pr).toBe(+pr); expect(evt.pr).toBe(+pr);
expect(evt.sha).toBe(shortSha); expect(evt.sha).toBe(shortSha);
expect(evt.isPublic).toBe(isPublic); expect(evt.isPublic).toBe(isPublic);
@ -113,108 +115,130 @@ describe('BuildCreator', () => {
emitted = true; emitted = true;
}); });
await bc.create(pr, sha, archive, isPublic); bc.create(pr, sha, archive, isPublic).
expect(emitted).toBe(true); then(() => expect(emitted).toBe(true)).
then(done);
}); });
describe('on error', () => { describe('on error', () => {
let existsValues: {[dir: string]: boolean};
beforeEach(() => { beforeEach(() => {
bcExistsSpy.and.returnValue(false); existsValues = {
[prDir]: false,
[shaDir]: false,
};
bcExistsSpy.and.callFake((dir: string) => existsValues[dir]);
}); });
it('should abort and skip further operations if changing the PR\'s visibility fails', async () => { it('should abort and skip further operations if changing the PR\'s visibility fails', done => {
const mockError = new PreviewServerError(543, 'Test'); const mockError = new PreviewServerError(543, 'Test');
bcUpdatePrVisibilitySpy.and.rejectWith(mockError); bcUpdatePrVisibilitySpy.and.callFake(() => Promise.reject(mockError));
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWith(mockError); bc.create(pr, sha, archive, isPublic).catch(err => {
expect(err).toBe(mockError);
expect(bcExistsSpy).not.toHaveBeenCalled(); expect(bcExistsSpy).not.toHaveBeenCalled();
expect(shellMkdirSpy).not.toHaveBeenCalled(); expect(shellMkdirSpy).not.toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled(); expect(bcExtractArchiveSpy).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
done();
});
}); });
it('should abort and skip further operations if the build does already exist', async () => { it('should abort and skip further operations if the build does already exist', done => {
bcExistsSpy.withArgs(shaDir).and.returnValue(true); existsValues[shaDir] = true;
bc.create(pr, sha, archive, isPublic).catch(err => {
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWithPreviewServerError( const publicOrNot = isPublic ? 'public' : 'non-public';
409, `Request to overwrite existing ${isPublic ? '' : 'non-'}public directory: ${shaDir}`); expectToBePreviewServerError(err, 409, `Request to overwrite existing ${publicOrNot} directory: ${shaDir}`);
expect(shellMkdirSpy).not.toHaveBeenCalled();
expect(shellMkdirSpy).not.toHaveBeenCalled(); expect(bcExtractArchiveSpy).not.toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled(); done();
});
}); });
it('should detect existing build directory after visibility change', async () => { it('should detect existing build directory after visibility change', done => {
bcUpdatePrVisibilitySpy.and.callFake(() => bcExistsSpy.and.returnValue(true)); bcUpdatePrVisibilitySpy.and.callFake(() => existsValues[prDir] = existsValues[shaDir] = true);
expect(bcExistsSpy(prDir)).toBe(false); expect(bcExistsSpy(prDir)).toBe(false);
expect(bcExistsSpy(shaDir)).toBe(false); expect(bcExistsSpy(shaDir)).toBe(false);
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWithPreviewServerError( bc.create(pr, sha, archive, isPublic).catch(err => {
409, `Request to overwrite existing ${isPublic ? '' : 'non-'}public directory: ${shaDir}`); const publicOrNot = isPublic ? 'public' : 'non-public';
expectToBePreviewServerError(err, 409, `Request to overwrite existing ${publicOrNot} directory: ${shaDir}`);
expect(shellMkdirSpy).not.toHaveBeenCalled(); expect(shellMkdirSpy).not.toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled(); expect(bcExtractArchiveSpy).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
done();
});
}); });
it('should abort and skip further operations if it fails to create the directories', async () => { it('should abort and skip further operations if it fails to create the directories', done => {
shellMkdirSpy.and.throwError(''); shellMkdirSpy.and.throwError('');
bc.create(pr, sha, archive, isPublic).catch(() => {
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejected(); expect(shellMkdirSpy).toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled();
expect(shellMkdirSpy).toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
expect(bcExtractArchiveSpy).not.toHaveBeenCalled(); done();
expect(bcEmitSpy).not.toHaveBeenCalled(); });
}); });
it('should abort and skip further operations if it fails to extract the archive', async () => { it('should abort and skip further operations if it fails to extract the archive', done => {
bcExtractArchiveSpy.and.throwError('');
bc.create(pr, sha, archive, isPublic).catch(() => {
expect(shellMkdirSpy).toHaveBeenCalled();
expect(bcExtractArchiveSpy).toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled();
done();
});
});
it('should delete the PR directory (for new PR)', done => {
bcExtractArchiveSpy.and.throwError('');
bc.create(pr, sha, archive, isPublic).catch(() => {
expect(shellRmSpy).toHaveBeenCalledWith('-rf', prDir);
done();
});
});
it('should delete the SHA directory (for existing PR)', done => {
existsValues[prDir] = true;
bcExtractArchiveSpy.and.throwError(''); bcExtractArchiveSpy.and.throwError('');
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejected(); bc.create(pr, sha, archive, isPublic).catch(() => {
expect(shellRmSpy).toHaveBeenCalledWith('-rf', shaDir);
expect(shellMkdirSpy).toHaveBeenCalled(); done();
expect(bcExtractArchiveSpy).toHaveBeenCalled(); });
expect(bcEmitSpy).not.toHaveBeenCalled();
}); });
it('should delete the PR directory (for new PR)', async () => { it('should reject with an PreviewServerError', done => {
bcExtractArchiveSpy.and.throwError('');
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejected();
expect(shellRmSpy).toHaveBeenCalledWith('-rf', prDir);
});
it('should delete the SHA directory (for existing PR)', async () => {
bcExistsSpy.withArgs(prDir).and.returnValue(true);
bcExtractArchiveSpy.and.throwError('');
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejected();
expect(shellRmSpy).toHaveBeenCalledWith('-rf', shaDir);
});
it('should reject with an PreviewServerError', async () => {
// tslint:disable-next-line: no-string-throw // tslint:disable-next-line: no-string-throw
shellMkdirSpy.and.callFake(() => { throw 'Test'; }); shellMkdirSpy.and.callFake(() => { throw 'Test'; });
bc.create(pr, sha, archive, isPublic).catch(err => {
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWithPreviewServerError( expectToBePreviewServerError(err, 500, `Error while creating preview at: ${shaDir}\nTest`);
500, `Error while creating preview at: ${shaDir}\nTest`); done();
});
}); });
it('should pass PreviewServerError instances unmodified', async () => { it('should pass PreviewServerError instances unmodified', done => {
shellMkdirSpy.and.callFake(() => { throw new PreviewServerError(543, 'Test'); }); shellMkdirSpy.and.callFake(() => { throw new PreviewServerError(543, 'Test'); });
await expectAsync(bc.create(pr, sha, archive, isPublic)).toBeRejectedWithPreviewServerError(543, 'Test'); bc.create(pr, sha, archive, isPublic).catch(err => {
expectToBePreviewServerError(err, 543, 'Test');
done();
});
}); });
}); });
@ -241,12 +265,12 @@ describe('BuildCreator', () => {
}); });
it('should return a promise', async () => { it('should return a promise', done => {
const promise = bc.updatePrVisibility(pr, true); const promise = bc.updatePrVisibility(pr, true);
expect(promise).toBeInstanceOf(Promise); promise.then(done); // Do not complete the test (and release the spies) synchronously
// to avoid running the actual `extractArchive()`.
// Do not complete the test (and release the spies) synchronously to avoid running the actual `extractArchive()`. expect(promise).toEqual(jasmine.any(Promise));
await promise;
}); });
@ -255,53 +279,58 @@ describe('BuildCreator', () => {
const newPrDir = makePublic ? publicPrDir : hiddenPrDir; const newPrDir = makePublic ? publicPrDir : hiddenPrDir;
it('should rename the directory', async () => { it('should rename the directory', done => {
await bc.updatePrVisibility(pr, makePublic); bc.updatePrVisibility(pr, makePublic).
expect(shellMvSpy).toHaveBeenCalledWith(oldPrDir, newPrDir); then(() => expect(shellMvSpy).toHaveBeenCalledWith(oldPrDir, newPrDir)).
then(done);
}); });
describe('when the visibility is updated', () => { describe('when the visibility is updated', () => {
it('should resolve to true', async () => { it('should resolve to true', done => {
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeResolvedTo(true); bc.updatePrVisibility(pr, makePublic).
then(result => expect(result).toBe(true)).
then(done);
}); });
it('should rename the directory', async () => { it('should rename the directory', done => {
await bc.updatePrVisibility(pr, makePublic); bc.updatePrVisibility(pr, makePublic).
expect(shellMvSpy).toHaveBeenCalledWith(oldPrDir, newPrDir); then(() => expect(shellMvSpy).toHaveBeenCalledWith(oldPrDir, newPrDir)).
then(done);
}); });
it('should emit a ChangedPrVisibilityEvent on success', async () => { it('should emit a ChangedPrVisibilityEvent on success', done => {
let emitted = false; let emitted = false;
bcEmitSpy.and.callFake((type: string, evt: ChangedPrVisibilityEvent) => { bcEmitSpy.and.callFake((type: string, evt: ChangedPrVisibilityEvent) => {
expect(type).toBe(ChangedPrVisibilityEvent.type); expect(type).toBe(ChangedPrVisibilityEvent.type);
expect(evt).toBeInstanceOf(ChangedPrVisibilityEvent); expect(evt).toEqual(jasmine.any(ChangedPrVisibilityEvent));
expect(evt.pr).toBe(+pr); expect(evt.pr).toBe(+pr);
expect(evt.shas).toBeInstanceOf(Array); expect(evt.shas).toEqual(jasmine.any(Array));
expect(evt.isPublic).toBe(makePublic); expect(evt.isPublic).toBe(makePublic);
emitted = true; emitted = true;
}); });
await bc.updatePrVisibility(pr, makePublic); bc.updatePrVisibility(pr, makePublic).
expect(emitted).toBe(true); then(() => expect(emitted).toBe(true)).
then(done);
}); });
it('should include all shas in the emitted event', async () => { it('should include all shas in the emitted event', done => {
const shas = ['foo', 'bar', 'baz']; const shas = ['foo', 'bar', 'baz'];
let emitted = false; let emitted = false;
bcListShasByDate.and.resolveTo(shas); bcListShasByDate.and.callFake(() => Promise.resolve(shas));
bcEmitSpy.and.callFake((type: string, evt: ChangedPrVisibilityEvent) => { bcEmitSpy.and.callFake((type: string, evt: ChangedPrVisibilityEvent) => {
expect(bcListShasByDate).toHaveBeenCalledWith(newPrDir); expect(bcListShasByDate).toHaveBeenCalledWith(newPrDir);
expect(type).toBe(ChangedPrVisibilityEvent.type); expect(type).toBe(ChangedPrVisibilityEvent.type);
expect(evt).toBeInstanceOf(ChangedPrVisibilityEvent); expect(evt).toEqual(jasmine.any(ChangedPrVisibilityEvent));
expect(evt.pr).toBe(+pr); expect(evt.pr).toBe(+pr);
expect(evt.shas).toBe(shas); expect(evt.shas).toBe(shas);
expect(evt.isPublic).toBe(makePublic); expect(evt.isPublic).toBe(makePublic);
@ -309,82 +338,94 @@ describe('BuildCreator', () => {
emitted = true; emitted = true;
}); });
await bc.updatePrVisibility(pr, makePublic); bc.updatePrVisibility(pr, makePublic).
expect(emitted).toBe(true); then(() => expect(emitted).toBe(true)).
then(done);
}); });
}); });
it('should do nothing if the visibility is already up-to-date', async () => { it('should do nothing if the visibility is already up-to-date', done => {
bcExistsSpy.and.callFake((dir: string) => dir === newPrDir); bcExistsSpy.and.callFake((dir: string) => dir === newPrDir);
bc.updatePrVisibility(pr, makePublic).
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeResolvedTo(false); then(result => {
expect(result).toBe(false);
expect(shellMvSpy).not.toHaveBeenCalled(); expect(shellMvSpy).not.toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled(); expect(bcListShasByDate).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
}).
then(done);
}); });
it('should do nothing if the PR directory does not exist', async () => { it('should do nothing if the PR directory does not exist', done => {
bcExistsSpy.and.returnValue(false); bcExistsSpy.and.returnValue(false);
bc.updatePrVisibility(pr, makePublic).
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeResolvedTo(false); then(result => {
expect(result).toBe(false);
expect(shellMvSpy).not.toHaveBeenCalled(); expect(shellMvSpy).not.toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled(); expect(bcListShasByDate).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
}).
then(done);
}); });
describe('on error', () => { describe('on error', () => {
it('should abort and skip further operations if both directories exist', async () => { it('should abort and skip further operations if both directories exist', done => {
bcExistsSpy.and.returnValue(true); bcExistsSpy.and.returnValue(true);
bc.updatePrVisibility(pr, makePublic).catch(err => {
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejectedWithPreviewServerError( expectToBePreviewServerError(err, 409,
409, `Request to move '${oldPrDir}' to existing directory '${newPrDir}'.`); `Request to move '${oldPrDir}' to existing directory '${newPrDir}'.`);
expect(shellMvSpy).not.toHaveBeenCalled();
expect(shellMvSpy).not.toHaveBeenCalled(); expect(bcListShasByDate).not.toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
expect(bcEmitSpy).not.toHaveBeenCalled(); done();
});
}); });
it('should abort and skip further operations if it fails to rename the directory', async () => { it('should abort and skip further operations if it fails to rename the directory', done => {
shellMvSpy.and.throwError(''); shellMvSpy.and.throwError('');
bc.updatePrVisibility(pr, makePublic).catch(() => {
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejected(); expect(shellMvSpy).toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled();
expect(shellMvSpy).toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
expect(bcListShasByDate).not.toHaveBeenCalled(); done();
expect(bcEmitSpy).not.toHaveBeenCalled(); });
}); });
it('should abort and skip further operations if it fails to list the SHAs', async () => { it('should abort and skip further operations if it fails to list the SHAs', done => {
bcListShasByDate.and.throwError(''); bcListShasByDate.and.throwError('');
bc.updatePrVisibility(pr, makePublic).catch(() => {
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejected(); expect(shellMvSpy).toHaveBeenCalled();
expect(bcListShasByDate).toHaveBeenCalled();
expect(shellMvSpy).toHaveBeenCalled(); expect(bcEmitSpy).not.toHaveBeenCalled();
expect(bcListShasByDate).toHaveBeenCalled(); done();
expect(bcEmitSpy).not.toHaveBeenCalled(); });
}); });
it('should reject with an PreviewServerError', async () => { it('should reject with an PreviewServerError', done => {
// tslint:disable-next-line: no-string-throw // tslint:disable-next-line: no-string-throw
shellMvSpy.and.callFake(() => { throw 'Test'; }); shellMvSpy.and.callFake(() => { throw 'Test'; });
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejectedWithPreviewServerError( bc.updatePrVisibility(pr, makePublic).catch(err => {
500, `Error while making PR ${pr} ${makePublic ? 'public' : 'hidden'}.\nTest`); expectToBePreviewServerError(err, 500,
`Error while making PR ${pr} ${makePublic ? 'public' : 'hidden'}.\nTest`);
done();
});
}); });
it('should pass PreviewServerError instances unmodified', async () => { it('should pass PreviewServerError instances unmodified', done => {
shellMvSpy.and.callFake(() => { throw new PreviewServerError(543, 'Test'); }); shellMvSpy.and.callFake(() => { throw new PreviewServerError(543, 'Test'); });
await expectAsync(bc.updatePrVisibility(pr, makePublic)).toBeRejectedWithPreviewServerError(543, 'Test'); bc.updatePrVisibility(pr, makePublic).catch(err => {
expectToBePreviewServerError(err, 543, 'Test');
done();
});
}); });
}); });
@ -402,14 +443,12 @@ describe('BuildCreator', () => {
beforeEach(() => { beforeEach(() => {
fsAccessCbs = []; fsAccessCbs = [];
fsAccessSpy = spyOn(fs, 'access').and.callFake( fsAccessSpy = spyOn(fs, 'access').and.callFake((_: string, cb: (v?: any) => void) => fsAccessCbs.push(cb));
((_: string, cb: (v?: any) => void) => fsAccessCbs.push(cb)) as unknown as typeof fs.access,
);
}); });
it('should return a promise', () => { it('should return a promise', () => {
expect((bc as any).exists('foo')).toBeInstanceOf(Promise); expect((bc as any).exists('foo')).toEqual(jasmine.any(Promise));
}); });
@ -419,29 +458,25 @@ describe('BuildCreator', () => {
}); });
it('should resolve with \'true\' if \'fs.access()\' succeeds', async () => { it('should resolve with \'true\' if \'fs.access()\' succeeds', done => {
const existsPromises = [ Promise.
(bc as any).exists('foo'), all([(bc as any).exists('foo'), (bc as any).exists('bar')]).
(bc as any).exists('bar'), then(results => expect(results).toEqual([true, true])).
]; then(done);
fsAccessCbs[0](); fsAccessCbs[0]();
fsAccessCbs[1](null); fsAccessCbs[1](null);
await expectAsync(Promise.all(existsPromises)).toBeResolvedTo([true, true]);
}); });
it('should resolve with \'false\' if \'fs.access()\' errors', async () => { it('should resolve with \'false\' if \'fs.access()\' errors', done => {
const existsPromises = [ Promise.
(bc as any).exists('foo'), all([(bc as any).exists('foo'), (bc as any).exists('bar')]).
(bc as any).exists('bar'), then(results => expect(results).toEqual([false, false])).
]; then(done);
fsAccessCbs[0]('Error'); fsAccessCbs[0]('Error');
fsAccessCbs[1](new Error()); fsAccessCbs[1](new Error());
await expectAsync(Promise.all(existsPromises)).toBeResolvedTo([false, false]);
}); });
}); });
@ -460,15 +495,12 @@ describe('BuildCreator', () => {
consoleWarnSpy = spyOn(Logger.prototype, 'warn'); consoleWarnSpy = spyOn(Logger.prototype, 'warn');
shellChmodSpy = spyOn(shell, 'chmod'); shellChmodSpy = spyOn(shell, 'chmod');
shellRmSpy = spyOn(shell, 'rm'); shellRmSpy = spyOn(shell, 'rm');
cpExecSpy = spyOn(cp, 'exec').and.callFake( cpExecSpy = spyOn(cp, 'exec').and.callFake((_: string, cb: (...args: any[]) => void) => cpExecCbs.push(cb));
((_: string, cb: (...args: any[]) => void) =>
cpExecCbs.push(cb)) as unknown as typeof cp.exec,
);
}); });
it('should return a promise', () => { it('should return a promise', () => {
expect((bc as any).extractArchive('foo', 'bar')).toBeInstanceOf(Promise); expect((bc as any).extractArchive('foo', 'bar')).toEqual(jasmine.any(Promise));
}); });
@ -480,68 +512,78 @@ describe('BuildCreator', () => {
}); });
it('should log (as a warning) any stderr output if extracting succeeded', async () => { it('should log (as a warning) any stderr output if extracting succeeded', done => {
const extractPromise = (bc as any).extractArchive('foo', 'bar'); (bc as any).extractArchive('foo', 'bar').
then(() => expect(consoleWarnSpy).toHaveBeenCalledWith('This is stderr')).
then(done);
cpExecCbs[0](null, 'This is stdout', 'This is stderr'); cpExecCbs[0](null, 'This is stdout', 'This is stderr');
await expectAsync(extractPromise).toBeResolved();
expect(consoleWarnSpy).toHaveBeenCalledWith('This is stderr');
}); });
it('should make the build directory non-writable', async () => { it('should make the build directory non-writable', done => {
const extractPromise = (bc as any).extractArchive('foo', 'bar'); (bc as any).extractArchive('foo', 'bar').
cpExecCbs[0](); then(() => expect(shellChmodSpy).toHaveBeenCalledWith('-R', 'a-w', 'bar')).
then(done);
await expectAsync(extractPromise).toBeResolved(); cpExecCbs[0]();
expect(shellChmodSpy).toHaveBeenCalledWith('-R', 'a-w', 'bar');
}); });
it('should delete the build artifact file on success', async () => { it('should delete the build artifact file on success', done => {
const extractPromise = (bc as any).extractArchive('input/file', 'output/dir'); (bc as any).extractArchive('input/file', 'output/dir').
cpExecCbs[0](); then(() => expect(shellRmSpy).toHaveBeenCalledWith('-f', 'input/file')).
then(done);
await expectAsync(extractPromise).toBeResolved(); cpExecCbs[0]();
expect(shellRmSpy).toHaveBeenCalledWith('-f', 'input/file');
}); });
describe('on error', () => { describe('on error', () => {
it('should abort and skip further operations if it fails to extract the archive', async () => { it('should abort and skip further operations if it fails to extract the archive', done => {
const extractPromise = (bc as any).extractArchive('foo', 'bar'); (bc as any).extractArchive('foo', 'bar').catch((err: any) => {
expect(shellChmodSpy).not.toHaveBeenCalled();
expect(shellRmSpy).not.toHaveBeenCalled();
expect(err).toBe('Test');
done();
});
cpExecCbs[0]('Test'); cpExecCbs[0]('Test');
await expectAsync(extractPromise).toBeRejectedWith('Test');
expect(shellChmodSpy).not.toHaveBeenCalled();
expect(shellRmSpy).not.toHaveBeenCalled();
}); });
it('should abort and skip further operations if it fails to make non-writable', async () => { it('should abort and skip further operations if it fails to make non-writable', done => {
// tslint:disable-next-line: no-string-throw (bc as any).extractArchive('foo', 'bar').catch((err: any) => {
shellChmodSpy.and.callFake(() => { throw 'Test'; }); expect(shellChmodSpy).toHaveBeenCalled();
expect(shellRmSpy).not.toHaveBeenCalled();
expect(err).toBe('Test');
done();
});
shellChmodSpy.and.callFake(() => {
// tslint:disable-next-line: no-string-throw
throw 'Test';
});
const extractPromise = (bc as any).extractArchive('foo', 'bar');
cpExecCbs[0](); cpExecCbs[0]();
await expectAsync(extractPromise).toBeRejectedWith('Test');
expect(shellChmodSpy).toHaveBeenCalled();
expect(shellRmSpy).not.toHaveBeenCalled();
}); });
it('should abort and reject if it fails to remove the build artifact file', async () => { it('should abort and reject if it fails to remove the build artifact file', done => {
// tslint:disable-next-line: no-string-throw (bc as any).extractArchive('foo', 'bar').catch((err: any) => {
shellRmSpy.and.callFake(() => { throw 'Test'; }); expect(shellChmodSpy).toHaveBeenCalled();
expect(shellRmSpy).toHaveBeenCalled();
expect(err).toBe('Test');
done();
});
shellRmSpy.and.callFake(() => {
// tslint:disable-next-line: no-string-throw
throw 'Test';
});
const extractPromise = (bc as any).extractArchive('foo', 'bar');
cpExecCbs[0](); cpExecCbs[0]();
await expectAsync(extractPromise).toBeRejectedWith('Test');
expect(shellChmodSpy).toHaveBeenCalled();
expect(shellRmSpy).toHaveBeenCalled();
}); });
}); });
@ -558,54 +600,62 @@ describe('BuildCreator', () => {
}); });
beforeEach(() => { beforeEach(() => {
shellLsSpy = spyOn(shell, 'ls').and.returnValue([] as unknown as shell.ShellArray); shellLsSpy = spyOn(shell, 'ls').and.returnValue([]);
}); });
it('should return a promise', async () => { it('should return a promise', done => {
const promise = (bc as any).listShasByDate('input/dir'); const promise = (bc as any).listShasByDate('input/dir');
expect(promise).toBeInstanceOf(Promise); promise.then(done); // Do not complete the test (and release the spies) synchronously
// to avoid running the actual `ls()`.
// Do not complete the test (and release the spies) synchronously to avoid running the actual `ls()`. expect(promise).toEqual(jasmine.any(Promise));
await promise;
}); });
it('should `ls()` files with their metadata', async () => { it('should `ls()` files with their metadata', done => {
await (bc as any).listShasByDate('input/dir'); (bc as any).listShasByDate('input/dir').
expect(shellLsSpy).toHaveBeenCalledWith('-l', 'input/dir'); then(() => expect(shellLsSpy).toHaveBeenCalledWith('-l', 'input/dir')).
then(done);
}); });
it('should reject if listing files fails', async () => { it('should reject if listing files fails', done => {
shellLsSpy.and.rejectWith('Test'); shellLsSpy.and.callFake(() => Promise.reject('Test'));
await expectAsync((bc as any).listShasByDate('input/dir')).toBeRejectedWith('Test'); (bc as any).listShasByDate('input/dir').catch((err: string) => {
expect(err).toBe('Test');
done();
});
}); });
it('should return the filenames', async () => { it('should return the filenames', done => {
shellLsSpy.and.resolveTo([ shellLsSpy.and.callFake(() => Promise.resolve([
lsResult('foo', 100), lsResult('foo', 100),
lsResult('bar', 200), lsResult('bar', 200),
lsResult('baz', 300), lsResult('baz', 300),
]); ]));
await expectAsync((bc as any).listShasByDate('input/dir')).toBeResolvedTo(['foo', 'bar', 'baz']); (bc as any).listShasByDate('input/dir').
then((shas: string[]) => expect(shas).toEqual(['foo', 'bar', 'baz'])).
then(done);
}); });
it('should sort by date', async () => { it('should sort by date', done => {
shellLsSpy.and.resolveTo([ shellLsSpy.and.callFake(() => Promise.resolve([
lsResult('foo', 300), lsResult('foo', 300),
lsResult('bar', 100), lsResult('bar', 100),
lsResult('baz', 200), lsResult('baz', 200),
]); ]));
await expectAsync((bc as any).listShasByDate('input/dir')).toBeResolvedTo(['bar', 'baz', 'foo']); (bc as any).listShasByDate('input/dir').
then((shas: string[]) => expect(shas).toEqual(['bar', 'baz', 'foo'])).
then(done);
}); });
it('should not break with ShellJS\' custom `sort()` method', async () => { it('should not break with ShellJS\' custom `sort()` method', done => {
const mockArray = [ const mockArray = [
lsResult('foo', 300), lsResult('foo', 300),
lsResult('bar', 100), lsResult('bar', 100),
@ -613,21 +663,26 @@ describe('BuildCreator', () => {
]; ];
mockArray.sort = jasmine.createSpy('sort'); mockArray.sort = jasmine.createSpy('sort');
shellLsSpy.and.resolveTo(mockArray); shellLsSpy.and.callFake(() => Promise.resolve(mockArray));
(bc as any).listShasByDate('input/dir').
await expectAsync((bc as any).listShasByDate('input/dir')).toBeResolvedTo(['bar', 'baz', 'foo']); then((shas: string[]) => {
expect(mockArray.sort).not.toHaveBeenCalled(); expect(shas).toEqual(['bar', 'baz', 'foo']);
expect(mockArray.sort).not.toHaveBeenCalled();
}).
then(done);
}); });
it('should only include directories', async () => { it('should only include directories', done => {
shellLsSpy.and.resolveTo([ shellLsSpy.and.callFake(() => Promise.resolve([
lsResult('foo', 100), lsResult('foo', 100),
lsResult('bar', 200, false), lsResult('bar', 200, false),
lsResult('baz', 300), lsResult('baz', 300),
]); ]));
await expectAsync((bc as any).listShasByDate('input/dir')).toBeResolvedTo(['foo', 'baz']); (bc as any).listShasByDate('input/dir').
then((shas: string[]) => expect(shas).toEqual(['foo', 'baz'])).
then(done);
}); });
}); });

View File

@ -32,18 +32,18 @@ describe('BuildRetriever', () => {
}; };
api = new CircleCiApi('ORG', 'REPO', 'TOKEN'); api = new CircleCiApi('ORG', 'REPO', 'TOKEN');
spyOn(api, 'getBuildInfo').and.resolveTo(BUILD_INFO); spyOn(api, 'getBuildInfo').and.callFake(() => Promise.resolve(BUILD_INFO));
getBuildArtifactUrlSpy = spyOn(api, 'getBuildArtifactUrl').and.resolveTo(BASE_URL + ARTIFACT_PATH); getBuildArtifactUrlSpy = spyOn(api, 'getBuildArtifactUrl')
.and.callFake(() => Promise.resolve(BASE_URL + ARTIFACT_PATH));
WRITEFILE_RESULT = undefined; WRITEFILE_RESULT = undefined;
writeFileSpy = spyOn(fs, 'writeFile').and.callFake( writeFileSpy = spyOn(fs, 'writeFile').and.callFake(
((_path: string, _buffer: Buffer, callback: fs.NoParamCallback) => (_path: string, _buffer: Buffer, callback: (err?: any) => {}) => callback(WRITEFILE_RESULT),
callback(WRITEFILE_RESULT)) as typeof fs.writeFile,
); );
EXISTS_RESULT = false; EXISTS_RESULT = false;
existsSpy = spyOn(fs, 'exists').and.callFake( existsSpy = spyOn(fs, 'exists').and.callFake(
((_path, callback) => callback(EXISTS_RESULT)) as typeof fs.exists, (_path: string, callback: (exists: boolean) => {}) => callback(EXISTS_RESULT),
); );
}); });
@ -56,7 +56,6 @@ describe('BuildRetriever', () => {
expect(() => new BuildRetriever(api, -1, DOWNLOAD_DIR)) expect(() => new BuildRetriever(api, -1, DOWNLOAD_DIR))
.toThrowError(`Invalid parameter "downloadSizeLimit" should be a number greater than 0.`); .toThrowError(`Invalid parameter "downloadSizeLimit" should be a number greater than 0.`);
}); });
it('should fail if the "downloadDir" is missing', () => { it('should fail if the "downloadDir" is missing', () => {
expect(() => new BuildRetriever(api, MAX_DOWNLOAD_SIZE, '')) expect(() => new BuildRetriever(api, MAX_DOWNLOAD_SIZE, ''))
.toThrowError(`Missing or empty required parameter 'downloadDir'!`); .toThrowError(`Missing or empty required parameter 'downloadDir'!`);
@ -73,10 +72,14 @@ describe('BuildRetriever', () => {
}); });
it('should error if it is not possible to extract the PR number from the branch', async () => { it('should error if it is not possible to extract the PR number from the branch', async () => {
BUILD_INFO.branch = 'master';
const retriever = new BuildRetriever(api, MAX_DOWNLOAD_SIZE, DOWNLOAD_DIR); const retriever = new BuildRetriever(api, MAX_DOWNLOAD_SIZE, DOWNLOAD_DIR);
try {
await expectAsync(retriever.getGithubInfo(12345)).toBeRejectedWithError('No PR found in branch field: master'); BUILD_INFO.branch = 'master';
await retriever.getGithubInfo(12345);
throw new Error('Exception Expected');
} catch (error) {
expect(error.message).toEqual('No PR found in branch field: master');
}
}); });
}); });
@ -107,10 +110,12 @@ describe('BuildRetriever', () => {
it('should fail if the artifact is too large', async () => { it('should fail if the artifact is too large', async () => {
const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(200, ARTIFACT_CONTENTS); const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(200, ARTIFACT_CONTENTS);
retriever = new BuildRetriever(api, 10, DOWNLOAD_DIR); retriever = new BuildRetriever(api, 10, DOWNLOAD_DIR);
try {
await expectAsync(retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH)). await retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH);
toBeRejectedWith(jasmine.objectContaining({status: 413})); throw new Error('Exception Expected');
} catch (error) {
expect(error.status).toEqual(413);
}
artifactRequest.done(); artifactRequest.done();
}); });
@ -138,40 +143,50 @@ describe('BuildRetriever', () => {
artifactRequest.done(); artifactRequest.done();
}); });
it('should fail if the CircleCI API fails', async () => { it('should fail if the CircleCI API fails', async () => {
getBuildArtifactUrlSpy.and.rejectWith('getBuildArtifactUrl failed'); try {
await expectAsync(retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH)). getBuildArtifactUrlSpy.and.callFake(() => Promise.reject('getBuildArtifactUrl failed'));
toBeRejectedWithError('CircleCI artifact download failed (getBuildArtifactUrl failed)'); await retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH);
throw new Error('Exception Expected');
} catch (error) {
expect(error.message).toEqual('CircleCI artifact download failed (getBuildArtifactUrl failed)');
}
}); });
it('should fail if the URL fetch errors', async () => { it('should fail if the URL fetch errors', async () => {
// create a new handler that errors // create a new handler that errors
const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).replyWithError('Artifact Request Failed'); const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).replyWithError('Artifact Request Failed');
try {
await expectAsync(retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH)).toBeRejectedWithError( await retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH);
'CircleCI artifact download failed ' + throw new Error('Exception Expected');
} catch (error) {
expect(error.message).toEqual('CircleCI artifact download failed ' +
'(request to http://test.com/some/path/build.zip failed, reason: Artifact Request Failed)'); '(request to http://test.com/some/path/build.zip failed, reason: Artifact Request Failed)');
}
artifactRequest.done(); artifactRequest.done();
}); });
it('should fail if the URL fetch 404s', async () => { it('should fail if the URL fetch 404s', async () => {
// create a new handler that errors // create a new handler that errors
const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(404, 'No such artifact'); const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(404, 'No such artifact');
try {
await expectAsync(retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH)). await retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH);
toBeRejectedWithError('CircleCI artifact download failed (Error 404 - Not Found)'); throw new Error('Exception Expected');
} catch (error) {
expect(error.message).toEqual('CircleCI artifact download failed (Error 404 - Not Found)');
}
artifactRequest.done(); artifactRequest.done();
}); });
it('should fail if file write fails', async () => { it('should fail if file write fails', async () => {
const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(200, ARTIFACT_CONTENTS); const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(200, ARTIFACT_CONTENTS);
WRITEFILE_RESULT = 'Test Error'; try {
WRITEFILE_RESULT = 'Test Error';
await expectAsync(retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH)). await retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH);
toBeRejectedWithError('CircleCI artifact download failed (Test Error)'); throw new Error('Exception Expected');
} catch (error) {
expect(error.message).toEqual('CircleCI artifact download failed (Test Error)');
}
artifactRequest.done(); artifactRequest.done();
}); });
}); });

View File

@ -51,10 +51,7 @@ describe('BuildVerifier', () => {
describe('getSignificantFilesChanged', () => { describe('getSignificantFilesChanged', () => {
it('should return false if none of the fetched files match the given pattern', async () => { it('should return false if none of the fetched files match the given pattern', async () => {
const fetchFilesSpy = spyOn(prs, 'fetchFiles'); const fetchFilesSpy = spyOn(prs, 'fetchFiles');
fetchFilesSpy.and.resolveTo([ fetchFilesSpy.and.callFake(() => Promise.resolve([{filename: 'a/b/c'}, {filename: 'd/e/f'}]));
{filename: 'a/b/c', sha: 'a1'},
{filename: 'd/e/f', sha: 'b2'},
]);
expect(await bv.getSignificantFilesChanged(777, /^x/)).toEqual(false); expect(await bv.getSignificantFilesChanged(777, /^x/)).toEqual(false);
expect(fetchFilesSpy).toHaveBeenCalledWith(777); expect(fetchFilesSpy).toHaveBeenCalledWith(777);
@ -81,30 +78,37 @@ describe('BuildVerifier', () => {
user: {login: 'username'}, user: {login: 'username'},
}; };
prsFetchSpy = spyOn(GithubPullRequests.prototype, 'fetch').and.resolveTo(mockPrInfo); prsFetchSpy = spyOn(GithubPullRequests.prototype, 'fetch').
teamsIsMemberBySlugSpy = spyOn(GithubTeams.prototype, 'isMemberBySlug').and.resolveTo(true); and.callFake(() => Promise.resolve(mockPrInfo));
teamsIsMemberBySlugSpy = spyOn(GithubTeams.prototype, 'isMemberBySlug').
and.callFake(() => Promise.resolve(true));
}); });
it('should return a promise', async () => { it('should return a promise', done => {
const promise = bv.getPrIsTrusted(pr); const promise = bv.getPrIsTrusted(pr);
expect(promise).toBeInstanceOf(Promise); promise.then(done); // Do not complete the test (and release the spies) synchronously
// to avoid running the actual `GithubTeams#isMemberBySlug()`.
// Do not complete the test (and release the spies) synchronously to avoid running the actual expect(promise).toEqual(jasmine.any(Promise));
// `GithubTeams#isMemberBySlug()`.
await promise;
}); });
it('should fetch the corresponding PR', async () => { it('should fetch the corresponding PR', done => {
await bv.getPrIsTrusted(pr); bv.getPrIsTrusted(pr).then(() => {
expect(prsFetchSpy).toHaveBeenCalledWith(pr); expect(prsFetchSpy).toHaveBeenCalledWith(pr);
done();
});
}); });
it('should fail if fetching the PR errors', async () => { it('should fail if fetching the PR errors', done => {
prsFetchSpy.and.rejectWith('Test'); prsFetchSpy.and.callFake(() => Promise.reject('Test'));
await expectAsync(bv.getPrIsTrusted(pr)).toBeRejectedWith('Test'); bv.getPrIsTrusted(pr).catch(err => {
expect(err).toBe('Test');
done();
});
}); });
@ -113,14 +117,19 @@ describe('BuildVerifier', () => {
beforeEach(() => mockPrInfo.labels.push({name: 'trusted: pr-label'})); beforeEach(() => mockPrInfo.labels.push({name: 'trusted: pr-label'}));
it('should resolve to true', async () => { it('should resolve to true', done => {
await expectAsync(bv.getPrIsTrusted(pr)).toBeResolvedTo(true); bv.getPrIsTrusted(pr).then(isTrusted => {
expect(isTrusted).toBe(true);
done();
});
}); });
it('should not try to verify the author\'s membership status', async () => { it('should not try to verify the author\'s membership status', done => {
await expectAsync(bv.getPrIsTrusted(pr)); bv.getPrIsTrusted(pr).then(() => {
expect(teamsIsMemberBySlugSpy).not.toHaveBeenCalled(); expect(teamsIsMemberBySlugSpy).not.toHaveBeenCalled();
done();
});
}); });
}); });
@ -128,27 +137,40 @@ describe('BuildVerifier', () => {
describe('when the PR does not have the "trusted PR" label', () => { describe('when the PR does not have the "trusted PR" label', () => {
it('should verify the PR author\'s membership in the specified teams', async () => { it('should verify the PR author\'s membership in the specified teams', done => {
await bv.getPrIsTrusted(pr); bv.getPrIsTrusted(pr).then(() => {
expect(teamsIsMemberBySlugSpy).toHaveBeenCalledWith('username', ['team1', 'team2']); expect(teamsIsMemberBySlugSpy).toHaveBeenCalledWith('username', ['team1', 'team2']);
done();
});
}); });
it('should fail if verifying membership errors', async () => { it('should fail if verifying membership errors', done => {
teamsIsMemberBySlugSpy.and.rejectWith('Test'); teamsIsMemberBySlugSpy.and.callFake(() => Promise.reject('Test'));
await expectAsync(bv.getPrIsTrusted(pr)).toBeRejectedWith('Test'); bv.getPrIsTrusted(pr).catch(err => {
expect(err).toBe('Test');
done();
});
}); });
it('should resolve to true if the PR\'s author is a member', async () => { it('should resolve to true if the PR\'s author is a member', done => {
teamsIsMemberBySlugSpy.and.resolveTo(true); teamsIsMemberBySlugSpy.and.callFake(() => Promise.resolve(true));
await expectAsync(bv.getPrIsTrusted(pr)).toBeResolvedTo(true);
bv.getPrIsTrusted(pr).then(isTrusted => {
expect(isTrusted).toBe(true);
done();
});
}); });
it('should resolve to false if the PR\'s author is not a member', async () => { it('should resolve to false if the PR\'s author is not a member', done => {
teamsIsMemberBySlugSpy.and.resolveTo(false); teamsIsMemberBySlugSpy.and.callFake(() => Promise.resolve(false));
await expectAsync(bv.getPrIsTrusted(pr)).toBeResolvedTo(false);
bv.getPrIsTrusted(pr).then(isTrusted => {
expect(isTrusted).toBe(false);
done();
});
}); });
}); });

View File

@ -0,0 +1,11 @@
import {PreviewServerError} from '../../lib/preview-server/preview-error';
export const expectToBePreviewServerError = (actual: PreviewServerError, status?: number, message?: string) => {
expect(actual).toEqual(jasmine.any(PreviewServerError));
if (status != null) {
expect(actual.status).toBe(status);
}
if (message != null) {
expect(actual.message).toBe(message);
}
};

View File

@ -1,5 +0,0 @@
declare module jasmine {
interface AsyncMatchers {
toBeRejectedWithPreviewServerError(status: number, message?: string | RegExp): Promise<void>;
}
}

View File

@ -1,59 +0,0 @@
import {PreviewServerError} from '../../lib/preview-server/preview-error';
// Matchers
const toBeRejectedWithPreviewServerError: jasmine.CustomAsyncMatcherFactory = () => {
return {
async compare(actualPromise: Promise<never>, expectedStatus: number, expectedMessage?: string | RegExp) {
if (!(actualPromise instanceof Promise)) {
throw new Error(`Expected '${toBeRejectedWithPreviewServerError.name}()' to be called on a promise.`);
}
try {
await actualPromise;
return {
pass: false,
message: `Expected a promise to be rejected with a '${PreviewServerError.name}', but it was resolved.`,
};
} catch (actualError) {
const actualPrintValue = stringify(actualError);
const expectedPrintValue =
stringify(new PreviewServerError(expectedStatus, expectedMessage && `${expectedMessage}`));
const pass = errorMatches(actualError, expectedStatus, expectedMessage);
const message =
`Expected a promise ${pass ? 'not ' : ''}to be rejected with ${expectedPrintValue}, but is was` +
`${pass ? '' : ` rejected with ${actualPrintValue}`}.`;
return {pass, message};
}
},
};
// Helpers
function errorMatches(actualErr: unknown, expectedStatus: number, expectedMsg?: string | RegExp): boolean {
if (!(actualErr instanceof PreviewServerError)) return false;
if (actualErr.status !== expectedStatus) return false;
return messageMatches(actualErr.message, expectedMsg);
}
function messageMatches(actualMsg: string, expectedMsg?: string | RegExp): boolean {
if (typeof expectedMsg === 'undefined') return true;
if (typeof expectedMsg === 'string') return actualMsg === expectedMsg;
return expectedMsg.test(actualMsg);
}
function stringify(value: unknown): string {
if (value instanceof PreviewServerError) {
return `${PreviewServerError.name}(${value.status}${value.message ? `, ${value.message}` : ''})`;
}
return jasmine.pp(value);
}
};
// Exports
export const customAsyncMatchers: jasmine.CustomAsyncMatcherFactories = {
toBeRejectedWithPreviewServerError,
};

View File

@ -9,8 +9,8 @@ describe('PreviewServerError', () => {
it('should extend Error', () => { it('should extend Error', () => {
expect(err).toBeInstanceOf(PreviewServerError); expect(err).toEqual(jasmine.any(PreviewServerError));
expect(err).toBeInstanceOf(Error); expect(err).toEqual(jasmine.any(Error));
expect(Object.getPrototypeOf(err)).toBe(PreviewServerError.prototype); expect(Object.getPrototypeOf(err)).toBe(PreviewServerError.prototype);
}); });

View File

@ -1,4 +1,5 @@
// Imports // Imports
import * as express from 'express';
import * as http from 'http'; import * as http from 'http';
import * as supertest from 'supertest'; import * as supertest from 'supertest';
import {CircleCiApi} from '../../lib/common/circle-ci-api'; import {CircleCiApi} from '../../lib/common/circle-ci-api';
@ -133,7 +134,7 @@ describe('PreviewServerFactory', () => {
const buildCreator = jasmine.any(BuildCreator); const buildCreator = jasmine.any(BuildCreator);
expect(usfCreateMiddlewareSpy).toHaveBeenCalledWith(buildRetriever, buildVerifier, buildCreator, defaultConfig); expect(usfCreateMiddlewareSpy).toHaveBeenCalledWith(buildRetriever, buildVerifier, buildCreator, defaultConfig);
const middleware = usfCreateMiddlewareSpy.calls.mostRecent().returnValue; const middleware: express.Express = usfCreateMiddlewareSpy.calls.mostRecent().returnValue;
expect(httpCreateServerSpy).toHaveBeenCalledWith(middleware); expect(httpCreateServerSpy).toHaveBeenCalledWith(middleware);
}); });
@ -229,7 +230,7 @@ describe('PreviewServerFactory', () => {
expect(prsAddCommentSpy).toHaveBeenCalledTimes(2); expect(prsAddCommentSpy).toHaveBeenCalledTimes(2);
expect(prs).toBe(allCalls[1].object); expect(prs).toBe(allCalls[1].object);
expect(prs).toBeInstanceOf(GithubPullRequests); expect(prs).toEqual(jasmine.any(GithubPullRequests));
expect(prs.repoSlug).toBe('organisation/repo'); expect(prs.repoSlug).toBe('organisation/repo');
}); });
@ -301,8 +302,9 @@ describe('PreviewServerFactory', () => {
let bvGetSignificantFilesChangedSpy: jasmine.Spy; let bvGetSignificantFilesChangedSpy: jasmine.Spy;
beforeEach(() => { beforeEach(() => {
bvGetPrIsTrustedSpy = spyOn(buildVerifier, 'getPrIsTrusted').and.resolveTo(true); bvGetPrIsTrustedSpy = spyOn(buildVerifier, 'getPrIsTrusted').and.returnValue(Promise.resolve(true));
bvGetSignificantFilesChangedSpy = spyOn(buildVerifier, 'getSignificantFilesChanged').and.resolveTo(true); bvGetSignificantFilesChangedSpy = spyOn(buildVerifier, 'getSignificantFilesChanged').
and.returnValue(Promise.resolve(true));
}); });
@ -329,7 +331,7 @@ describe('PreviewServerFactory', () => {
it('should respond appropriately if the PR did not touch any significant files', async () => { it('should respond appropriately if the PR did not touch any significant files', async () => {
bvGetSignificantFilesChangedSpy.and.resolveTo(false); bvGetSignificantFilesChangedSpy.and.returnValue(Promise.resolve(false));
const expectedResponse = {canHavePublicPreview: false, reason: 'No significant files touched.'}; const expectedResponse = {canHavePublicPreview: false, reason: 'No significant files touched.'};
const expectedLog = `PR:${pr} - Cannot have a public preview, because it did not touch any significant files.`; const expectedLog = `PR:${pr} - Cannot have a public preview, because it did not touch any significant files.`;
@ -343,7 +345,7 @@ describe('PreviewServerFactory', () => {
it('should respond appropriately if the PR is not automatically verifiable as "trusted"', async () => { it('should respond appropriately if the PR is not automatically verifiable as "trusted"', async () => {
bvGetPrIsTrustedSpy.and.resolveTo(false); bvGetPrIsTrustedSpy.and.returnValue(Promise.resolve(false));
const expectedResponse = {canHavePublicPreview: false, reason: 'Not automatically verifiable as "trusted".'}; const expectedResponse = {canHavePublicPreview: false, reason: 'Not automatically verifiable as "trusted".'};
const expectedLog = const expectedLog =
@ -370,7 +372,7 @@ describe('PreviewServerFactory', () => {
it('should respond with error if `getSignificantFilesChanged()` fails', async () => { it('should respond with error if `getSignificantFilesChanged()` fails', async () => {
bvGetSignificantFilesChangedSpy.and.rejectWith('getSignificantFilesChanged error'); bvGetSignificantFilesChangedSpy.and.callFake(() => Promise.reject('getSignificantFilesChanged error'));
await agent.get(url).expect(500, 'getSignificantFilesChanged error'); await agent.get(url).expect(500, 'getSignificantFilesChanged error');
expect(loggerErrorSpy).toHaveBeenCalledWith('Previewability check error', 'getSignificantFilesChanged error'); expect(loggerErrorSpy).toHaveBeenCalledWith('Previewability check error', 'getSignificantFilesChanged error');
@ -378,10 +380,11 @@ describe('PreviewServerFactory', () => {
it('should respond with error if `getPrIsTrusted()` fails', async () => { it('should respond with error if `getPrIsTrusted()` fails', async () => {
bvGetPrIsTrustedSpy.and.throwError('getPrIsTrusted error'); const error = new Error('getPrIsTrusted error');
bvGetPrIsTrustedSpy.and.callFake(() => { throw error; });
await agent.get(url).expect(500, 'getPrIsTrusted error'); await agent.get(url).expect(500, 'getPrIsTrusted error');
expect(loggerErrorSpy).toHaveBeenCalledWith('Previewability check error', new Error('getPrIsTrusted error')); expect(loggerErrorSpy).toHaveBeenCalledWith('Previewability check error', error);
}); });
}); });
@ -494,7 +497,7 @@ describe('PreviewServerFactory', () => {
// Note it is important to put the `reject` into `and.callFake`; // Note it is important to put the `reject` into `and.callFake`;
// If you just `and.returnValue` the rejected promise // If you just `and.returnValue` the rejected promise
// then you get an "unhandled rejection" message in the console. // then you get an "unhandled rejection" message in the console.
getGithubInfoSpy.and.rejectWith('Test Error'); getGithubInfoSpy.and.callFake(() => Promise.reject('Test Error'));
await agent.post(URL).send(BASIC_PAYLOAD).expect(500, 'Test Error'); await agent.post(URL).send(BASIC_PAYLOAD).expect(500, 'Test Error');
expect(getGithubInfoSpy).toHaveBeenCalledWith(BUILD_NUM); expect(getGithubInfoSpy).toHaveBeenCalledWith(BUILD_NUM);
expect(downloadBuildArtifactSpy).not.toHaveBeenCalled(); expect(downloadBuildArtifactSpy).not.toHaveBeenCalled();
@ -515,7 +518,7 @@ describe('PreviewServerFactory', () => {
}); });
it('should fail if the artifact fetch request fails', async () => { it('should fail if the artifact fetch request fails', async () => {
downloadBuildArtifactSpy.and.rejectWith('Test Error'); downloadBuildArtifactSpy.and.callFake(() => Promise.reject('Test Error'));
await agent.post(URL).send(BASIC_PAYLOAD).expect(500, 'Test Error'); await agent.post(URL).send(BASIC_PAYLOAD).expect(500, 'Test Error');
expect(getGithubInfoSpy).toHaveBeenCalledWith(BUILD_NUM); expect(getGithubInfoSpy).toHaveBeenCalledWith(BUILD_NUM);
expect(downloadBuildArtifactSpy).toHaveBeenCalled(); expect(downloadBuildArtifactSpy).toHaveBeenCalled();
@ -524,7 +527,7 @@ describe('PreviewServerFactory', () => {
}); });
it('should fail if verifying the PR fails', async () => { it('should fail if verifying the PR fails', async () => {
getPrIsTrustedSpy.and.rejectWith('Test Error'); getPrIsTrustedSpy.and.callFake(() => Promise.reject('Test Error'));
await agent.post(URL).send(BASIC_PAYLOAD).expect(500, 'Test Error'); await agent.post(URL).send(BASIC_PAYLOAD).expect(500, 'Test Error');
expect(getGithubInfoSpy).toHaveBeenCalledWith(BUILD_NUM); expect(getGithubInfoSpy).toHaveBeenCalledWith(BUILD_NUM);
expect(downloadBuildArtifactSpy).toHaveBeenCalled(); expect(downloadBuildArtifactSpy).toHaveBeenCalled();
@ -533,7 +536,7 @@ describe('PreviewServerFactory', () => {
}); });
it('should fail if creating the preview build fails', async () => { it('should fail if creating the preview build fails', async () => {
createBuildSpy.and.rejectWith('Test Error'); createBuildSpy.and.callFake(() => Promise.reject('Test Error'));
await agent.post(URL).send(BASIC_PAYLOAD).expect(500, 'Test Error'); await agent.post(URL).send(BASIC_PAYLOAD).expect(500, 'Test Error');
expect(getGithubInfoSpy).toHaveBeenCalledWith(BUILD_NUM); expect(getGithubInfoSpy).toHaveBeenCalledWith(BUILD_NUM);
expect(downloadBuildArtifactSpy).toHaveBeenCalled(); expect(downloadBuildArtifactSpy).toHaveBeenCalled();
@ -602,7 +605,7 @@ describe('PreviewServerFactory', () => {
it('should propagate errors from BuildVerifier', async () => { it('should propagate errors from BuildVerifier', async () => {
bvGetPrIsTrustedSpy.and.rejectWith('Test'); bvGetPrIsTrustedSpy.and.callFake(() => Promise.reject('Test'));
await createRequest(+pr).expect(500, 'Test'); await createRequest(+pr).expect(500, 'Test');
@ -612,9 +615,7 @@ describe('PreviewServerFactory', () => {
it('should call \'BuildCreator#updatePrVisibility()\' with the correct arguments', async () => { it('should call \'BuildCreator#updatePrVisibility()\' with the correct arguments', async () => {
bvGetPrIsTrustedSpy. bvGetPrIsTrustedSpy.and.callFake((pr2: number) => Promise.resolve(pr2 === 42));
withArgs(24).and.resolveTo(false).
withArgs(42).and.resolveTo(true);
await createRequest(24); await createRequest(24);
expect(bcUpdatePrVisibilitySpy).toHaveBeenCalledWith(24, false); expect(bcUpdatePrVisibilitySpy).toHaveBeenCalledWith(24, false);
@ -625,7 +626,7 @@ describe('PreviewServerFactory', () => {
it('should propagate errors from BuildCreator', async () => { it('should propagate errors from BuildCreator', async () => {
bcUpdatePrVisibilitySpy.and.rejectWith('Test'); bcUpdatePrVisibilitySpy.and.callFake(() => Promise.reject('Test'));
await createRequest(+pr).expect(500, 'Test'); await createRequest(+pr).expect(500, 'Test');
}); });
@ -633,9 +634,7 @@ describe('PreviewServerFactory', () => {
describe('on success', () => { describe('on success', () => {
it('should respond with 200 (action: undefined)', async () => { it('should respond with 200 (action: undefined)', async () => {
bvGetPrIsTrustedSpy. bvGetPrIsTrustedSpy.and.returnValues(Promise.resolve(true), Promise.resolve(false));
withArgs(2).and.resolveTo(false).
withArgs(4).and.resolveTo(true);
const reqs = [4, 2].map(num => createRequest(num).expect(200, http.STATUS_CODES[200])); const reqs = [4, 2].map(num => createRequest(num).expect(200, http.STATUS_CODES[200]));
await Promise.all(reqs); await Promise.all(reqs);
@ -643,9 +642,7 @@ describe('PreviewServerFactory', () => {
it('should respond with 200 (action: labeled)', async () => { it('should respond with 200 (action: labeled)', async () => {
bvGetPrIsTrustedSpy. bvGetPrIsTrustedSpy.and.returnValues(Promise.resolve(true), Promise.resolve(false));
withArgs(2).and.resolveTo(false).
withArgs(4).and.resolveTo(true);
const reqs = [4, 2].map(num => createRequest(num, 'labeled').expect(200, http.STATUS_CODES[200])); const reqs = [4, 2].map(num => createRequest(num, 'labeled').expect(200, http.STATUS_CODES[200]));
await Promise.all(reqs); await Promise.all(reqs);
@ -653,9 +650,7 @@ describe('PreviewServerFactory', () => {
it('should respond with 200 (action: unlabeled)', async () => { it('should respond with 200 (action: unlabeled)', async () => {
bvGetPrIsTrustedSpy. bvGetPrIsTrustedSpy.and.returnValues(Promise.resolve(true), Promise.resolve(false));
withArgs(2).and.resolveTo(false).
withArgs(4).and.resolveTo(true);
const reqs = [4, 2].map(num => createRequest(num, 'unlabeled').expect(200, http.STATUS_CODES[200])); const reqs = [4, 2].map(num => createRequest(num, 'unlabeled').expect(200, http.STATUS_CODES[200]));
await Promise.all(reqs); await Promise.all(reqs);

View File

@ -39,7 +39,7 @@ describe('preview-server/utils', () => {
throwRequestError(505, 'ERROR MESSAGE', request); throwRequestError(505, 'ERROR MESSAGE', request);
} catch (error) { } catch (error) {
caught = true; caught = true;
expect(error).toBeInstanceOf(PreviewServerError); expect(error).toEqual(jasmine.any(PreviewServerError));
expect(error.status).toEqual(505); expect(error.status).toEqual(505);
expect(error.message).toEqual(`ERROR MESSAGE in request: POST some.domain.com/path "The request body"`); expect(error.message).toEqual(`ERROR MESSAGE in request: POST some.domain.com/path "The request body"`);
} }

File diff suppressed because it is too large Load Diff

View File

@ -8,32 +8,10 @@ exitCode=0
# Helpers # Helpers
function checkCert {
local certPath=$1
if [[ ! -f "$certPath" ]]; then
echo "Certificate '$certPath' does not exist. Skipping expiration check..."
return
fi
openssl x509 -checkend 0 -in "$certPath" -noout > /dev/null
reportStatus "Certificate '$certPath'"
if [[ $? -ne 0 ]]; then
echo " [WARN]"
echo " If you did not provide the certificate explicitly, try running the"
echo " 'docker build' command again with the '--no-cache' option to generate"
echo " a new self-signed certificate."
fi
}
function reportStatus { function reportStatus {
local lastExitCode=$? local lastExitCode=$?
echo "$1: $([[ $lastExitCode -eq 0 ]] && echo OK || echo NOT OK)" echo "$1: $([[ $lastExitCode -eq 0 ]] && echo OK || echo NOT OK)"
[[ $lastExitCode -eq 0 ]] || exitCode=1 [[ $lastExitCode -eq 0 ]] || exitCode=1
return $lastExitCode
} }
@ -50,16 +28,6 @@ for s in ${services[@]}; do
done done
# Check SSL/TLS certificates expiration
certs=(
"$AIO_LOCALCERTS_DIR/$AIO_DOMAIN_NAME.crt"
"$TEST_AIO_LOCALCERTS_DIR/$TEST_AIO_DOMAIN_NAME.crt"
)
for c in ${certs[@]}; do
checkCert $c
done
# Check servers # Check servers
origins=( origins=(
http://$AIO_PREVIEW_SERVER_HOSTNAME:$AIO_PREVIEW_SERVER_PORT http://$AIO_PREVIEW_SERVER_HOSTNAME:$AIO_PREVIEW_SERVER_PORT

View File

@ -3,7 +3,7 @@
## Create `aio-builds` persistent disk (if not already exists) ## Create `aio-builds` persistent disk (if not already exists)
- Follow instructions [here](https://cloud.google.com/compute/docs/disks/add-persistent-disk#create_disk). - Follow instructions [here](https://cloud.google.com/compute/docs/disks/add-persistent-disk#create_disk).
- `sudo mkfs.ext4 -m 0 -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/disk/by-id/google-aio-builds` - `sudo mkfs.ext4 -F -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/disk/by-id/google-aio-builds`
## Mount disk ## Mount disk
@ -14,7 +14,7 @@
## Mount disk on boot ## Mount disk on boot
- Run: - Run:
```sh ```
echo UUID=`sudo blkid -s UUID -o value /dev/disk/by-id/google-aio-builds` \ echo UUID=`sudo blkid -s UUID -o value /dev/disk/by-id/google-aio-builds` \
/mnt/disks/aio-builds ext4 defaults,discard,nofail 0 2 | sudo tee -a /etc/fstab /mnt/disks/aio-builds ext4 discard,defaults,nofail 0 2 | sudo tee -a /etc/fstab
``` ```

View File

@ -1,11 +1,10 @@
# VM setup - Create docker image # VM setup - Create docker image
## Install git, Node.js and yarn ## Install node and yarn
- `sudo apt-get update` - Install [nvm](https://github.com/creationix/nvm#installation).
- `sudo apt-get install -y git` - Install node.js: `nvm install 8`
- Install the latest stable version of [Node.js](https://nodejs.org/en/download). - Install yarn: `npm -g install yarn`
- Install the latest stable version of [yarn](https://classic.yarnpkg.com/en/docs/install).
## Checkout repository ## Checkout repository
@ -17,11 +16,7 @@
- You can overwrite the default environment variables inside the image, by passing new values using - You can overwrite the default environment variables inside the image, by passing new values using
`--build-arg`. `--build-arg`.
**Note 1:** The script has to execute docker commands with `sudo`. **Note:** The script has to execute docker commands with `sudo`.
**Note 2:**
The script has to execute `yarn` commands, so make sure `yarn` is on the `PATH` when invoking the
script.
## Example ## Example
@ -31,7 +26,7 @@ The following commands would create a docker image from GitHub repo `foo/bar` to
- `git clone https://github.com/foo/bar.git foobar` - `git clone https://github.com/foo/bar.git foobar`
- Run: - Run:
```sh ```
./foobar/aio-builds-setup/scripts/create-image.sh foobar-builds \ ./foobar/aio-builds-setup/scripts/create-image.sh foobar-builds \
--build-arg AIO_REPO_SLUG=foo/bar \ --build-arg AIO_REPO_SLUG=foo/bar \
--build-arg AIO_DOMAIN_NAME=foobar-builds.io \ --build-arg AIO_DOMAIN_NAME=foobar-builds.io \

View File

@ -3,17 +3,24 @@
## Install docker ## Install docker
Official installation instructions: https://docs.docker.com/engine/install _Debian (jessie):_
Example: - `sudo apt-get update`
- `sudo apt-get install -y apt-transport-https ca-certificates curl git software-properties-common`
- `curl -fsSL https://apt.dockerproject.org/gpg | sudo apt-key add -`
- `apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D`
- `sudo add-apt-repository "deb https://apt.dockerproject.org/repo/ debian-$(lsb_release -cs) main"`
- `sudo apt-get update`
- `sudo apt-get -y install docker-engine`
_Debian (buster):_ _Ubuntu (16.04):_
- `sudo apt-get update` - `sudo apt-get update`
- `sudo apt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common` - `sudo apt-get install -y curl git linux-image-extra-$(uname -r) linux-image-extra-virtual`
- `curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -` - `sudo apt-get install -y apt-transport-https ca-certificates`
- `sudo apt-key fingerprint 0EBFCD88` - `curl -fsSL https://yum.dockerproject.org/gpg | sudo apt-key add -`
- `sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"` - `apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D`
- `sudo add-apt-repository "deb https://apt.dockerproject.org/repo/ ubuntu-$(lsb_release -cs) main"`
- `sudo apt-get update` - `sudo apt-get update`
- `sudo apt-get -y install docker-ce docker-ce-cli containerd.io` - `sudo apt-get -y install docker-engine`
## Start the docker ## Start the docker

View File

@ -8,16 +8,16 @@ VM host to update the preview server based on changes in the source code.
The script will pull the latest changes from the origin's master branch and examine if there have The script will pull the latest changes from the origin's master branch and examine if there have
been any changes in files inside the preview server source code directory (see below). If there are, been any changes in files inside the preview server source code directory (see below). If there are,
it will create a new image and verify that it works as expected. Finally, it will stop and remove it will create a new image and verify that is works as expected. Finally, it will stop and remove
the old docker container and image, create a new container based on the new image and start it. the old docker container and image, create a new container based on the new image and start it.
The script assumes that the preview server source code is in the repository's The script assumes that the preview server source code is in the repository's
`aio/aio-builds-setup/` directory and expects the following inputs: `aio/aio-builds-setup/` directory and expects the following inputs:
- **$1**: `HOST_REPO_DIR` - **$1**: `HOST_REPO_DIR`
- **$2**: `HOST_SECRETS_DIR` - **$2**: `HOST_LOCALCERTS_DIR`
- **$3**: `HOST_BUILDS_DIR` - **$3**: `HOST_SECRETS_DIR`
- **$4**: `HOST_LOCALCERTS_DIR` - **$4**: `HOST_BUILDS_DIR`
- **$5**: `HOST_LOGS_DIR` - **$5**: `HOST_LOGS_DIR`
See [here](vm-setup--create-host-dirs-and-files.md) for more info on what each input directory is See [here](vm-setup--create-host-dirs-and-files.md) for more info on what each input directory is
@ -25,38 +25,28 @@ used for.
**Note 1:** The script has to execute docker commands with `sudo`. **Note 1:** The script has to execute docker commands with `sudo`.
**Note 2:** **Note 2:** Make sure the user that executes the script has access to update the repository
The script has to execute `yarn` commands, so make sure `yarn` is on the `PATH` when invoking the
script.
**Note 3:** Make sure the user that executes the script has access to update the repository.
## Run the script manually ## Run the script manually
You may choose to manually run the script, when necessary. Example: You may choose to manually run the script, when necessary. Example:
```sh ```
update-preview-server.sh \ update-preview-server.sh \
/path/to/repo \ /path/to/repo \
/path/to/localcerts \
/path/to/secrets \ /path/to/secrets \
/path/to/builds \ /path/to/builds \
/path/to/localcerts \
/path/to/logs /path/to/logs
``` ```
## Run the script automatically ## Run the script automatically
You may choose to automatically trigger the script, e.g. using a cronjob. For example, the following You may choose to automatically trigger the script, e.g. using a cronjob. For example, the following
cronjob entry would run the script every 30 minutes, update the preview server (if necessary) and cronjob entry would run the script every hour and update the preview server (assuming the user has
log its output to `update-preview-server.log` (assuming the user has the necessary permissions): the necessary permissions):
``` ```
# Periodically check for changes and update the preview server (if necessary) # Periodically check for changes and update the preview server (if necessary)
*/30 * * * * /path/to/update-preview-server.sh /path/to/repo /path/to/secrets /path/to/builds /path/to/localcerts /path/to/logs >> /path/to/update-preview-server.log 2>&1 */30 * * * * /path/to/update-preview-server.sh /path/to/repo /path/to/localcerts /path/to/secrets /path/to/builds /path/to/logs
``` ```
**Note:**
Keep in mind that cron jobs run in non-interactive, non-login shells. This means that the execution
context might be different compared to when running the same commands from an interactive, login
shell. For example, `.bashrc` files are normally _not_ sourced automatically in cron jobs. See
[here](http://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html) for more info.

View File

@ -7,14 +7,13 @@ echo -e "\n\n[`date`] - Updating the preview server..."
# Input # Input
readonly HOST_REPO_DIR=$1 readonly HOST_REPO_DIR=$1
readonly HOST_SECRETS_DIR=$2 readonly HOST_LOCALCERTS_DIR=$2
readonly HOST_BUILDS_DIR=$3 readonly HOST_SECRETS_DIR=$3
readonly HOST_LOCALCERTS_DIR=$4 readonly HOST_BUILDS_DIR=$4
readonly HOST_LOGS_DIR=$5 readonly HOST_LOGS_DIR=$5
# Constants # Constants
readonly PROVISIONAL_TAG=provisional readonly PROVISIONAL_IMAGE_NAME=aio-builds:provisional
readonly PROVISIONAL_IMAGE_NAME=aio-builds:$PROVISIONAL_TAG
readonly LATEST_IMAGE_NAME=aio-builds:latest readonly LATEST_IMAGE_NAME=aio-builds:latest
readonly CONTAINER_NAME=aio readonly CONTAINER_NAME=aio
@ -31,7 +30,7 @@ readonly CONTAINER_NAME=aio
# Do not update the server unless files inside `aio-builds-setup/` have changed # Do not update the server unless files inside `aio-builds-setup/` have changed
# or the last attempt failed (identified by the provisional image still being around). # or the last attempt failed (identified by the provisional image still being around).
readonly relevantChangedFilesCount=$(git diff --name-only $lastDeployedCommit...HEAD | grep -P "^aio/aio-builds-setup/" | wc -l) readonly relevantChangedFilesCount=$(git diff --name-only $lastDeployedCommit...HEAD | grep -P "^aio/aio-builds-setup/" | wc -l)
readonly lastAttemptFailed=$(sudo docker image ls | grep "$PROVISIONAL_TAG" >> /dev/fd/3 && echo "true" || echo "false") readonly lastAttemptFailed=$(sudo docker rmi "$PROVISIONAL_IMAGE_NAME" >> /dev/fd/3 && echo "true" || echo "false")
if [[ $relevantChangedFilesCount -eq 0 ]] && [[ "$lastAttemptFailed" != "true" ]]; then if [[ $relevantChangedFilesCount -eq 0 ]] && [[ "$lastAttemptFailed" != "true" ]]; then
echo "Skipping update because no relevant files have been touched." echo "Skipping update because no relevant files have been touched."
exit 0 exit 0
@ -61,9 +60,9 @@ readonly CONTAINER_NAME=aio
--publish 80:80 \ --publish 80:80 \
--publish 443:443 \ --publish 443:443 \
--restart unless-stopped \ --restart unless-stopped \
--volume $HOST_LOCALCERTS_DIR:/etc/ssl/localcerts:ro \
--volume $HOST_SECRETS_DIR:/aio-secrets:ro \ --volume $HOST_SECRETS_DIR:/aio-secrets:ro \
--volume $HOST_BUILDS_DIR:/var/www/aio-builds \ --volume $HOST_BUILDS_DIR:/var/www/aio-builds \
--volume $HOST_LOCALCERTS_DIR:/etc/ssl/localcerts:ro \
--volume $HOST_LOGS_DIR:/var/log/aio \ --volume $HOST_LOGS_DIR:/var/log/aio \
"$LATEST_IMAGE_NAME" "$LATEST_IMAGE_NAME"

View File

@ -1,12 +1,8 @@
{ {
"$schema": "./node_modules/@angular/cli/lib/config/schema.json", "$schema": "./node_modules/@angular-devkit/core/src/workspace/workspace-schema.json",
"version": 1, "version": 1,
"cli": { "cli": {
"packageManager": "yarn", "packageManager": "yarn"
"warnings": {
"typescriptMismatch": false
},
"analytics": false
}, },
"newProjectRoot": "projects", "newProjectRoot": "projects",
"projects": { "projects": {
@ -14,13 +10,6 @@
"root": "", "root": "",
"sourceRoot": "src", "sourceRoot": "src",
"projectType": "application", "projectType": "application",
"prefix": "aio",
"schematics": {
"@schematics/angular:component": {
"inlineStyle": true,
"style": "scss"
}
},
"architect": { "architect": {
"build": { "build": {
"builder": "@angular-devkit/build-angular:browser", "builder": "@angular-devkit/build-angular:browser",
@ -28,9 +17,7 @@
"outputPath": "dist", "outputPath": "dist",
"index": "src/index.html", "index": "src/index.html",
"main": "src/main.ts", "main": "src/main.ts",
"polyfills": "src/polyfills.ts", "tsConfig": "src/tsconfig.app.json",
"tsConfig": "tsconfig.app.json",
"webWorkerTsConfig": "tsconfig.worker.json",
"aot": true, "aot": true,
"optimization": true, "optimization": true,
"buildOptimizer": true, "buildOptimizer": true,
@ -41,9 +28,11 @@
"extractLicenses": true, "extractLicenses": true,
"namedChunks": true, "namedChunks": true,
"vendorChunk": false, "vendorChunk": false,
"polyfills": "src/polyfills.ts",
"assets": [ "assets": [
"src/assets", "src/assets",
"src/generated", "src/generated",
"src/app/search/search-worker.js",
"src/pwa-manifest.json", "src/pwa-manifest.json",
"src/google385281288605d160.html", "src/google385281288605d160.html",
{ {
@ -58,15 +47,9 @@
} }
], ],
"styles": [ "styles": [
"src/styles/main.scss" "src/styles.scss"
], ],
"scripts": [], "scripts": []
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
]
}, },
"configurations": { "configurations": {
"fast": { "fast": {
@ -75,8 +58,8 @@
"next": { "next": {
"fileReplacements": [ "fileReplacements": [
{ {
"replace": "src/environments/environment.ts", "src": "src/environments/environment.ts",
"with": "src/environments/environment.next.ts" "replaceWith": "src/environments/environment.next.ts"
} }
], ],
"serviceWorker": true "serviceWorker": true
@ -84,8 +67,8 @@
"stable": { "stable": {
"fileReplacements": [ "fileReplacements": [
{ {
"replace": "src/environments/environment.ts", "src": "src/environments/environment.ts",
"with": "src/environments/environment.stable.ts" "replaceWith": "src/environments/environment.stable.ts"
} }
], ],
"serviceWorker": true "serviceWorker": true
@ -93,14 +76,11 @@
"archive": { "archive": {
"fileReplacements": [ "fileReplacements": [
{ {
"replace": "src/environments/environment.ts", "src": "src/environments/environment.ts",
"with": "src/environments/environment.archive.ts" "replaceWith": "src/environments/environment.archive.ts"
} }
], ],
"serviceWorker": true "serviceWorker": true
},
"ci": {
"progress": false
} }
} }
}, },
@ -121,9 +101,6 @@
}, },
"archive": { "archive": {
"browserTarget": "site:build:archive" "browserTarget": "site:build:archive"
},
"ci": {
"browserTarget": "site:build:ci"
} }
} }
}, },
@ -137,13 +114,17 @@
"builder": "@angular-devkit/build-angular:karma", "builder": "@angular-devkit/build-angular:karma",
"options": { "options": {
"main": "src/test.ts", "main": "src/test.ts",
"karmaConfig": "src/karma.conf.js",
"polyfills": "src/polyfills.ts", "polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json", "tsConfig": "src/tsconfig.spec.json",
"webWorkerTsConfig": "tsconfig.worker.json", "scripts": [],
"karmaConfig": "karma.conf.js", "styles": [
"src/styles.scss"
],
"assets": [ "assets": [
"src/assets", "src/assets",
"src/generated", "src/generated",
"src/app/search/search-worker.js",
"src/pwa-manifest.json", "src/pwa-manifest.json",
"src/google385281288605d160.html", "src/google385281288605d160.html",
{ {
@ -156,41 +137,54 @@
"input": "node_modules/@webcomponents/custom-elements/src", "input": "node_modules/@webcomponents/custom-elements/src",
"output": "/assets/js" "output": "/assets/js"
} }
], ]
"styles": [
"src/styles/main.scss"
],
"scripts": []
} }
}, },
"lint": { "lint": {
"builder": "@angular-devkit/build-angular:tslint", "builder": "@angular-devkit/build-angular:tslint",
"options": { "options": {
"tsConfig": [ "tsConfig": [
"tsconfig.app.json", "src/tsconfig.app.json",
"tsconfig.spec.json", "src/tsconfig.spec.json"
"tsconfig.worker.json",
"tests/e2e/tsconfig.json"
], ],
"exclude": [ "exclude": []
"**/node_modules/**"
]
} }
}, }
}
},
"site-e2e": {
"root": "",
"projectType": "application",
"cli": {},
"schematics": {},
"architect": {
"e2e": { "e2e": {
"builder": "@angular-devkit/build-angular:protractor", "builder": "@angular-devkit/build-angular:protractor",
"options": { "options": {
"protractorConfig": "tests/e2e/protractor.conf.js", "protractorConfig": "tests/e2e/protractor.conf.js",
"devServerTarget": "site:serve" "devServerTarget": "site:serve"
}, }
"configurations": { },
"ci": { "lint": {
"devServerTarget": "site:serve:ci" "builder": "@angular-devkit/build-angular:tslint",
} "options": {
"tsConfig": [
"tests/e2e/tsconfig.e2e.json"
],
"exclude": []
} }
} }
} }
} }
}, },
"defaultProject": "site" "schematics": {
"@schematics/angular:component": {
"inlineStyle": true,
"prefix": "aio",
"styleext": "scss"
},
"@schematics/angular:directive": {
"prefix": "aio"
}
}
} }

View File

@ -1,13 +1,13 @@
# CLI Overview and Command Reference <h1 class="no-toc">CLI Command Reference</h1>
The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications directly from a command shell. The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications. You can use the tool directly in a command shell, or indirectly through an interactive UI such as [Angular Console](https://angularconsole.com).
## Installing Angular CLI ## Installing Angular CLI
Major versions of Angular CLI follow the supported major version of Angular, but minor versions can be released separately. Major versions of Angular CLI follow the supported major version of Angular, but minor versions can be released separately.
Install the CLI using the `npm` package manager: Install the CLI using the `npm` package manager:
<code-example language="bash"> <code-example format="." language="bash">
npm install -g @angular/cli npm install -g @angular/cli
</code-example> </code-example>
@ -20,14 +20,14 @@ Invoke the tool on the command line through the `ng` executable.
Online help is available on the command line. Online help is available on the command line.
Enter the following to list commands or options for a given command (such as [generate](cli/generate)) with a short description. Enter the following to list commands or options for a given command (such as [generate](cli/generate)) with a short description.
<code-example language="bash"> <code-example format="." language="bash">
ng help ng help
ng generate --help ng generate --help
</code-example> </code-example>
To create, build, and serve a new, basic Angular project on a development server, go to the parent directory of your new workspace use the following commands: To create, build, and serve a new, basic Angular project on a development server, go to the parent directory of your new workspace use the following commands:
<code-example language="bash"> <code-example format="." language="bash">
ng new my-first-project ng new my-first-project
cd my-first-project cd my-first-project
ng serve ng serve
@ -36,14 +36,6 @@ ng serve
In your browser, open http://localhost:4200/ to see the new app run. In your browser, open http://localhost:4200/ to see the new app run.
When you use the [ng serve](cli/serve) command to build an app and serve it locally, the server automatically rebuilds the app and reloads the page when you change any of the source files. When you use the [ng serve](cli/serve) command to build an app and serve it locally, the server automatically rebuilds the app and reloads the page when you change any of the source files.
<div class="alert is-helpful">
When you run `ng new my-first-project` a new folder, named `my-first-project`, will be created in the current working directory. Since you want to be able to create files inside that folder, make sure you have sufficient rights in the current working directory before running the command.
If the current working directory is not the right place for your project, you can change to a more appropriate directory by running `cd <path-to-other-directory>` first.
</div>
## Workspaces and project files ## Workspaces and project files
The [ng new](cli/new) command creates an *Angular workspace* folder and generates a new app skeleton. The [ng new](cli/new) command creates an *Angular workspace* folder and generates a new app skeleton.
@ -82,10 +74,7 @@ Command syntax is shown as follows:
* Option names are prefixed with a double dash (--). * Option names are prefixed with a double dash (--).
Option aliases are prefixed with a single dash (-). Option aliases are prefixed with a single dash (-).
Arguments are not prefixed. Arguments are not prefixed.
For example: For example: `ng build my-app -c production`
<code-example language="bash">
ng build my-app -c production
</code-example>
* Typically, the name of a generated artifact can be given as an argument to the command or specified with the --name option. * Typically, the name of a generated artifact can be given as an argument to the command or specified with the --name option.

View File

@ -1,48 +0,0 @@
# Gathering and Viewing Usage Analytics
Users can opt in to share their Angular CLI usage data with [Google Analytics](https://support.google.com/analytics/answer/1008015?hl=en), using the [`ng analytics` CLI command](analytics).
The data is also shared with the Angular team, and used to improve the CLI.
The gathering of CLI analytics data is disabled by default, and must be enabled at the project level by individual users.
It cannot be enabled at the project level for all users.
Data gathered in this way can be viewed on the Google Analytics site, but is not automatically visible on your own organization's Analytics site.
As an administrator for an Angular development group, you can configure your instance of Angular CLI to be able to see analytics data for your own team's usage of the Angular CLI.
This configuration option is separate from and in addition to other usage analytics that your users may be sharing with Google.
## Enable access to CLI usage data
To configure access to your own users' CLI usage data, use the `ng config` command to add a key to your global [`angular.json` workspace configuration file](guide/workspace-config).
The key goes under `cli.analyticsSharing` at the top level of the file, outside the `projects` sections.
The value of the key is your organization's tracking ID, as assigned by Google Analytics.
This ID is a string that looks like `UA-123456-12`.
You can choose to use a descriptive string as the key value, or be assigned a random key when you run the CLI command.
For example, the following command adds a configuration key named "tracking".
<code-example language="sh" class="code-shell">
ng config --global cli.analyticsSharing.tracking UA-123456-12
</code-example>
To turn off this feature, run the following command:
<code-example language="sh" class="code-shell">
ng config --global --remove cli.analyticsSharing
</code-example>
## Per user tracking
You can add a custom user ID to the global configuration, in order to identify unique usage of commands and flags.
If that user enables CLI analytics for their own project, your analytics display tracks and labels their individual usage.
<code-example language="sh" class="code-shell">
ng config --global cli.analyticsSharing.user SOME_USER_NAME
</code-example>
To generate a new random user ID, run the following command:
<code-example language="sh" class="code-shell">
ng config --global cli.analyticsSharing.user ""
</code-example>

View File

@ -18,15 +18,11 @@
**/src/karma.conf.js **/src/karma.conf.js
**/.angular-cli.json **/.angular-cli.json
**/.editorconfig **/.editorconfig
**/.gitignore
**/angular.json **/angular.json
**/tsconfig.json **/tsconfig.json
**/bs-config.e2e.json **/bs-config.e2e.json
**/bs-config.json **/bs-config.json
**/package.json **/package.json
**/tsconfig.json
**/tsconfig.app.json
**/tsconfig.spec.json
**/tslint.json **/tslint.json
**/karma-test-shim.js **/karma-test-shim.js
**/browser-test-shim.js **/browser-test-shim.js
@ -61,9 +57,7 @@ dist/
# aot # aot
**/*.ngsummary.json **/*.ngsummary.json
upgrade-module/tsconfig-aot.json
!rollup-config.js !rollup-config.js
upgrade-module/rollup-config.js
aot-compiler/**/*.d.ts aot-compiler/**/*.d.ts
aot-compiler/**/*.factory.d.ts aot-compiler/**/*.factory.d.ts
upgrade-phonecat-2-hybrid/aot/**/* upgrade-phonecat-2-hybrid/aot/**/*
@ -83,16 +77,12 @@ upgrade-phonecat-2-hybrid/aot/**/*
# styleguide # styleguide
!styleguide/src/systemjs.custom.js !styleguide/src/systemjs.custom.js
# universal
!universal/webpack.server.config.js
# stackblitz # stackblitz
*stackblitz.no-link.html *stackblitz.no-link.html
# ngUpgrade testing # ngUpgrade testing
upgrade-phonecat-1-typescript/tsconfig-aot.json
upgrade-phonecat-1-typescript/rollup-config.js
upgrade-phonecat-3-final/tsconfig-aot.json
upgrade-phonecat-3-final/rollup-config.js
!upgrade-phonecat-*/**/karma.conf.js !upgrade-phonecat-*/**/karma.conf.js
!upgrade-phonecat-*/**/karma-test-shim.js !upgrade-phonecat-*/**/karma-test-shim.js
# schematics
!schematics-for-libraries/projects/my-lib/package.json

View File

@ -1,19 +0,0 @@
import { browser, element, by } from 'protractor';
describe('Accessibility example e2e tests', () => {
beforeEach(() => {
browser.get('');
});
it('should display Accessibility Example', () => {
expect(element(by.css('h1')).getText()).toEqual('Accessibility Example');
});
it('should take a number and change progressbar width', () => {
element(by.css('input')).sendKeys('16');
expect(element(by.css('input')).getAttribute('value')).toEqual('016');
expect(element(by.css('app-example-progressbar div')).getCssValue('width')).toBe('48px');
});
});

View File

@ -1,13 +0,0 @@
<h1>Accessibility Example</h1>
<!-- #docregion template -->
<label>
Enter an example progress value
<input type="number" min="0" max="100"
[value]="progress" (input)="progress = $event.target.value">
</label>
<!-- The user of the progressbar sets an aria-label to communicate what the progress means. -->
<app-example-progressbar [value]="progress" aria-label="Example of a progress bar">
</app-example-progressbar>
<!-- #enddocregion template -->

Some files were not shown because too many files have changed in this diff Show More