content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Java
Java
add support to receive null payload in events
936de607b185c2c9411e5268a6ce4014ad179a79
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> public void invoke(long eventTarget, String name, WritableMap params) { <ide> TAG, <ide> "Dispatching event for target: " + eventTarget); <ide> } <add> if (params == null) { <add> params = new WritableNativeMap(); <add> } <ide> mBinding.dispatchEventToTarget(mJSContext.get(), mEventHandlerPointer, eventTarget, name, (WritableNativeMap) params); <ide> } <ide>
1
PHP
PHP
fix unique validation without ignored column
93abbf579b18b28b70ba18db7468c1dc500b60da
<ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php <ide> public function validateUnique($attribute, $value, $parameters) <ide> if (isset($parameters[2])) { <ide> [$idColumn, $id] = $this->getUniqueIds($parameters); <ide> <del> $id = stripslashes($id); <add> if (! is_null($id)) { <add> $id = stripslashes($id); <add> } <ide> } <ide> <ide> // The presence verifier is responsible for counting rows within this store <ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testValidateUnique() <ide> $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users,email_addr,NULL,id_col,foo,bar']); <ide> $mock = m::mock(PresenceVerifierInterface::class); <ide> $mock->shouldReceive('setConnection')->once()->with(null); <del> $mock->shouldReceive('getCount')->once()->with('users', 'email_addr', 'foo', null, 'id_col', ['foo' => 'bar'])->andReturn(2); <add> $mock->shouldReceive('getCount')->once()->withArgs(function () { <add> return func_get_args() === ['users', 'email_addr', 'foo', null, 'id_col', ['foo' => 'bar']]; <add> })->andReturn(2); <ide> $v->setPresenceVerifier($mock); <ide> $this->assertFalse($v->passes()); <ide> }
2
Text
Text
fix lint errors for readme
680cb9954389c108d111e438997d1b039a277997
<ide><path>README.md <ide> To specify how the actions transform the state tree, you write pure *reducers*. <ide> That’s it! <ide> <ide> ```js <del>import { createStore } from 'redux'; <add>import { createStore } from 'redux' <ide> <ide> /** <ide> * This is a reducer, a pure function with (state, action) => state signature. <ide> import { createStore } from 'redux'; <ide> function counter(state = 0, action) { <ide> switch (action.type) { <ide> case 'INCREMENT': <del> return state + 1; <add> return state + 1 <ide> case 'DECREMENT': <del> return state - 1; <add> return state - 1 <ide> default: <del> return state; <add> return state <ide> } <ide> } <ide> <ide> // Create a Redux store holding the state of your app. <ide> // Its API is { subscribe, dispatch, getState }. <del>let store = createStore(counter); <add>let store = createStore(counter) <ide> <ide> // You can subscribe to the updates manually, or use bindings to your view layer. <ide> store.subscribe(() => <ide> console.log(store.getState()) <del>); <add>) <ide> <ide> // The only way to mutate the internal state is to dispatch an action. <ide> // The actions can be serialized, logged or stored and later replayed. <del>store.dispatch({ type: 'INCREMENT' }); <add>store.dispatch({ type: 'INCREMENT' }) <ide> // 1 <del>store.dispatch({ type: 'INCREMENT' }); <add>store.dispatch({ type: 'INCREMENT' }) <ide> // 2 <del>store.dispatch({ type: 'DECREMENT' }); <add>store.dispatch({ type: 'DECREMENT' }) <ide> // 1 <ide> ``` <ide>
1
Java
Java
implement file resolution for isreadable() as well
bda3d81bc9cda4ec8da79da3c45c6b2a5b6713bd
<ide><path>org.springframework.core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java <ide> public boolean exists() { <ide> } <ide> } <ide> <add> @Override <add> public boolean isReadable() { <add> try { <add> URL url = getURL(); <add> if (ResourceUtils.isFileURL(url)) { <add> // Proceed with file system resolution... <add> File file = getFile(); <add> return (file.canRead() && !file.isDirectory()); <add> } <add> else { <add> return true; <add> } <add> } <add> catch (IOException ex) { <add> return false; <add> } <add> } <add> <ide> @Override <ide> public int contentLength() throws IOException { <ide> URL url = getURL();
1
Text
Text
update docker stack experimental notes
3225150b164c97e5e67893e93f45888d552f4919
<ide><path>experimental/docker-stacks-and-bundles.md <ide> Wrote bundle to vossibility-stack.dab <ide> A stack is created using the `docker deploy` command: <ide> <ide> ```bash <del># docker deploy --help <del> <add>$ docker deploy --help <ide> Usage: docker deploy [OPTIONS] STACK <ide> <del>Create and update a stack from a Distributed Application Bundle (DAB) <add>Deploy a new stack or update an existing stack <add> <add>Aliases: <add> deploy, up <ide> <ide> Options: <del> --file string Path to a Distributed Application Bundle file (Default: STACK.dab) <del> --help Print usage <del> --with-registry-auth Send registry authentication details to Swarm agents <add> --bundle-file string Path to a Distributed Application Bundle file <add> -c, --compose-file string Path to a Compose file <add> --help Print usage <add> --with-registry-auth Send registry authentication details to Swarm agents <add> <ide> ``` <ide> <ide> Let's deploy the stack created before: <ide> <ide> ```bash <del># docker deploy vossibility-stack <add>$ docker deploy --bundle-file vossibility-stack.dab vossibility-stack <ide> Loading bundle from vossibility-stack.dab <ide> Creating service vossibility-stack_elasticsearch <ide> Creating service vossibility-stack_kibana <ide> Options: <ide> --help Print usage <ide> <ide> Commands: <del> config Print the stack configuration <del> deploy Create and update a stack <add> deploy Deploy a new stack or update an existing stack <ide> ls List stacks <add> ps List the tasks in the stack <ide> rm Remove the stack <ide> services List the services in the stack <del> tasks List the tasks in the stack <ide> <ide> Run 'docker stack COMMAND --help' for more information on a command. <ide> ``` <ide> are persisted as files, the file extension is `.dab` (Docker 1.12RC2 tools use <ide> `.dsb` for the file extension—this will be updated in the next release client). <ide> <ide> A bundle has two top-level fields: `version` and `services`. The version used <del>by Docker 1.12 tools is `0.1`. <add>by Docker 1.12 and later tools is `0.1`. <ide> <ide> `services` in the bundle are the services that comprise the app. They <ide> correspond to the new `Service` object introduced in the 1.12 Docker Engine API.
1
Python
Python
add missing word to warning message
e3e6c41843c6c0842d55304b0fc9d88cf1408893
<ide><path>numpy/lib/function_base.py <ide> def _check_interpolation_as_method(method, interpolation, fname): <ide> f"the `interpolation=` argument to {fname} was renamed to " <ide> "`method=`, which has additional options.\n" <ide> "Users of the modes 'nearest', 'lower', 'higher', or " <del> "'midpoint' are encouraged to review the method they. " <add> "'midpoint' are encouraged to review the method they used. " <ide> "(Deprecated NumPy 1.22)", <ide> DeprecationWarning, stacklevel=4) <ide> if method != "linear":
1
Javascript
Javascript
move changes into js directory rather than jsm
66b7db927b6947c629c3cf9b266824a8474c5898
<ide><path>examples/js/loaders/SVGLoader.js <ide> THREE.SVGLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype <ide> var numbers = parseFloats( data ); <ide> <ide> for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) { <add> <add> // skip command if start point == end point <add> if( numbers[ j + 5 ] == point.x && numbers[ j + 6 ] == point.y ) continue; <ide> <ide> var start = point.clone(); <ide> point.x = numbers[ j + 5 ]; <ide> THREE.SVGLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype <ide> <ide> for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) { <ide> <add> // skip command if no displacement <add> if( numbers[ j + 5 ] == 0 && numbers[ j + 6 ] == 0 ) continue; <add> <ide> var start = point.clone(); <ide> point.x += numbers[ j + 5 ]; <ide> point.y += numbers[ j + 6 ]; <ide> THREE.SVGLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype <ide> <ide> function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) { <ide> <add> if( rx == 0 || ry == 0 ) { <add> // draw a line if either of the radii == 0 <add> path.lineTo( end.x, end.y ); <add> return; <add> } <add> <ide> x_axis_rotation = x_axis_rotation * Math.PI / 180; <ide> <ide> // Ensure radii are positive
1
PHP
PHP
trim trailing whitespace
805d52de8e5b31f488fe1f1503f24045b553cbcc
<ide><path>src/Http/ResponseEmitter.php <ide> * <ide> * - It logs headers sent using CakePHP's logging tools. <ide> * - Cookies are emitted using setcookie() to not conflict with ext/session <del> * - For fastcgi servers with PHP-FPM session_write_close() is called just <del> * before fastcgi_finish_request() to make sure session data is saved <add> * - For fastcgi servers with PHP-FPM session_write_close() is called just <add> * before fastcgi_finish_request() to make sure session data is saved <ide> * correctly (especially on slower session backends). <ide> */ <ide> class ResponseEmitter implements EmitterInterface <ide> public function emit(ResponseInterface $response, $maxBufferLength = 8192) <ide> } <ide> <ide> if (function_exists('fastcgi_finish_request')) { <del> session_write_close(); <add> session_write_close(); <ide> fastcgi_finish_request(); <ide> } <ide> }
1
Text
Text
change links to use head in top level docs
7a4c2c8d86031b986e8a514d5c64b42d8a6b1806
<ide><path>BUILDING.md <ide> packages: <ide> <ide> To install Node.js prerequisites using <ide> [Boxstarter WebLauncher](https://boxstarter.org/WebLauncher), open <del><https://boxstarter.org/package/nr/url?https://raw.githubusercontent.com/nodejs/node/master/tools/bootstrap/windows_boxstarter> <add><https://boxstarter.org/package/nr/url?https://raw.githubusercontent.com/nodejs/node/HEAD/tools/bootstrap/windows_boxstarter> <ide> with Internet Explorer or Edge browser on the target machine. <ide> <ide> Alternatively, you can use PowerShell. Run those commands from an elevated <ide> PowerShell terminal: <ide> Set-ExecutionPolicy Unrestricted -Force <ide> iex ((New-Object System.Net.WebClient).DownloadString('https://boxstarter.org/bootstrapper.ps1')) <ide> get-boxstarter -Force <del>Install-BoxstarterPackage https://raw.githubusercontent.com/nodejs/node/master/tools/bootstrap/windows_boxstarter -DisableReboots <add>Install-BoxstarterPackage https://raw.githubusercontent.com/nodejs/node/HEAD/tools/bootstrap/windows_boxstarter -DisableReboots <ide> ``` <ide> <ide> The entire installation using Boxstarter will take up approximately 10 GB of <ide><path>CODE_OF_CONDUCT.md <ide> # Code of Conduct <ide> <del>* [Node.js Code of Conduct](https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md) <del>* [Node.js Moderation Policy](https://github.com/nodejs/admin/blob/master/Moderation-Policy.md) <add>* [Node.js Code of Conduct](https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md) <add>* [Node.js Moderation Policy](https://github.com/nodejs/admin/blob/HEAD/Moderation-Policy.md) <ide><path>CONTRIBUTING.md <ide> ## [Code of Conduct](./doc/guides/contributing/code-of-conduct.md) <ide> <ide> The Node.js project has a <del>[Code of Conduct](https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md) <add>[Code of Conduct](https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md) <ide> to which all contributors must adhere. <ide> <ide> See [details on our policy on Code of Conduct](./doc/guides/contributing/code-of-conduct.md). <ide><path>onboarding.md <ide> The project has two venues for real-time discussion: <ide> organization (not just Collaborators on Node.js core) have access. Its <ide> contents should not be shared externally. <ide> * You can find the full moderation policy <del> [here](https://github.com/nodejs/admin/blob/master/Moderation-Policy.md). <add> [here](https://github.com/nodejs/admin/blob/HEAD/Moderation-Policy.md). <ide> <ide> ## Reviewing PRs <ide> <ide> needs to be pointed out separately during the onboarding. <ide> including accommodations, transportation, visa fees, etc. if needed. Check out <ide> the [summit](https://github.com/nodejs/summit) repository for details. <ide> <del>[Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md <add>[Code of Conduct]: https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md <ide> [Landing Pull Requests]: doc/guides/collaborator-guide.md#landing-pull-requests <ide> [Publicizing or hiding organization membership]: https://help.github.com/articles/publicizing-or-hiding-organization-membership/ <ide> [`author-ready`]: doc/guides/collaborator-guide.md#author-ready-pull-requests <ide> [`core-validate-commit`]: https://github.com/nodejs/core-validate-commit <del>[`git-node`]: https://github.com/nodejs/node-core-utils/blob/master/docs/git-node.md <add>[`git-node`]: https://github.com/nodejs/node-core-utils/blob/HEAD/docs/git-node.md <ide> [`node-core-utils`]: https://github.com/nodejs/node-core-utils <ide> [set up the credentials]: https://github.com/nodejs/node-core-utils#setting-up-credentials <ide> [two-factor authentication]: https://help.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/
4
Text
Text
add proper stetho debugging setup documentation
c5bd033e4b7fe0299792b52893809320354acd9b
<ide><path>docs/Debugging.md <ide> Alternatively, select "Dev Settings" from the Developer Menu, then update the "D <ide> <ide> ### Debugging with [Stetho](http://facebook.github.io/stetho/) on Android <ide> <del>1. In ```android/app/build.gradle```, add these lines in the `dependencies` section: <add>Follow this guide to enable Stetho for Debug mode: <add> <add>1. In `android/app/build.gradle`, add these lines in the `dependencies` section: <ide> <ide> ```gradle <del> compile 'com.facebook.stetho:stetho:1.3.1' <del> compile 'com.facebook.stetho:stetho-okhttp3:1.3.1' <add> debugCompile 'com.facebook.stetho:stetho:1.5.0' <add> debugCompile 'com.facebook.stetho:stetho-okhttp3:1.5.0' <ide> ``` <ide> <del>2. In ```android/app/src/main/java/com/{yourAppName}/MainApplication.java```, add the following imports: <del> <del> ```java <del> import com.facebook.react.modules.network.ReactCookieJarContainer; <del> import com.facebook.stetho.Stetho; <del> import okhttp3.OkHttpClient; <del> import com.facebook.react.modules.network.OkHttpClientProvider; <del> import com.facebook.stetho.okhttp3.StethoInterceptor; <del> import java.util.concurrent.TimeUnit; <del> ``` <add>> The above will configure Stetho v1.5.0. You can check at http://facebook.github.io/stetho/ if a newer version is available. <add> <add>2. Create the following Java classes to wrap the Stetho call, one for release and one for debug: <add> <add> ```java <add> // android/app/src/release/java/com/{yourAppName}/StethoWrapper.java <add> <add> public class StethoWrapper { <add> <add> public static void initialize(Context context) { <add> // NO_OP <add> } <add> <add> public static void addInterceptor() { <add> // NO_OP <add> } <add> } <add> ``` <add> <add> ```java <add> // android/app/src/debug/java/com/{yourAppName}/StethoWrapper.java <add> <add> public class StethoWrapper { <add> public static void initialize(Context context) { <add> Stetho.initializeWithDefaults(context); <add> } <add> <add> public static void addInterceptor() { <add> OkHttpClient client = OkHttpClientProvider.getOkHttpClient() <add> .newBuilder() <add> .addNetworkInterceptor(new StethoInterceptor()) <add> .build(); <add> <add> OkHttpClientProvider.replaceOkHttpClient(client); <add> } <add> } <add> ``` <add> <add>3. Open `android/app/src/main/java/com/{yourAppName}/MainApplication.java` and replace the original `onCreate` function: <add> <add>```java <add> public void onCreate() { <add> super.onCreate(); <add> <add> if (BuildConfig.DEBUG) { <add> StethoWrapper.initialize(this); <add> StethoWrapper.addInterceptor(); <add> } <add> <add> SoLoader.init(this, /* native exopackage */ false); <add> } <add>``` <ide> <del>3. In ```android/app/src/main/java/com/{yourAppName}/MainApplication.java``` add the function: <del> ```java <del> public void onCreate() { <del> super.onCreate(); <del> Stetho.initializeWithDefaults(this); <del> OkHttpClient client = new OkHttpClient.Builder() <del> .connectTimeout(0, TimeUnit.MILLISECONDS) <del> .readTimeout(0, TimeUnit.MILLISECONDS) <del> .writeTimeout(0, TimeUnit.MILLISECONDS) <del> .cookieJar(new ReactCookieJarContainer()) <del> .addNetworkInterceptor(new StethoInterceptor()) <del> .build(); <del> OkHttpClientProvider.replaceOkHttpClient(client); <del> } <del> ``` <add>4. Open the project in Android Studio and resolve any dependency issues. The IDE should guide you through this steps after hovering your pointer over the red lines. <ide> <del>4. Run ```react-native run-android ``` <add>5. Run `react-native run-android`. <ide> <del>5. In a new Chrome tab, open: ```chrome://inspect```, then click on 'Inspect device' (the one followed by "Powered by Stetho"). <add>6. In a new Chrome tab, open: `chrome://inspect`, then click on the 'Inspect device' item next to "Powered by Stetho". <ide> <ide> ## Debugging native code <ide>
1
Javascript
Javascript
remove rogue terminal.log()
48b86022fbf0895242bf3c16f3c8b043fc48d6bc
<ide><path>packager/react-packager/src/lib/TerminalReporter.js <ide> class TerminalReporter { <ide> case 'global_cache_disabled': <ide> this._logCacheDisabled(event.reason); <ide> break; <add> case 'transform_cache_reset': <add> reporting.logWarning(terminal, 'the transform cache was reset.'); <add> break; <ide> } <ide> } <ide> <ide><path>packager/react-packager/src/lib/TransformCache.js <ide> const CACHE_NAME = 'react-native-packager-cache'; <ide> type CacheFilePaths = {transformedCode: string, metadata: string}; <ide> import type {Options as TransformOptions} from '../JSTransformer/worker/worker'; <ide> import type {SourceMap} from './SourceMap'; <add>import type {Reporter} from './reporting'; <ide> <ide> /** <ide> * If packager is running for two different directories, we don't want the <ide> function writeSync(props: { <ide> ])); <ide> } <ide> <del>export type CacheOptions = {resetCache?: boolean}; <add>export type CacheOptions = { <add> reporter: Reporter, <add> resetCache?: boolean, <add>}; <ide> <ide> /* 1 day */ <ide> const GARBAGE_COLLECTION_PERIOD = 24 * 60 * 60 * 1000; <ide> const GARBAGE_COLLECTOR = new (class GarbageCollector { <ide> this._lastCollected = Date.now(); <ide> } <ide> <del> _resetCache() { <add> _resetCache(reporter: Reporter) { <ide> rimraf.sync(getCacheDirPath()); <del> terminal.log('Warning: The transform cache was reset.'); <add> reporter.update({type: 'transform_cache_reset'}); <ide> this._cacheWasReset = true; <ide> this._lastCollected = Date.now(); <ide> } <ide> <ide> collectIfNecessarySync(options: CacheOptions) { <ide> if (options.resetCache && !this._cacheWasReset) { <del> this._resetCache(); <add> this._resetCache(options.reporter); <ide> return; <ide> } <ide> const lastCollected = this._lastCollected; <ide><path>packager/react-packager/src/lib/reporting.js <ide> export type ReportableEvent = { <ide> } | { <ide> type: 'global_cache_disabled', <ide> reason: GlobalCacheDisabledReason, <add>} | { <add> type: 'transform_cache_reset', <ide> }; <ide> <ide> /** <ide><path>packager/react-packager/src/node-haste/Module.js <ide> class Module { <ide> sourceCode, <ide> transformCacheKey, <ide> transformOptions, <del> cacheOptions: this._options, <add> cacheOptions: { <add> resetCache: this._options.resetCache, <add> reporter: this._reporter, <add> }, <ide> }; <ide> const cachedResult = TransformCache.readSync(cacheProps); <ide> if (cachedResult) {
4
Ruby
Ruby
fix a state leak in `autosave_association_test`
dedb946bfb940ece65064175f09ed55815768ec6
<ide><path>activerecord/test/cases/autosave_association_test.rb <ide> def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it <ide> end <ide> <ide> def test_should_not_ignore_different_error_messages_on_the_same_attribute <add> old_validators = Ship._validators.deep_dup <add> old_callbacks = Ship._validate_callbacks.deep_dup <ide> Ship.validates_format_of :name, :with => /\w/ <ide> @pirate.ship.name = "" <ide> @pirate.catchphrase = nil <ide> assert @pirate.invalid? <ide> assert_equal ["can't be blank", "is invalid"], @pirate.errors[:"ship.name"] <add> ensure <add> Ship._validators = old_validators if old_validators <add> Ship._validate_callbacks = old_callbacks if old_callbacks <ide> end <ide> <ide> def test_should_still_allow_to_bypass_validations_on_the_associated_model
1
Python
Python
fix docstrings in preprocessing/text.py
9f4734cbf1044cb5eb921f8e834423c3f528d0d4
<ide><path>keras/preprocessing/text.py <ide> def base_filter(): <ide> <ide> <ide> def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "): <del> """prune: sequence of characters to filter out <add> """Converts a text to a sequence of word indices. <add> <add> # Arguments <add> text: Input text (string). <add> filters: Sequence of characters to filter out. <add> lower: Whether to convert the input to lowercase. <add> split: Sentence split marker (string). <add> <add> # Returns <add> A list of integer word indices. <ide> """ <ide> if lower: <ide> text = text.lower() <ide> def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "): <ide> <ide> <ide> def one_hot(text, n, filters=base_filter(), lower=True, split=" "): <del> seq = text_to_word_sequence(text, filters=filters, lower=lower, split=split) <add> seq = text_to_word_sequence(text, <add> filters=filters, <add> lower=lower, <add> split=split) <ide> return [(abs(hash(w)) % (n - 1) + 1) for w in seq] <ide> <ide> <ide> class Tokenizer(object): <add> """Text tokenization utility class. <add> <add> This class allows to vectorize a text corpus, by turning each <add> text into either a sequence of integers (each integer being the index <add> of a token in a dictionary) or into a vector where the coefficient <add> for each token could be binary, based on word count, based on tf-idf... <add> <add> # Arguments <add> nb_words: the maximum number of words to keep, based <add> on word frequency. Only the most common `nb_words` words will <add> be kept. <add> filters: a string where each element is a character that will be <add> filtered from the texts. The default is all punctuation, plus <add> tabs and line breaks, minus the `'` character. <add> lower: boolean. Whether to convert the texts to lowercase. <add> split: character or string to use for token splitting. <add> char_level: if True, every character will be treated as a word. <add> <add> By default, all punctuation is removed, turning the texts into <add> space-separated sequences of words <add> (words maybe include the `'` character). These sequences are then <add> split into lists of tokens. They will then be indexed or vectorized. <add> <add> `0` is a reserved index that won't be assigned to any word. <add> """ <ide> <ide> def __init__(self, nb_words=None, filters=base_filter(), <ide> lower=True, split=' ', char_level=False): <del> """The class allows to vectorize a text corpus, by turning each <del> text into either a sequence of integers (each integer being the index <del> of a token in a dictionary) or into a vector where the coefficient <del> for each token could be binary, based on word count, based on tf-idf... <del> <del> # Arguments <del> nb_words: the maximum number of words to keep, based <del> on word frequency. Only the most common `nb_words` words will <del> be kept. <del> filters: a string where each element is a character that will be <del> filtered from the texts. The default is all punctuation, plus <del> tabs and line breaks, minus the `'` character. <del> lower: boolean. Whether to convert the texts to lowercase. <del> split: character or string to use for token splitting. <del> char_level: if True, every character will be treated as a word. <del> <del> By default, all punctuation is removed, turning the texts into <del> space-separated sequences of words <del> (words maybe include the `'` character). These sequences are then <del> split into lists of tokens. They will then be indexed or vectorized. <del> <del> `0` is a reserved index that won't be assigned to any word. <del> """ <ide> self.word_counts = {} <ide> self.word_docs = {} <ide> self.filters = filters <ide> def __init__(self, nb_words=None, filters=base_filter(), <ide> self.char_level = char_level <ide> <ide> def fit_on_texts(self, texts): <del> """Required before using texts_to_sequences or texts_to_matrix <add> """Updates internal vocabulary based on a list of texts. <add> <add> Required before using `texts_to_sequences` or `texts_to_matrix`. <ide> <ide> # Arguments <ide> texts: can be a list of strings, <ide> def fit_on_texts(self, texts): <ide> self.document_count = 0 <ide> for text in texts: <ide> self.document_count += 1 <del> seq = text if self.char_level else text_to_word_sequence(text, self.filters, self.lower, self.split) <add> seq = text if self.char_level else text_to_word_sequence(text, <add> self.filters, <add> self.lower, <add> self.split) <ide> for w in seq: <ide> if w in self.word_counts: <ide> self.word_counts[w] += 1 <ide> def fit_on_texts(self, texts): <ide> self.index_docs[self.word_index[w]] = c <ide> <ide> def fit_on_sequences(self, sequences): <del> """Required before using sequences_to_matrix <del> (if fit_on_texts was never called) <add> """Updates internal vocabulary based on a list of sequences. <add> <add> Required before using `sequences_to_matrix` <add> (if `fit_on_texts` was never called). <add> <add> # Arguments <add> sequences: A list of sequence. <add> A "sequence" is a list of integer word indices. <ide> """ <ide> self.document_count = len(sequences) <ide> self.index_docs = {} <ide> def fit_on_sequences(self, sequences): <ide> <ide> def texts_to_sequences(self, texts): <ide> """Transforms each text in texts in a sequence of integers. <add> <ide> Only top "nb_words" most frequent words will be taken into account. <ide> Only words known by the tokenizer will be taken into account. <ide> <del> Returns a list of sequences. <add> # Arguments <add> texts: A list of texts (strings). <add> <add> # Returns <add> A list of sequences. <ide> """ <ide> res = [] <ide> for vect in self.texts_to_sequences_generator(texts): <ide> def texts_to_sequences_generator(self, texts): <ide> Only top "nb_words" most frequent words will be taken into account. <ide> Only words known by the tokenizer will be taken into account. <ide> <del> Yields individual sequences. <add> # Arguments <add> texts: A list of texts (strings). <ide> <del> # Arguments: <del> texts: list of strings. <add> # Yields <add> Yields individual sequences. <ide> """ <ide> nb_words = self.nb_words <ide> for text in texts: <del> seq = text if self.char_level else text_to_word_sequence(text, self.filters, self.lower, self.split) <add> seq = text if self.char_level else text_to_word_sequence(text, <add> self.filters, <add> self.lower, <add> self.split) <ide> vect = [] <ide> for w in seq: <ide> i = self.word_index.get(w) <ide> def texts_to_matrix(self, texts, mode='binary'): <ide> """Convert a list of texts to a Numpy matrix, <ide> according to some vectorization mode. <ide> <del> # Arguments: <add> # Arguments <ide> texts: list of strings. <del> modes: one of "binary", "count", "tfidf", "freq" <add> modes: one of "binary", "count", "tfidf", "freq". <add> <add> # Returns <add> A Numpy matrix. <ide> """ <ide> sequences = self.texts_to_sequences(texts) <ide> return self.sequences_to_matrix(sequences, mode=mode) <ide> def sequences_to_matrix(self, sequences, mode='binary'): <ide> """Converts a list of sequences into a Numpy matrix, <ide> according to some vectorization mode. <ide> <del> # Arguments: <add> # Arguments <ide> sequences: list of sequences <ide> (a sequence is a list of integer word indices). <ide> modes: one of "binary", "count", "tfidf", "freq" <add> <add> # Returns <add> A Numpy matrix. <ide> """ <ide> if not self.nb_words: <ide> if self.word_index: <ide> def sequences_to_matrix(self, sequences, mode='binary'): <ide> X[i][j] = 1 <ide> elif mode == 'tfidf': <ide> # Use weighting scheme 2 in <del> # https://en.wikipedia.org/wiki/Tf%E2%80%93idf <add> # https://en.wikipedia.org/wiki/Tf%E2%80%93idf <ide> tf = 1 + np.log(c) <ide> idf = np.log(1 + self.document_count / (1 + self.index_docs.get(j, 0))) <ide> X[i][j] = tf * idf
1
Go
Go
fix empty reference
795ecf02ce25007932cdc0b676f08f32fcb8509d
<ide><path>builder/builder-next/exporter/export.go <ide> func (e *imageExporter) Resolve(ctx context.Context, opt map[string]string) (exp <ide> for k, v := range opt { <ide> switch k { <ide> case keyImageName: <del> i.targetName = v <add> for _, v := range strings.Split(v, ",") { <add> ref, err := distref.ParseNormalizedNamed(v) <add> if err != nil { <add> return nil, err <add> } <add> i.targetNames = append(i.targetNames, ref) <add> } <ide> case keyBuildInfo: <ide> if v == "" { <ide> i.buildInfo = true <ide> func (e *imageExporter) Resolve(ctx context.Context, opt map[string]string) (exp <ide> <ide> type imageExporterInstance struct { <ide> *imageExporter <del> targetName string <add> targetNames []distref.Named <ide> meta map[string][]byte <ide> buildInfo bool <ide> buildInfoAttrs bool <ide> func (e *imageExporterInstance) Export(ctx context.Context, inp exporter.Source, <ide> _ = configDone(nil) <ide> <ide> if e.opt.ReferenceStore != nil { <del> targetNames := strings.Split(e.targetName, ",") <del> for _, targetName := range targetNames { <del> tagDone := oneOffProgress(ctx, "naming to "+targetName) <del> tref, err := distref.ParseNormalizedNamed(targetName) <del> if err != nil { <del> return nil, err <del> } <del> if err := e.opt.ReferenceStore.AddTag(tref, digest.Digest(id), true); err != nil { <add> for _, targetName := range e.targetNames { <add> tagDone := oneOffProgress(ctx, "naming to "+targetName.String()) <add> if err := e.opt.ReferenceStore.AddTag(targetName, digest.Digest(id), true); err != nil { <ide> return nil, tagDone(err) <ide> } <ide> _ = tagDone(nil)
1
Javascript
Javascript
remove appetize embedded examples
3153c3baa00a8e7e3b0299c9476af3f8eccd162e
<ide><path>website/layout/AutodocsLayout.js <ide> var TypeDef = React.createClass({ <ide> }, <ide> }); <ide> <del>var EmbeddedSimulator = React.createClass({ <del> render: function() { <del> if (!this.props.shouldRender) { <del> return null; <del> } <del> <del> var metadata = this.props.metadata; <del> <del> var imagePreview = metadata.platform === 'android' <del> ? <img alt="Run example in simulator" width="170" height="338" src="img/uiexplorer_main_android.png" /> <del> : <img alt="Run example in simulator" width="170" height="356" src="img/uiexplorer_main_ios.png" />; <del> <del> return ( <del> <div className="embedded-simulator"> <del> <p><a className="modal-button-open"><strong>Run this example</strong></a></p> <del> <div className="modal-button-open modal-button-open-img"> <del> {imagePreview} <del> </div> <del> <Modal metadata={metadata} /> <del> </div> <del> ); <del> } <del>}); <del> <del>var Modal = React.createClass({ <del> render: function() { <del> var metadata = this.props.metadata; <del> var appParams = {route: metadata.title}; <del> var encodedParams = encodeURIComponent(JSON.stringify(appParams)); <del> var url = metadata.platform === 'android' <del> ? `https://appetize.io/embed/q7wkvt42v6bkr0pzt1n0gmbwfr?device=nexus5&scale=65&autoplay=false&orientation=portrait&deviceColor=white&params=${encodedParams}` <del> : `https://appetize.io/embed/7vdfm9h3e6vuf4gfdm7r5rgc48?device=iphone6s&scale=60&autoplay=false&orientation=portrait&deviceColor=white&params=${encodedParams}`; <del> <del> return ( <del> <div> <del> <div className="modal"> <del> <div className="modal-content"> <del> <button className="modal-button-close">&times;</button> <del> <div className="center"> <del> <iframe className="simulator" src={url} width="256" height="550" frameborder="0" scrolling="no" /> <del> <p>Powered by <a target="_blank" href="https://appetize.io">appetize.io</a></p> <del> </div> <del> </div> <del> </div> <del> <div className="modal-backdrop" /> <del> </div> <del> ); <del> } <del>}); <del> <ide> var Autodocs = React.createClass({ <ide> childContextTypes: { <ide> permalink: PropTypes.string, <ide> var Autodocs = React.createClass({ <ide> <Prism> <ide> {example.content.replace(/^[\s\S]*?\*\//, '').trim()} <ide> </Prism> <del> <EmbeddedSimulator shouldRender={metadata.runnable} metadata={metadata} /> <ide> </div> <ide> </div> <ide> );
1
Javascript
Javascript
extract sc.touchlist into its own file
ce52f618113242a8464e38eac94c984ddac1c72c
<ide><path>packages/sproutcore-touch/lib/system/gesture.js <ide> var set = SC.set; <ide> <ide> var sigFigs = 100; <ide> <del>SC.TouchList = SC.Object.extend({ <del> touches: null, <del> <del> timestamp: null, <del> <del> init: function() { <del> this._super(); <del> <del> set(this, 'touches', []); <del> }, <del> <del> addTouch: function(touch) { <del> var touches = get(this, 'touches'); <del> touches.push(touch); <del> this.notifyPropertyChange('touches'); <del> }, <del> <del> updateTouch: function(touch) { <del> var touches = get(this, 'touches'); <del> <del> for (var i=0, l=touches.length; i<l; i++) { <del> var _t = touches[i]; <del> <del> if (_t.identifier === touch.identifier) { <del> touches[i] = touch; <del> this.notifyPropertyChange('touches'); <del> break; <del> } <del> } <del> }, <del> <del> removeTouch: function(touch) { <del> var touches = get(this, 'touches'); <del> <del> for (var i=0, l=touches.length; i<l; i++) { <del> var _t = touches[i]; <del> <del> if (_t.identifier === touch.identifier) { <del> touches.splice(i,1); <del> this.notifyPropertyChange('touches'); <del> break; <del> } <del> } <del> }, <del> <del> removeAllTouches: function() { <del> set(this, 'touches', []); <del> }, <del> <del> touchWithId: function(id) { <del> var ret = null, <del> touches = get(this, 'touches'); <del> <del> for (var i=0, l=touches.length; i<l; i++) { <del> var _t = touches[i]; <del> <del> if (_t.identifier === id) { <del> ret = _t; <del> break; <del> } <del> } <del> <del> return ret; <del> }, <del> <del> length: function() { <del> var touches = get(this, 'touches'); <del> return touches.length; <del> }.property('touches').cacheable() <del>}); <del> <ide> /** <ide> @class <ide> <ide><path>packages/sproutcore-touch/lib/system/touch_list.js <add>// ========================================================================== <add>// Project: SproutCore Touch <add>// Copyright: ©2011 Strobe Inc. and contributors. <add>// License: Licensed under MIT license (see license.js) <add>// ========================================================================== <add> <add>var get = SC.get; <add>var set = SC.set; <add> <add>/** <add> @class <add> @private <add> <add> Used to manage and maintain a list of active touches related to a gesture <add> recognizer. <add>*/ <add>SC.TouchList = SC.Object.extend({ <add> touches: null, <add> <add> timestamp: null, <add> <add> init: function() { <add> this._super(); <add> <add> set(this, 'touches', []); <add> }, <add> <add> addTouch: function(touch) { <add> var touches = get(this, 'touches'); <add> touches.push(touch); <add> this.notifyPropertyChange('touches'); <add> }, <add> <add> updateTouch: function(touch) { <add> var touches = get(this, 'touches'); <add> <add> for (var i=0, l=touches.length; i<l; i++) { <add> var _t = touches[i]; <add> <add> if (_t.identifier === touch.identifier) { <add> touches[i] = touch; <add> this.notifyPropertyChange('touches'); <add> break; <add> } <add> } <add> }, <add> <add> removeTouch: function(touch) { <add> var touches = get(this, 'touches'); <add> <add> for (var i=0, l=touches.length; i<l; i++) { <add> var _t = touches[i]; <add> <add> if (_t.identifier === touch.identifier) { <add> touches.splice(i,1); <add> this.notifyPropertyChange('touches'); <add> break; <add> } <add> } <add> }, <add> <add> removeAllTouches: function() { <add> set(this, 'touches', []); <add> }, <add> <add> touchWithId: function(id) { <add> var ret = null, <add> touches = get(this, 'touches'); <add> <add> for (var i=0, l=touches.length; i<l; i++) { <add> var _t = touches[i]; <add> <add> if (_t.identifier === id) { <add> ret = _t; <add> break; <add> } <add> } <add> <add> return ret; <add> }, <add> <add> length: function() { <add> var touches = get(this, 'touches'); <add> return touches.length; <add> }.property('touches').cacheable() <add>});
2
Javascript
Javascript
remove unused functions
b7b7b29f509c46e6d5854b1cd04c0ec757de6389
<ide><path>lib/dns.js <ide> function errnoException(errorno, syscall) { <ide> } <ide> <ide> <del>function familyToSym(family) { <del> switch (family) { <del> case 4: return cares.AF_INET; <del> case 6: return cares.AF_INET6; <del> default: return cares.AF_UNSPEC; <del> } <del>} <del> <del> <del>function symToFamily(family) { <del> switch (family) { <del> case cares.AF_INET: return 4; <del> case cares.AF_INET6: return 6; <del> default: return undefined; <del> } <del>} <del> <ide> // c-ares invokes a callback either synchronously or asynchronously, <ide> // but the dns API should always invoke a callback asynchronously. <ide> //
1
Javascript
Javascript
add key to inspected-element error boundary
ebcec3cc20417528ffe80f0b11701af42b399939
<ide><path>packages/react-devtools-shared/src/devtools/views/Components/InspectedElementErrorBoundary.js <ide> */ <ide> <ide> import * as React from 'react'; <add>import {useContext} from 'react'; <ide> import ErrorBoundary from '../ErrorBoundary'; <add>import {TreeStateContext} from './TreeContext'; <ide> import styles from './InspectedElementErrorBoundary.css'; <ide> <ide> type WrapperProps = {| <ide> type WrapperProps = {| <ide> export default function InspectedElementErrorBoundaryWrapper({ <ide> children, <ide> }: WrapperProps) { <add> // Key on the selected element ID so that changing the selected element automatically hides the boundary. <add> // This seems best since an error inspecting one element isn't likely to be relevant to another element. <add> const {selectedElementID} = useContext(TreeStateContext); <ide> return ( <ide> <div className={styles.Wrapper}> <del> <ErrorBoundary canDismiss={true}>{children}</ErrorBoundary> <add> <ErrorBoundary key={selectedElementID} canDismiss={true}> <add> {children} <add> </ErrorBoundary> <ide> </div> <ide> ); <ide> }
1
PHP
PHP
add tests related to
8b2f80b83f3e2c8dd8099f30dbd0729310edac9d
<ide><path>tests/TestCase/I18n/TimeTest.php <ide> public function tearDown() <ide> Time::setTestNow($this->now); <ide> Time::setDefaultLocale($this->locale); <ide> Time::resetToStringFormat(); <add> Time::setJsonEncodeFormat("yyyy-MM-dd'T'HH:mm:ssxxx"); <ide> <ide> FrozenTime::setTestNow($this->frozenNow); <ide> FrozenTime::setDefaultLocale($this->locale); <ide> FrozenTime::resetToStringFormat(); <add> FrozenTime::setJsonEncodeFormat("yyyy-MM-dd'T'HH:mm:ssxxx"); <add> <ide> date_default_timezone_set('UTC'); <ide> I18n::locale(I18n::DEFAULT_LOCALE); <ide> } <ide> public function testJsonEncode($class) <ide> $this->assertEquals('1397988610', json_encode($time)); <ide> } <ide> <add> /** <add> * Test jsonSerialize no side-effects <add> * <add> * @dataProvider classNameProvider <add> * @return void <add> */ <add> public function testJsonEncodeSideEffectFree($class) <add> { <add> if (version_compare(INTL_ICU_VERSION, '50.0', '<')) { <add> $this->markTestSkipped('ICU 5x is needed'); <add> } <add> $date = new \Cake\I18n\FrozenTime('2016-11-29 09:00:00'); <add> $this->assertInstanceOf('DateTimeZone', $date->timezone); <add> <add> $result = json_encode($date); <add> $this->assertEquals('"2016-11-29T09:00:00+00:00"', $result); <add> $this->assertInstanceOf('DateTimeZone', $date->getTimezone()); <add> } <add> <ide> /** <ide> * Tests debugInfo <ide> *
1
Java
Java
fix compilation warnings
d37f29e420003c8e040669e76f99e1f9c2de4876
<ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableFromSource.java <ide> public CompletableFromSource(CompletableSource source) { <ide> extends AtomicBoolean <ide> implements CompletableObserver, Disposable { <ide> <add> /** */ <add> private static final long serialVersionUID = -1520879094105684863L; <ide> private final CompletableObserver o; <ide> private Disposable d; <ide> <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableFromSource.java <ide> protected void subscribeActual(Observer<? super T> observer) { <ide> extends AtomicBoolean <ide> implements Observer<T>, Disposable { <ide> <add> /** */ <add> private static final long serialVersionUID = -7920748056724379224L; <ide> private final Observer<? super T> o; <ide> private Disposable d; <ide> <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleFromSource.java <ide> public SingleFromSource(SingleSource<T> source) { <ide> static final class DisposeAwareSingleObserver<T> <ide> extends AtomicBoolean <ide> implements SingleObserver<T>, Disposable { <add> /** */ <add> private static final long serialVersionUID = -166991076349162358L; <ide> private final SingleObserver<? super T> o; <ide> private Disposable d; <ide> <ide><path>src/test/java/io/reactivex/subscribers/SafeSubscriberWithPluginTest.java <ide> <ide> package io.reactivex.subscribers; <ide> <del>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.*; <ide> <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> public void onComplete() { <ide> SafeSubscriber<Integer> safe = new SafeSubscriber<Integer>(ts); <ide> try { <ide> safe.onComplete(); <del> Assert.fail(); <add> fail(); <ide> } catch (RuntimeException e) { <ide> // FIXME no longer assertable <ide> // assertTrue(safe.isUnsubscribed());
4
Python
Python
restore correct ordering for latestcommentsfeed
cc72e64e19f57954f86e866d245aff9c52bde642
<ide><path>django/contrib/comments/feeds.py <ide> def items(self): <ide> where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)'] <ide> params = [settings.COMMENTS_BANNED_USERS_GROUP] <ide> qs = qs.extra(where=where, params=params) <del> return qs[:40] <add> return qs.order_by('-submit_date')[:40] <ide> <ide> def item_pubdate(self, item): <del> return item.submit_date <ide>\ No newline at end of file <add> return item.submit_date
1
Ruby
Ruby
remove useless method
f6fecabc0cb8ad7be3783d31656a0b10fe3b5bc7
<ide><path>actionview/lib/action_view/lookup_context.rb <ide> def self.clear <ide> @details_keys.clear <ide> end <ide> <del> def self.empty?; @details_keys.empty?; end <del> <ide> def self.digest_caches <ide> @details_keys.values.map(&:digest_cache) <ide> end
1
PHP
PHP
prevent null in fixture files
0c4613fdd217a48faebe23085839d01b8c47cd0a
<ide><path>lib/Cake/Model/CakeSchema.php <ide> protected function _values($values) { <ide> $vals[] = "'{$key}' => array('" . implode("', '", $val) . "')"; <ide> } elseif (!is_numeric($key)) { <ide> $val = var_export($val, true); <add> if ($val === 'NULL') { <add> $val = 'null'; <add> } <ide> $vals[] = "'{$key}' => {$val}"; <ide> } <ide> }
1
Javascript
Javascript
fix spelling mistakes
c11015ff4f610ac2924d1fc6d569a17657a404fd
<ide><path>packages/eslint-plugin-react-hooks/src/RulesOfHooks.js <ide> export default { <ide> // hook functions. <ide> const codePathFunctionName = getFunctionName(codePathNode); <ide> <del> // This is a valid code path for React hooks if we are direcly in a React <add> // This is a valid code path for React hooks if we are directly in a React <ide> // function component or we are in a hook function. <ide> const isSomewhereInsideComponentOrHook = isInsideComponentOrHook( <ide> codePathNode, <ide> export default { <ide> // false positives due to feature flag checks. We're less <ide> // sensitive to them in classes because hooks would produce <ide> // runtime errors in classes anyway, and because a use*() <del> // call in a class, if it works, is unambigously *not* a hook. <add> // call in a class, if it works, is unambiguously *not* a hook. <ide> } else if (codePathFunctionName) { <ide> // Custom message if we found an invalid function name. <ide> const message = <ide> export default { <ide> }; <ide> <ide> /** <del> * Gets tbe static name of a function AST node. For function declarations it is <add> * Gets the static name of a function AST node. For function declarations it is <ide> * easy. For anonymous function expressions it is much harder. If you search for <ide> * `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places <ide> * where JS gives anonymous function expressions names. We roughly detect the <ide><path>packages/react-reconciler/src/ReactChildFiber.js <ide> function ChildReconciler(shouldTrackSideEffects) { <ide> newChildren: Array<*>, <ide> expirationTime: ExpirationTime, <ide> ): Fiber | null { <del> // This algorithm can't optimize by searching from boths ends since we <add> // This algorithm can't optimize by searching from both ends since we <ide> // don't have backpointers on fibers. I'm trying to see how far we can get <ide> // with that model. If it ends up not being worth the tradeoffs, we can <ide> // add it later. <ide><path>packages/react-reconciler/src/ReactFiberHooks.js <ide> function updateMemo<T>( <ide> let shouldWarnForUnbatchedSetState = false; <ide> <ide> if (__DEV__) { <del> // jest isnt' a 'global', it's just exposed to tests via a wrapped function <add> // jest isn't a 'global', it's just exposed to tests via a wrapped function <ide> // further, this isn't a test file, so flow doesn't recognize the symbol. So... <ide> // $FlowExpectedError - because requirements don't give a damn about your type sigs. <ide> if ('undefined' !== typeof jest) { <ide><path>packages/react-reconciler/src/ReactFiberScheduler.js <ide> function renderRoot(root: FiberRoot, isYieldy: boolean): void { <ide> return; <ide> } else if ( <ide> // There's no lower priority work, but we're rendering asynchronously. <del> // Synchronsouly attempt to render the same level one more time. This is <add> // Synchronously attempt to render the same level one more time. This is <ide> // similar to a suspend, but without a timeout because we're not waiting <ide> // for a promise to resolve. <ide> !root.didError && <ide><path>packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js <ide> describe('ReactHooks', () => { <ide> ]); <ide> expect(root).toMatchRenderedOutput('0 (light)'); <ide> <del> // Updating the theme to the same value does't cause the consumers <add> // Updating the theme to the same value doesn't cause the consumers <ide> // to re-render. <ide> setTheme('light'); <ide> expect(root).toFlushAndYield([]); <ide><path>packages/react-reconciler/src/forks/ReactFiberErrorDialog.www.js <ide> import invariant from 'shared/invariant'; <ide> const ReactFiberErrorDialogWWW = require('ReactFiberErrorDialog'); <ide> invariant( <ide> typeof ReactFiberErrorDialogWWW.showErrorDialog === 'function', <del> 'Expected ReactFiberErrorDialog.showErrorDialog to existbe a function.', <add> 'Expected ReactFiberErrorDialog.showErrorDialog to be a function.', <ide> ); <ide> <ide> export function showErrorDialog(capturedError: CapturedError): boolean { <ide><path>packages/scheduler/src/__tests__/SchedulerDOM-test.js <ide> describe('SchedulerDOM', () => { <ide> expect(callbackLog).toEqual(['A', 'B']); <ide> }); <ide> <del> it("accepts callbacks betweeen animationFrame and postMessage and doesn't stall", () => { <add> it("accepts callbacks between animationFrame and postMessage and doesn't stall", () => { <ide> const {unstable_scheduleCallback: scheduleCallback} = Scheduler; <ide> const callbackLog = []; <ide> const callbackA = jest.fn(() => callbackLog.push('A')); <ide><path>packages/shared/invokeGuardedCallbackImpl.js <ide> if (__DEV__) { <ide> // invokeGuardedCallback uses a try-catch, all user exceptions are treated <ide> // like caught exceptions, and the DevTools won't pause unless the developer <ide> // takes the extra step of enabling pause on caught exceptions. This is <del> // untintuitive, though, because even though React has caught the error, from <add> // unintuitive, though, because even though React has caught the error, from <ide> // the developer's perspective, the error is uncaught. <ide> // <ide> // To preserve the expected "Pause on exceptions" behavior, we don't use a
8
Javascript
Javascript
create hostcontainer component type
f04c38ed656a513fe5515e54d7645883767a177e
<ide><path>src/renderers/noop/ReactNoop.js <ide> var NoopRenderer = ReactFiberReconciler({ <ide> <ide> }); <ide> <add>var root = null; <add> <ide> var ReactNoop = { <ide> <ide> render(element : ReactElement<any>) { <del> <del> NoopRenderer.mountNewRoot(element); <del> <add> if (!root) { <add> root = NoopRenderer.mountContainer(element, null); <add> } else { <add> NoopRenderer.updateContainer(element, root); <add> } <ide> }, <ide> <ide> flushHighPri() { <ide><path>src/renderers/shared/fiber/ReactChildFiber.js <ide> function createFirstChild(parent, existingChild, newChildren) { <ide> } <ide> } <ide> <add>// TODO: This API won't work because we'll need to transfer the side-effects of <add>// unmounting children to the parent. <ide> exports.reconcileChildFibers = function(parent : Fiber, currentFirstChild : ?Fiber, newChildren : ReactNodeList) : ?Fiber { <ide> return createFirstChild(parent, currentFirstChild, newChildren); <ide> }; <ide><path>src/renderers/shared/fiber/ReactFiber.js <ide> var ReactTypeOfWork = require('ReactTypeOfWork'); <ide> var { <ide> IndeterminateComponent, <ide> ClassComponent, <add> HostContainer, <ide> HostComponent, <ide> CoroutineComponent, <ide> YieldComponent, <ide> exports.cloneFiber = function(fiber : Fiber) : Fiber { <ide> return alt; <ide> }; <ide> <add>exports.createHostContainerFiber = function(containerInfo : ?Object) { <add> const fiber = createFiber(HostContainer, null); <add> fiber.stateNode = containerInfo; <add> return fiber; <add>}; <add> <ide> exports.createFiberFromElement = function(element : ReactElement) { <ide> const fiber = exports.createFiberFromElementType(element.type, element.key); <ide> fiber.pendingProps = element.props; <ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js <ide> var { <ide> IndeterminateComponent, <ide> FunctionalComponent, <ide> ClassComponent, <add> HostContainer, <ide> HostComponent, <ide> CoroutineComponent, <ide> CoroutineHandlerPhase, <ide> function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { <ide> case ClassComponent: <ide> console.log('class component', workInProgress.pendingProps.type.name); <ide> return workInProgress.child; <add> case HostContainer: <add> reconcileChildren(current, workInProgress, workInProgress.pendingProps); <add> // A yield component is just a placeholder, we can just run through the <add> // next one immediately. <add> if (workInProgress.child) { <add> return beginWork( <add> workInProgress.child.alternate, <add> workInProgress.child <add> ); <add> } <add> return null; <ide> case HostComponent: <ide> updateHostComponent(current, workInProgress); <ide> return workInProgress.child; <ide><path>src/renderers/shared/fiber/ReactFiberCompleteWork.js <ide> var { <ide> IndeterminateComponent, <ide> FunctionalComponent, <ide> ClassComponent, <add> HostContainer, <ide> HostComponent, <ide> CoroutineComponent, <ide> CoroutineHandlerPhase, <ide> exports.completeWork = function(current : ?Fiber, workInProgress : Fiber) : ?Fib <ide> console.log('/class component', workInProgress.type.name); <ide> transferOutput(workInProgress.child, workInProgress); <ide> return null; <add> case HostContainer: <add> return null; <ide> case HostComponent: <ide> console.log('/host component', workInProgress.type); <ide> return null; <ide><path>src/renderers/shared/fiber/ReactFiberReconciler.js <ide> 'use strict'; <ide> <ide> import type { Fiber } from 'ReactFiber'; <add>import type { PriorityLevel } from 'ReactPriorityLevel'; <add> <ide> var ReactFiber = require('ReactFiber'); <ide> var { beginWork } = require('ReactFiberBeginWork'); <ide> var { completeWork } = require('ReactFiberCompleteWork'); <ide> <add>var { <add> NoWork, <add> HighPriority, <add> LowPriority, <add> OffscreenPriority, <add>} = require('ReactPriorityLevel'); <add> <ide> type ReactHostElement<T, P> = { <ide> type: T, <ide> props: P <ide> export type HostConfig<T, P, I> = { <ide> <ide> }; <ide> <del>type OpaqueID = {}; <add>type OpaqueNode = Fiber; <ide> <ide> export type Reconciler = { <del> mountNewRoot(element : ReactElement<any>) : OpaqueID; <add> mountContainer(element : ReactElement<any>, containerInfo : ?Object) : OpaqueNode, <add> updateContainer(element : ReactElement<any>, container : OpaqueNode) : void, <add> unmountContainer(container : OpaqueNode) : void, <add> <add> // Used to extract the return value from the initial render. Legacy API. <add> getPublicRootInstance(container : OpaqueNode) : ?Object, <ide> }; <ide> <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> <ide> let nextUnitOfWork : ?Fiber = null; <ide> <add> let currentRootsWithPendingWork : ?Fiber = null; <add> <add> function findNextUnitOfWork(priorityLevel : PriorityLevel) : ?Fiber { <add> let current = currentRootsWithPendingWork; <add> while (current) { <add> if (current.pendingWorkPriority !== 0 && <add> current.pendingWorkPriority <= priorityLevel) { <add> // This node has work to do that fits our priority level criteria. <add> if (current.pendingProps !== null) { <add> // We found some work to do. We need to return the "work in progress" <add> // of this node which will be the alternate. <add> return current.alternate; <add> } <add> // If we have a child let's see if any of our children has work to do. <add> // Only bother doing this at all if the current priority level matches <add> // because it is the highest priority for the whole subtree. <add> if (current.child) { <add> current = current.child; <add> continue; <add> } <add> // If we match the priority but has no child and no work to do, <add> // then we can safely reset the flag. <add> current.pendingWorkPriority = NoWork; <add> } <add> while (!current.sibling) { <add> // TODO: Stop using parent here. See below. <add> // $FlowFixMe: This downcast is not safe. It is intentionally an error. <add> current = current.parent; <add> if (!current) { <add> return null; <add> } <add> if (current.pendingWorkPriority <= priorityLevel) { <add> // If this subtree had work left to do, we would have returned it by <add> // now. This could happen if a child with pending work gets cleaned up <add> // but we don't clear the flag then. It is safe to reset it now. <add> current.pendingWorkPriority = NoWork; <add> } <add> } <add> current = current.sibling; <add> } <add> return null; <add> } <add> <ide> function completeUnitOfWork(workInProgress : Fiber) : ?Fiber { <ide> while (true) { <ide> // The current, flushed, state of this fiber is the alternate. <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> workInProgress = workInProgress.parent; <ide> } else { <ide> // If we're at the root, there's no more work to do. <add> currentRootsWithPendingWork = null; <ide> return null; <ide> } <ide> } <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> } <ide> <ide> function performLowPriWork(deadline : Deadline) { <add> if (!nextUnitOfWork) { <add> // Find the highest possible priority work to do. <add> // This loop is unrolled just to satisfy Flow's enum constraint. <add> // We could make arbitrary many idle priority levels but having <add> // too many just means flushing changes too often. <add> nextUnitOfWork = findNextUnitOfWork(HighPriority); <add> if (!nextUnitOfWork) { <add> nextUnitOfWork = findNextUnitOfWork(LowPriority); <add> if (!nextUnitOfWork) { <add> nextUnitOfWork = findNextUnitOfWork(OffscreenPriority); <add> } <add> } <add> } <ide> while (nextUnitOfWork) { <ide> if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { <ide> nextUnitOfWork = performUnitOfWork(nextUnitOfWork); <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> } <ide> } <ide> <del> function ensureLowPriIsScheduled() { <del> if (nextUnitOfWork) { <del> return; <add> function scheduleLowPriWork(root : Fiber) { <add> // We must reset the current unit of work pointer so that we restart the <add> // search from the root during the next tick. <add> nextUnitOfWork = null; <add> <add> if (currentRootsWithPendingWork) { <add> if (root === currentRootsWithPendingWork) { <add> // We're already scheduled. <add> return; <add> } <add> // We already have some work pending in another root. Add this to the <add> // linked list. <add> let previousSibling = currentRootsWithPendingWork; <add> while (previousSibling.sibling) { <add> previousSibling = previousSibling.sibling; <add> if (root === previousSibling) { <add> // We're already scheduled. <add> return; <add> } <add> } <add> previousSibling.sibling = root; <add> } else { <add> // We're the first and only root with new changes. <add> currentRootsWithPendingWork = root; <add> root.sibling = null; <add> // Ensure we will get another callback to process the work. <add> scheduleLowPriCallback(performLowPriWork); <ide> } <del> scheduleLowPriCallback(performLowPriWork); <ide> } <ide> <ide> /* <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> } <ide> */ <ide> <del> let rootFiber : ?Fiber = null; <del> <ide> return { <ide> <del> mountNewRoot(element : ReactElement<any>) : OpaqueID { <add> mountContainer(element : ReactElement<any>, containerInfo : ?Object) : OpaqueNode { <add> const container = ReactFiber.createHostContainerFiber(containerInfo); <add> container.alternate = container; <add> container.pendingProps = element; <add> container.pendingWorkPriority = LowPriority; <ide> <del> ensureLowPriIsScheduled(); <add> scheduleLowPriWork(container); <ide> <del> // TODO: Unify this with ReactChildFiber. We can't now because the parent <del> // is passed. Should be doable though. Might require a wrapper don't know. <del> if (rootFiber && rootFiber.type === element.type && rootFiber.key === element.key) { <del> nextUnitOfWork = ReactFiber.cloneFiber(rootFiber); <del> nextUnitOfWork.pendingProps = element.props; <del> return {}; <del> } <add> return container; <add> }, <ide> <del> nextUnitOfWork = rootFiber = ReactFiber.createFiberFromElement(element); <add> updateContainer(element : ReactElement<any>, container : OpaqueNode) : void { <add> container.pendingProps = element; <add> container.pendingWorkPriority = LowPriority; <ide> <del> return {}; <add> scheduleLowPriWork(container); <add> }, <add> <add> unmountContainer(container : OpaqueNode) : void { <add> container.pendingProps = null; <add> container.pendingWorkPriority = LowPriority; <add> <add> scheduleLowPriWork(container); <add> }, <add> <add> getPublicRootInstance(container : OpaqueNode) : ?Object { <add> return null; <ide> }, <ide> <ide> }; <add> <ide> }; <ide><path>src/renderers/shared/fiber/ReactTypeOfWork.js <ide> <ide> 'use strict'; <ide> <del>export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6; <add>export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7; <ide> <ide> module.exports = { <ide> IndeterminateComponent: 0, // Before we know whether it is functional or class <ide> FunctionalComponent: 1, <ide> ClassComponent: 2, <del> HostComponent: 3, <del> CoroutineComponent: 4, <del> CoroutineHandlerPhase: 5, <del> YieldComponent: 6, <add> HostContainer: 3, // Root of a host tree. Could be nested inside another node. <add> HostComponent: 4, <add> CoroutineComponent: 5, <add> CoroutineHandlerPhase: 6, <add> YieldComponent: 7, <ide> };
7
Text
Text
fix the url in comparison of "copy" and "run curl"
3dd134cecaa045e73706c6ce4ab55188e98d1066
<ide><path>docs/articles/dockerfile_best-practices.md <ide> things like: <ide> And instead, do something like: <ide> <ide> RUN mkdir -p /usr/src/things \ <del> && curl -SL http://example.com/big.tar.gz \ <add> && curl -SL http://example.com/big.tar.xz \ <ide> | tar -xJC /usr/src/things \ <ide> && make -C /usr/src/things all <ide>
1
Ruby
Ruby
fix flaky foreign key test
c1122879744fea71b356af78ba70bdd87153c214
<ide><path>activerecord/test/cases/migration/foreign_key_test.rb <ide> def test_schema_dumping_with_defferable_initially_immediate <ide> end <ide> end <ide> <del> unless in_memory_db? <del> def test_does_not_create_foreign_keys_when_bypassed_by_config <del> connection = ActiveRecord::Base.establish_connection( <del> { <del> adapter: "sqlite3", <del> database: "test/db/test.sqlite3", <del> foreign_keys: false, <del> } <del> ).connection <del> <del> connection.create_table "rockets", force: true do |t| <del> t.string :name <del> end <del> connection.create_table "astronauts", force: true do |t| <del> t.string :name <del> t.references :rocket <del> end <del> <del> connection.add_foreign_key :astronauts, :rockets <add> def test_does_not_create_foreign_keys_when_bypassed_by_config <add> require "active_record/connection_adapters/sqlite3_adapter" <add> connection = ActiveRecord::Base.sqlite3_connection( <add> adapter: "sqlite3", <add> database: ":memory:", <add> foreign_keys: false, <add> ) <add> <add> connection.create_table "rockets", force: true do |t| <add> t.string :name <add> end <add> connection.create_table "astronauts", force: true do |t| <add> t.string :name <add> t.references :rocket <add> end <ide> <del> foreign_keys = connection.foreign_keys("astronauts") <del> assert_equal 0, foreign_keys.size <del> ensure <del> connection.drop_table "astronauts", if_exists: true rescue nil <del> connection.drop_table "rockets", if_exists: true rescue nil <add> connection.add_foreign_key :astronauts, :rockets <ide> <del> ActiveRecord::Base.establish_connection(:arunit) <del> end <add> foreign_keys = connection.foreign_keys("astronauts") <add> assert_equal 0, foreign_keys.size <ide> end <ide> <ide> def test_schema_dumping
1
Ruby
Ruby
remove more warnings on ap
523f98099d331908db6ab4c45f7657e61a8a4d5f
<ide><path>actionpack/lib/action_dispatch/middleware/session/abstract_store.rb <ide> def loaded? <ide> <ide> def destroy <ide> clear <del> @by.send(:destroy, @env) if @by <del> @env[ENV_SESSION_OPTIONS_KEY][:id] = nil if @env && @env[ENV_SESSION_OPTIONS_KEY] <add> @by.send(:destroy, @env) if defined?(@by) && @by <add> @env[ENV_SESSION_OPTIONS_KEY][:id] = nil if defined?(@env) && @env && @env[ENV_SESSION_OPTIONS_KEY] <ide> @loaded = false <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/testing/assertions/selector.rb <ide> def css_select(*args) <ide> arg = args.shift <ide> elsif arg == nil <ide> raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?" <del> elsif @selected <add> elsif defined?(@selected) && @selected <ide> matches = [] <ide> <ide> @selected.each do |selected| <ide> def assert_select_rjs(*args, &block) <ide> assert_block("") { true } # to count the assertion <ide> if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type) <ide> begin <add> @selected ||= nil <ide> in_scope, @selected = @selected, matches <ide> yield matches <ide> ensure <ide><path>actionpack/test/controller/filters_test.rb <ide> def test_conditional_skipping_of_filters <ide> assert_equal %w( ensure_login find_user ), assigns["ran_filter"] <ide> <ide> test_process(ConditionalSkippingController, "login") <del> assert_nil @controller.instance_variable_get("@ran_after_filter") <add> assert !@controller.instance_variable_defined?("@ran_after_filter") <ide> test_process(ConditionalSkippingController, "change_password") <ide> assert_equal %w( clean_up ), @controller.instance_variable_get("@ran_after_filter") <ide> end
3
Text
Text
add note about hoc possibly adding gip to _app
467b65a889cc8d40d38910bdfdb28c756086a926
<ide><path>errors/opt-out-auto-static-optimization.md <ide> This causes **all non-getStaticProps pages** to be executed on the server -- dis <ide> Be sure you meant to use `getInitialProps` in `pages/_app`! <ide> There are some valid use cases for this, but it is often better to handle `getInitialProps` on a _per-page_ basis. <ide> <add>Check for any [higher-order components](https://reactjs.org/docs/higher-order-components.html) that may have added `getInitialProps` to your [Custom `<App>`](https://nextjs.org/docs#custom-app). <add> <ide> If you previously copied the [Custom `<App>`](https://nextjs.org/docs#custom-app) example, you may be able to remove your `getInitialProps`. <ide> <ide> The following `getInitialProps` does nothing and may be removed:
1
Ruby
Ruby
nullify the relation at a more general level
aae4f357b5dae389b91129258f9d6d3043e7631e
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def sum(*args) <ide> # association, it will be used for the query. Otherwise, construct options and pass them with <ide> # scope to the target class's +count+. <ide> def count(column_name = nil, count_options = {}) <del> return 0 if owner.new_record? <del> <ide> column_name, count_options = nil, column_name if column_name.is_a?(Hash) <ide> <ide> if options[:counter_sql] || options[:finder_sql] <ide> def add_to_target(record) <ide> record <ide> end <ide> <add> def scope(opts = {}) <add> scope = super() <add> scope.none! if opts.fetch(:nullify, true) && null_scope? <add> scope <add> end <add> <add> def null_scope? <add> owner.new_record? && !foreign_key_present? <add> end <add> <ide> private <ide> <ide> def custom_counter_sql <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb <ide> class CollectionProxy < Relation <ide> def initialize(association) #:nodoc: <ide> @association = association <ide> super association.klass, association.klass.arel_table <del> merge! association.scope <add> merge! association.scope(nullify: false) <ide> end <ide> <ide> def target <ide> def scoping <ide> # Returns a <tt>Relation</tt> object for the records in this association <ide> def scope <ide> association = @association <del> scope = @association.scope <del> scope.none! if @association.owner.new_record? <del> scope.extending! do <add> <add> @association.scope.extending! do <ide> define_method(:proxy_association) { association } <ide> end <ide> end <ide><path>activerecord/lib/active_record/null_relation.rb <ide> def where_values_hash <ide> {} <ide> end <ide> <del> def count <add> def count(*) <ide> 0 <ide> end <ide>
3
Go
Go
export more functions from libcontainer
b6b0dfdba7bda13d630217830423580c3152899d
<ide><path>pkg/libcontainer/nsinit/command.go <ide> package nsinit <ide> <ide> import ( <del> "github.com/dotcloud/docker/pkg/libcontainer" <del> "github.com/dotcloud/docker/pkg/system" <ide> "os" <ide> "os/exec" <add> <add> "github.com/dotcloud/docker/pkg/libcontainer" <add> "github.com/dotcloud/docker/pkg/system" <ide> ) <ide> <ide> // CommandFactory takes the container's configuration and options passed by the <ide> func (c *DefaultCommandFactory) Create(container *libcontainer.Container, consol <ide> command.ExtraFiles = []*os.File{pipe} <ide> return command <ide> } <del> <del>// GetNamespaceFlags parses the container's Namespaces options to set the correct <del>// flags on clone, unshare, and setns <del>func GetNamespaceFlags(namespaces libcontainer.Namespaces) (flag int) { <del> for _, ns := range namespaces { <del> if ns.Enabled { <del> flag |= ns.Value <del> } <del> } <del> return flag <del>} <ide><path>pkg/libcontainer/nsinit/exec.go <ide> func DeletePid(path string) error { <ide> } <ide> return err <ide> } <add> <add>// GetNamespaceFlags parses the container's Namespaces options to set the correct <add>// flags on clone, unshare, and setns <add>func GetNamespaceFlags(namespaces libcontainer.Namespaces) (flag int) { <add> for _, ns := range namespaces { <add> if ns.Enabled { <add> flag |= ns.Value <add> } <add> } <add> return flag <add>} <ide><path>pkg/libcontainer/nsinit/execin.go <ide> func (ns *linuxNs) ExecIn(container *libcontainer.Container, nspid int, args []s <ide> os.Exit(state.Sys().(syscall.WaitStatus).ExitStatus()) <ide> } <ide> dropAndExec: <del> if err := finalizeNamespace(container); err != nil { <add> if err := FinalizeNamespace(container); err != nil { <ide> return -1, err <ide> } <ide> err = label.SetProcessLabel(processLabel) <ide><path>pkg/libcontainer/nsinit/init.go <ide> func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, consol <ide> } <ide> <ide> label.Init() <add> <ide> if err := mount.InitializeMountNamespace(rootfs, consolePath, container); err != nil { <ide> return fmt.Errorf("setup mount namespace %s", err) <ide> } <ide> if err := system.Sethostname(container.Hostname); err != nil { <ide> return fmt.Errorf("sethostname %s", err) <ide> } <del> if err := finalizeNamespace(container); err != nil { <add> if err := FinalizeNamespace(container); err != nil { <ide> return fmt.Errorf("finalize namespace %s", err) <ide> } <ide> <del> if profile := container.Context["apparmor_profile"]; profile != "" { <del> if err := apparmor.ApplyProfile(os.Getpid(), profile); err != nil { <del> return err <del> } <del> } <ide> runtime.LockOSThread() <ide> <add> if err := apparmor.ApplyProfile(os.Getpid(), container.Context["apparmor_profile"]); err != nil { <add> return err <add> } <ide> if err := label.SetProcessLabel(container.Context["process_label"]); err != nil { <ide> return fmt.Errorf("set process label %s", err) <ide> } <ide> func setupNetwork(container *libcontainer.Container, context libcontainer.Contex <ide> return nil <ide> } <ide> <del>// finalizeNamespace drops the caps, sets the correct user <add>// FinalizeNamespace drops the caps, sets the correct user <ide> // and working dir, and closes any leaky file descriptors <ide> // before execing the command inside the namespace <del>func finalizeNamespace(container *libcontainer.Container) error { <add>func FinalizeNamespace(container *libcontainer.Container) error { <ide> if err := capabilities.DropCapabilities(container); err != nil { <ide> return fmt.Errorf("drop capabilities %s", err) <ide> } <ide><path>pkg/libcontainer/nsinit/unsupported.go <ide> func (ns *linuxNs) ExecIn(container *libcontainer.Container, nspid int, args []s <ide> func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, console string, syncPipe *SyncPipe, args []string) error { <ide> return libcontainer.ErrUnsupported <ide> } <add> <add>func GetNamespaceFlags(namespaces libcontainer.Namespaces) (flag int) { <add> return 0 <add>}
5
Java
Java
add error message to mockserverhttprequest
955f77bf5d30d74e28fa7c3f61fddc45aff771c4
<ide><path>spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpRequest.java <ide> public static BodyBuilder method(HttpMethod method, URI url) { <ide> * @return the created builder <ide> */ <ide> public static BodyBuilder method(HttpMethod method, String urlTemplate, Object... vars) { <add> Assert.notNull(method, "HttpMethod is required. If testing a custom HTTP method, " + <add> "please use the variant that accepts a String based HTTP method."); <ide> URI url = UriComponentsBuilder.fromUriString(urlTemplate).buildAndExpand(vars).encode().toUri(); <ide> return new DefaultBodyBuilder(method, url); <ide> } <ide><path>spring-web/src/testFixtures/java/org/springframework/web/testfixture/http/server/reactive/MockServerHttpRequest.java <ide> public static BodyBuilder method(HttpMethod method, URI url) { <ide> * @return the created builder <ide> */ <ide> public static BodyBuilder method(HttpMethod method, String urlTemplate, Object... vars) { <add> Assert.notNull(method, "HttpMethod is required. If testing a custom HTTP method, " + <add> "please use the variant that accepts a String based HTTP method."); <ide> URI url = UriComponentsBuilder.fromUriString(urlTemplate).buildAndExpand(vars).encode().toUri(); <ide> return new DefaultBodyBuilder(method, url); <ide> }
2
Text
Text
fix typo in pipe from async iterator example
eb4c1d5663ff7089badfeaf37dbe246df60607e9
<ide><path>doc/api/stream.md <ide> const writeable = fs.createWriteStream('./file'); <ide> (async function() { <ide> for await (const chunk of iterator) { <ide> // Handle backpressure on write <del> if (!writeable.write(value)) <add> if (!writeable.write(chunk)) <ide> await once(writeable, 'drain'); <ide> } <ide> writeable.end();
1
Ruby
Ruby
decrease allocations in transliterate
57ba9cbc6ccaa20a1ac3ca671d17040946839db3
<ide><path>activesupport/lib/active_support/inflector/transliterate.rb <ide> module Inflector <ide> # I18n.locale = :de <ide> # transliterate('Jürgen') <ide> # # => "Juergen" <del> def transliterate(string, replacement = "?") <add> def transliterate(string, replacement = "?".freeze) <ide> I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize( <ide> ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c), <ide> :replacement => replacement) <ide> def parameterize(string, sep = '-') <ide> # Turn unwanted chars into the separator <ide> parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep) <ide> unless sep.nil? || sep.empty? <del> re_sep = Regexp.escape(sep) <add> if sep == "-".freeze <add> re_duplicate_seperator = /-{2,}/ <add> re_leading_trailing_separator = /^-|-$/i <add> else <add> re_sep = Regexp.escape(sep) <add> re_duplicate_seperator = /#{re_sep}{2,}/ <add> re_leading_trailing_separator = /^#{re_sep}|#{re_sep}$/i <add> end <ide> # No more than one of the separator in a row. <del> parameterized_string.gsub!(/#{re_sep}{2,}/, sep) <add> parameterized_string.gsub!(re_duplicate_seperator, sep) <ide> # Remove leading/trailing separator. <del> parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, ''.freeze) <add> parameterized_string.gsub!(re_leading_trailing_separator, ''.freeze) <ide> end <del> parameterized_string.downcase <add> parameterized_string.downcase! <add> parameterized_string <ide> end <ide> end <ide> end
1
PHP
PHP
add application stack to app server provider
2893433b35c96a210564e4468ba4b5830c560477
<ide><path>app/Providers/AppServiceProvider.php <ide> <?php namespace App\Providers; <ide> <add>use Illuminate\Routing\Router; <ide> use Illuminate\Support\ServiceProvider; <add>use Illuminate\Routing\Stack\Builder as Stack; <ide> <ide> class AppServiceProvider extends ServiceProvider { <ide> <ide> class AppServiceProvider extends ServiceProvider { <ide> */ <ide> public function boot() <ide> { <del> // <add> // This service provider is a convenient place to register your services <add> // in the IoC container. If you wish, you may make additional methods <add> // or service providers to keep the code more focused and granular. <add> <add> $this->app->stack(function(Stack $stack, Router $router) <add> { <add> return $stack <add> ->middleware('Illuminate\Cookie\Guard') <add> ->middleware('Illuminate\Cookie\Queue') <add> ->middleware('Illuminate\Session\Middlewares\Reader') <add> ->middleware('Illuminate\Session\Middlewares\Writer') <add> ->then(function($request) use ($router) <add> { <add> return $router->dispatch($request); <add> }); <add> }); <ide> } <ide> <ide> /** <ide> public function boot() <ide> */ <ide> public function register() <ide> { <del> // This service provider is a convenient place to register your services <del> // in the IoC container. If you wish, you may make additional methods <del> // or service providers to keep the code more focused and granular. <del> <ide> // <ide> } <ide>
1
Text
Text
restore missing "format" example
edbb8fb86d7d0b715adc15415f0cb187433092a5
<ide><path>docs/reference/commandline/create.md <ide> Options: <ide> 'host': Use the Docker host user namespace <ide> '': Use the Docker daemon user namespace specified by `--userns-remap` option. <ide> --uts string UTS namespace to use <del> -v, --volume value Bind mount a volume (default []). The comma-delimited <del> `options` are [rw|ro], [z|Z], <del> [[r]shared|[r]slave|[r]private], and <add> -v, --volume value Bind mount a volume (default []). The format <add> is `[host-src:]container-dest[:<options>]`. <add> The comma-delimited `options` are [rw|ro], <add> [z|Z], [[r]shared|[r]slave|[r]private], and <ide> [nocopy]. The 'host-src' is an absolute path <ide> or a name value. <ide> --volume-driver string Optional volume driver for the container <ide><path>docs/reference/commandline/run.md <ide> Options: <ide> 'host': Use the Docker host user namespace <ide> '': Use the Docker daemon user namespace specified by `--userns-remap` option. <ide> --uts string UTS namespace to use <del> -v, --volume value Bind mount a volume (default []). The comma-delimited <del> `options` are [rw|ro], [z|Z], <del> [[r]shared|[r]slave|[r]private], and <add> -v, --volume value Bind mount a volume (default []). The format <add> is `[host-src:]container-dest[:<options>]`. <add> The comma-delimited `options` are [rw|ro], <add> [z|Z], [[r]shared|[r]slave|[r]private], and <ide> [nocopy]. The 'host-src' is an absolute path <ide> or a name value. <ide> --volume-driver string Optional volume driver for the container
2
Text
Text
remove unstable branch badge
ee858fadd593fc2d8867efebd5b202f9933786a7
<ide><path>README.md <ide> [![Code Consistency](https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/grade.svg)](http://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/) <ide> [![Total Downloads](https://img.shields.io/packagist/dt/cakephp/cakephp.svg?style=flat-square)](https://packagist.org/packages/cakephp/cakephp) <ide> [![Latest Stable Version](https://img.shields.io/packagist/v/cakephp/cakephp.svg?style=flat-square&label=stable)](https://packagist.org/packages/cakephp/cakephp) <del>[![Latest Unstable Version](https://img.shields.io/packagist/vpre/cakephp/cakephp.svg?style=flat-square&label=unstable)](https://packagist.org/packages/cakephp/cakephp) <ide> <ide> [CakePHP](http://www.cakephp.org) is a rapid development framework for PHP which <ide> uses commonly known design patterns like Associative Data
1
Javascript
Javascript
remove deprecated helpers
92a4654d9b2ae91683c179cbf6186b31952cfcd1
<ide><path>src/core/core.helpers.js <ide> module.exports = function() { <ide> return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); <ide> }; <ide> <del> /** <del> * Provided for backward compatibility, not available anymore <del> * @function Chart.helpers.aliasPixel <del> * @deprecated since version 2.8.0 <del> * @todo remove at version 3 <del> */ <del> helpers.aliasPixel = function(pixelWidth) { <del> return (pixelWidth % 2 === 0) ? 0 : 0.5; <del> }; <del> <ide> /** <ide> * Returns the aligned pixel value to avoid anti-aliasing blur <ide> * @param {Chart} chart - The chart instance. <ide> module.exports = function() { <ide> }; <ide> // Implementation of the nice number algorithm used in determining where axis labels will go <ide> helpers.niceNum = function(range, round) { <del> var exponent = Math.floor(helpers.log10(range)); <add> var exponent = Math.floor(helpers.math.log10(range)); <ide> var fraction = range / Math.pow(10, exponent); <ide> var niceFraction; <ide> <ide> module.exports = function() { <ide> return longest; <ide> }; <ide> <del> /** <del> * @deprecated <del> */ <del> helpers.numberOfLabelLines = function(arrayOfThings) { <del> var numberOfLines = 1; <del> helpers.each(arrayOfThings, function(thing) { <del> if (helpers.isArray(thing)) { <del> if (thing.length > numberOfLines) { <del> numberOfLines = thing.length; <del> } <del> } <del> }); <del> return numberOfLines; <del> }; <del> <ide> helpers.color = !color ? <ide> function(value) { <ide> console.error('Color.js not found!'); <ide><path>src/core/core.ticks.js <ide> 'use strict'; <ide> <ide> var helpers = require('../helpers/index'); <add>var math = helpers.math; <ide> <ide> /** <ide> * Namespace to hold static tick generation functions <ide> module.exports = { <ide> } <ide> } <ide> <del> var logDelta = helpers.log10(Math.abs(delta)); <add> var logDelta = math.log10(Math.abs(delta)); <ide> var tickString = ''; <ide> <ide> if (tickValue !== 0) { <ide> var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1])); <ide> if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation <del> var logTick = helpers.log10(Math.abs(tickValue)); <add> var logTick = math.log10(Math.abs(tickValue)); <ide> var numExponential = Math.floor(logTick) - Math.floor(logDelta); <ide> numExponential = Math.max(Math.min(numExponential, 20), 0); <ide> tickString = tickValue.toExponential(numExponential); <ide> module.exports = { <ide> }, <ide> <ide> logarithmic: function(tickValue, index, ticks) { <del> var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue)))); <add> var remain = tickValue / (Math.pow(10, Math.floor(math.log10(tickValue)))); <ide> <ide> if (tickValue === 0) { <ide> return '0'; <ide><path>src/helpers/helpers.canvas.js <ide> 'use strict'; <ide> <del>var helpers = require('./helpers.core'); <del> <ide> var PI = Math.PI; <ide> var RAD_PER_DEG = PI / 180; <ide> var DOUBLE_PI = PI * 2; <ide> var exports = { <ide> }; <ide> <ide> module.exports = exports; <del> <del>// DEPRECATIONS <del> <del>/** <del> * Provided for backward compatibility, use Chart.helpers.canvas.clear instead. <del> * @namespace Chart.helpers.clear <del> * @deprecated since version 2.7.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.clear = exports.clear; <del> <del>/** <del> * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead. <del> * @namespace Chart.helpers.drawRoundedRectangle <del> * @deprecated since version 2.7.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.drawRoundedRectangle = function(ctx) { <del> ctx.beginPath(); <del> exports.roundedRect.apply(exports, arguments); <del>}; <ide><path>src/helpers/helpers.core.js <ide> var helpers = { <ide> }; <ide> <ide> module.exports = helpers; <del> <del>// DEPRECATIONS <del> <del>/** <del> * Provided for backward compatibility, use Chart.helpers.callback instead. <del> * @function Chart.helpers.callCallback <del> * @deprecated since version 2.6.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.callCallback = helpers.callback; <del> <del>/** <del> * Provided for backward compatibility, use Array.prototype.indexOf instead. <del> * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+ <del> * @function Chart.helpers.indexOf <del> * @deprecated since version 2.7.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.indexOf = function(array, item, fromIndex) { <del> return Array.prototype.indexOf.call(array, item, fromIndex); <del>}; <del> <del>/** <del> * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead. <del> * @function Chart.helpers.getValueOrDefault <del> * @deprecated since version 2.7.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.getValueOrDefault = helpers.valueOrDefault; <del> <del>/** <del> * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead. <del> * @function Chart.helpers.getValueAtIndexOrDefault <del> * @deprecated since version 2.7.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault; <ide><path>src/helpers/helpers.easing.js <ide> 'use strict'; <ide> <del>var helpers = require('./helpers.core'); <del> <ide> /** <ide> * Easing functions adapted from Robert Penner's easing equations. <del> * @namespace Chart.helpers.easingEffects <add> * @namespace Chart.helpers.effects <ide> * @see http://www.robertpenner.com/easing/ <ide> */ <ide> var effects = { <ide> var effects = { <ide> module.exports = { <ide> effects: effects <ide> }; <del> <del>// DEPRECATIONS <del> <del>/** <del> * Provided for backward compatibility, use Chart.helpers.easing.effects instead. <del> * @function Chart.helpers.easingEffects <del> * @deprecated since version 2.7.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.easingEffects = effects; <ide><path>src/helpers/helpers.math.js <ide> 'use strict'; <ide> <del>var helpers = require('./helpers.core'); <del> <ide> /** <ide> * @alias Chart.helpers.math <ide> * @namespace <ide> var exports = { <ide> }; <ide> <ide> module.exports = exports; <del> <del>// DEPRECATIONS <del> <del>/** <del> * Provided for backward compatibility, use Chart.helpers.math.log10 instead. <del> * @namespace Chart.helpers.log10 <del> * @deprecated since version 2.9.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.log10 = exports.log10; <ide><path>src/platforms/platform.dom.js <ide> module.exports = { <ide> removeListener(canvas, type, proxy); <ide> } <ide> }; <del> <del>// DEPRECATIONS <del> <del>/** <del> * Provided for backward compatibility, use EventTarget.addEventListener instead. <del> * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ <del> * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener <del> * @function Chart.helpers.addEvent <del> * @deprecated since version 2.7.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.addEvent = addListener; <del> <del>/** <del> * Provided for backward compatibility, use EventTarget.removeEventListener instead. <del> * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ <del> * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener <del> * @function Chart.helpers.removeEvent <del> * @deprecated since version 2.7.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del>helpers.removeEvent = removeListener; <ide><path>test/specs/core.helpers.tests.js <ide> describe('Core helper tests', function() { <ide> }]); <ide> }); <ide> <del> it('count look at all the labels and return maximum number of lines', function() { <del> window.createMockContext(); <del> var arrayOfThings1 = ['Foo', 'Bar']; <del> var arrayOfThings2 = [['Foo', 'Bar'], 'Foo']; <del> var arrayOfThings3 = [['Foo', 'Bar', 'Boo'], ['Foo', 'Bar'], 'Foo']; <del> <del> expect(helpers.numberOfLabelLines(arrayOfThings1)).toEqual(1); <del> expect(helpers.numberOfLabelLines(arrayOfThings2)).toEqual(2); <del> expect(helpers.numberOfLabelLines(arrayOfThings3)).toEqual(3); <del> }); <del> <ide> it ('should get the maximum width and height for a node', function() { <ide> // Create div with fixed size as a test bed <ide> var div = document.createElement('div'); <ide><path>test/specs/global.deprecations.tests.js <del>describe('Deprecations', function() { <del> describe('Version 2.9.0', function() { <del> describe('Chart.Scale.mergeTicksOptions', function() { <del> it('should be defined as a function', function() { <del> expect(typeof Chart.Scale.prototype.mergeTicksOptions).toBe('function'); <del> }); <del> }); <del> }); <del> <del> describe('Version 2.8.0', function() { <del> [ <del> ['Bar', 'bar'], <del> ['Bubble', 'bubble'], <del> ['Doughnut', 'doughnut'], <del> ['Line', 'line'], <del> ['PolarArea', 'polarArea'], <del> ['Radar', 'radar'], <del> ['Scatter', 'scatter'] <del> ].forEach(function(descriptor) { <del> var klass = descriptor[0]; <del> var type = descriptor[1]; <del> <del> describe('Chart.' + klass, function() { <del> it('should be defined as a function', function() { <del> expect(typeof Chart[klass]).toBe('function'); <del> }); <del> it('should create a chart of type "' + type + '"', function() { <del> var chart = new Chart[klass]('foo', {data: {}}); <del> expect(chart instanceof Chart.Controller).toBeTruthy(); <del> expect(chart.config.type).toBe(type); <del> }); <del> }); <del> }); <del> <del> describe('Chart.Chart', function() { <del> it('should be defined as an alias to Chart', function() { <del> expect(Chart.Chart).toBe(Chart); <del> }); <del> }); <del> <del> describe('Chart.helpers.aliasPixel', function() { <del> it('should be defined as a function', function() { <del> expect(typeof Chart.helpers.aliasPixel).toBe('function'); <del> }); <del> }); <del> <del> describe('Chart.LinearScaleBase', function() { <del> it('should be defined and inherit from Chart.Scale', function() { <del> expect(typeof Chart.LinearScaleBase).toBe('function'); <del> expect(Chart.LinearScaleBase.prototype instanceof Chart.Scale).toBeTruthy(); <del> }); <del> }); <del> <del> describe('Chart.types', function() { <del> it('should be defined as an empty object', function() { <del> expect(Chart.types).toEqual({}); <del> }); <del> }); <del> <del> describe('Chart.helpers.configMerge', function() { <del> it('should be defined as a function', function() { <del> expect(typeof Chart.helpers.configMerge).toBe('function'); <del> }); <del> }); <del> <del> describe('Chart.helpers.scaleMerge', function() { <del> it('should be defined as a function', function() { <del> expect(typeof Chart.helpers.scaleMerge).toBe('function'); <del> }); <del> }); <del> }); <del> <del> describe('Version 2.7.3', function() { <del> describe('Chart.layoutService', function() { <del> it('should be defined and an alias of Chart.layouts', function() { <del> expect(Chart.layoutService).toBeDefined(); <del> expect(Chart.layoutService).toBe(Chart.layouts); <del> }); <del> }); <del> }); <del> <del> describe('Version 2.7.0', function() { <del> describe('Chart.Controller.update(duration, lazy)', function() { <del> it('should add an animation with the provided options', function() { <del> var chart = acquireChart({ <del> type: 'doughnut', <del> options: { <del> animation: { <del> easing: 'linear', <del> duration: 500 <del> } <del> } <del> }); <del> <del> spyOn(Chart.animationService, 'addAnimation'); <del> <del> chart.update(800, false); <del> <del> expect(Chart.animationService.addAnimation).toHaveBeenCalledWith( <del> chart, <del> jasmine.objectContaining({easing: 'linear'}), <del> 800, <del> false <del> ); <del> }); <del> }); <del> <del> describe('Chart.Controller.render(duration, lazy)', function() { <del> it('should add an animation with the provided options', function() { <del> var chart = acquireChart({ <del> type: 'doughnut', <del> options: { <del> animation: { <del> easing: 'linear', <del> duration: 500 <del> } <del> } <del> }); <del> <del> spyOn(Chart.animationService, 'addAnimation'); <del> <del> chart.render(800, true); <del> <del> expect(Chart.animationService.addAnimation).toHaveBeenCalledWith( <del> chart, <del> jasmine.objectContaining({easing: 'linear'}), <del> 800, <del> true <del> ); <del> }); <del> }); <del> <del> describe('Chart.helpers.indexOf', function() { <del> it('should be defined and a function', function() { <del> expect(typeof Chart.helpers.indexOf).toBe('function'); <del> }); <del> it('should returns the correct index', function() { <del> expect(Chart.helpers.indexOf([1, 2, 42], 42)).toBe(2); <del> expect(Chart.helpers.indexOf([1, 2, 42], 3)).toBe(-1); <del> expect(Chart.helpers.indexOf([1, 42, 2, 42], 42, 2)).toBe(3); <del> expect(Chart.helpers.indexOf([1, 42, 2, 42], 3, 2)).toBe(-1); <del> }); <del> }); <del> <del> describe('Chart.helpers.clear', function() { <del> it('should be defined and an alias of Chart.helpers.canvas.clear', function() { <del> expect(Chart.helpers.clear).toBeDefined(); <del> expect(Chart.helpers.clear).toBe(Chart.helpers.canvas.clear); <del> }); <del> }); <del> <del> describe('Chart.helpers.getValueOrDefault', function() { <del> it('should be defined and an alias of Chart.helpers.valueOrDefault', function() { <del> expect(Chart.helpers.getValueOrDefault).toBeDefined(); <del> expect(Chart.helpers.getValueOrDefault).toBe(Chart.helpers.valueOrDefault); <del> }); <del> }); <del> <del> describe('Chart.helpers.getValueAtIndexOrDefault', function() { <del> it('should be defined and an alias of Chart.helpers.valueAtIndexOrDefault', function() { <del> expect(Chart.helpers.getValueAtIndexOrDefault).toBeDefined(); <del> expect(Chart.helpers.getValueAtIndexOrDefault).toBe(Chart.helpers.valueAtIndexOrDefault); <del> }); <del> }); <del> <del> describe('Chart.helpers.easingEffects', function() { <del> it('should be defined and an alias of Chart.helpers.easing.effects', function() { <del> expect(Chart.helpers.easingEffects).toBeDefined(); <del> expect(Chart.helpers.easingEffects).toBe(Chart.helpers.easing.effects); <del> }); <del> }); <del> <del> describe('Chart.helpers.drawRoundedRectangle', function() { <del> it('should be defined and a function', function() { <del> expect(typeof Chart.helpers.drawRoundedRectangle).toBe('function'); <del> }); <del> it('should call Chart.helpers.canvas.roundedRect', function() { <del> var ctx = window.createMockContext(); <del> spyOn(Chart.helpers.canvas, 'roundedRect'); <del> <del> Chart.helpers.drawRoundedRectangle(ctx, 10, 20, 30, 40, 5); <del> <del> var calls = ctx.getCalls(); <del> expect(calls[0]).toEqual({name: 'beginPath', args: []}); <del> expect(Chart.helpers.canvas.roundedRect).toHaveBeenCalledWith(ctx, 10, 20, 30, 40, 5); <del> }); <del> }); <del> <del> describe('Chart.helpers.addEvent', function() { <del> it('should be defined and a function', function() { <del> expect(typeof Chart.helpers.addEvent).toBe('function'); <del> }); <del> it('should correctly add event listener', function() { <del> var listener = jasmine.createSpy('spy'); <del> Chart.helpers.addEvent(window, 'test', listener); <del> window.dispatchEvent(new Event('test')); <del> expect(listener).toHaveBeenCalled(); <del> }); <del> }); <del> <del> describe('Chart.helpers.removeEvent', function() { <del> it('should be defined and a function', function() { <del> expect(typeof Chart.helpers.removeEvent).toBe('function'); <del> }); <del> it('should correctly remove event listener', function() { <del> var listener = jasmine.createSpy('spy'); <del> Chart.helpers.addEvent(window, 'test', listener); <del> Chart.helpers.removeEvent(window, 'test', listener); <del> window.dispatchEvent(new Event('test')); <del> expect(listener).not.toHaveBeenCalled(); <del> }); <del> }); <del> }); <del> <del> describe('Version 2.6.0', function() { <del> // https://github.com/chartjs/Chart.js/issues/2481 <del> describe('Chart.Controller', function() { <del> it('should be defined and an alias of Chart', function() { <del> expect(Chart.Controller).toBeDefined(); <del> expect(Chart.Controller).toBe(Chart); <del> }); <del> it('should be prototype of chart instances', function() { <del> var chart = acquireChart({}); <del> expect(chart.constructor).toBe(Chart.Controller); <del> expect(chart instanceof Chart.Controller).toBeTruthy(); <del> expect(Chart.Controller.prototype.isPrototypeOf(chart)).toBeTruthy(); <del> }); <del> }); <del> <del> describe('chart.chart', function() { <del> it('should be defined and an alias of chart', function() { <del> var chart = acquireChart({}); <del> var proxy = chart.chart; <del> expect(proxy).toBeDefined(); <del> expect(proxy).toBe(chart); <del> }); <del> it('should defined previously existing properties', function() { <del> var chart = acquireChart({}, { <del> canvas: { <del> style: 'width: 140px; height: 320px' <del> } <del> }); <del> <del> var proxy = chart.chart; <del> expect(proxy.config instanceof Object).toBeTruthy(); <del> expect(proxy.controller instanceof Chart.Controller).toBeTruthy(); <del> expect(proxy.canvas instanceof HTMLCanvasElement).toBeTruthy(); <del> expect(proxy.ctx instanceof CanvasRenderingContext2D).toBeTruthy(); <del> expect(proxy.currentDevicePixelRatio).toBe(window.devicePixelRatio || 1); <del> expect(proxy.aspectRatio).toBe(140 / 320); <del> expect(proxy.height).toBe(320); <del> expect(proxy.width).toBe(140); <del> }); <del> }); <del> <del> describe('Chart.Animation.animationObject', function() { <del> it('should be defined and an alias of Chart.Animation', function(done) { <del> var animation = null; <del> <del> acquireChart({ <del> options: { <del> animation: { <del> duration: 50, <del> onComplete: function(arg) { <del> animation = arg; <del> } <del> } <del> } <del> }); <del> <del> setTimeout(function() { <del> expect(animation).not.toBeNull(); <del> expect(animation.animationObject).toBeDefined(); <del> expect(animation.animationObject).toBe(animation); <del> done(); <del> }, 200); <del> }); <del> }); <del> <del> describe('Chart.Animation.chartInstance', function() { <del> it('should be defined and an alias of Chart.Animation.chart', function(done) { <del> var animation = null; <del> var chart = acquireChart({ <del> options: { <del> animation: { <del> duration: 50, <del> onComplete: function(arg) { <del> animation = arg; <del> } <del> } <del> } <del> }); <del> <del> setTimeout(function() { <del> expect(animation).not.toBeNull(); <del> expect(animation.chartInstance).toBeDefined(); <del> expect(animation.chartInstance).toBe(chart); <del> done(); <del> }, 200); <del> }); <del> }); <del> <del> describe('Chart.elements.Line: fill option', function() { <del> it('should decode "zero", "top" and "bottom" as "origin", "start" and "end"', function() { <del> var chart = window.acquireChart({ <del> type: 'line', <del> data: { <del> datasets: [ <del> {fill: 'zero'}, <del> {fill: 'bottom'}, <del> {fill: 'top'}, <del> ] <del> } <del> }); <del> <del> ['origin', 'start', 'end'].forEach(function(expected, index) { <del> var meta = chart.getDatasetMeta(index); <del> expect(meta.$filler).toBeDefined(); <del> expect(meta.$filler.fill).toBe(expected); <del> }); <del> }); <del> }); <del> <del> describe('Chart.helpers.callCallback', function() { <del> it('should be defined and an alias of Chart.helpers.callback', function() { <del> expect(Chart.helpers.callCallback).toBeDefined(); <del> expect(Chart.helpers.callCallback).toBe(Chart.helpers.callback); <del> }); <del> }); <del> <del> describe('Time Axis: unitStepSize option', function() { <del> it('should use the stepSize property', function() { <del> var chart = window.acquireChart({ <del> type: 'line', <del> data: { <del> labels: ['2015-01-01T20:00:00', '2015-01-01T21:00:00'], <del> }, <del> options: { <del> scales: { <del> xAxes: [{ <del> id: 'time', <del> type: 'time', <del> bounds: 'ticks', <del> time: { <del> unit: 'hour', <del> unitStepSize: 2 <del> } <del> }] <del> } <del> } <del> }); <del> <del> var ticks = chart.scales.time.getTicks().map(function(tick) { <del> return tick.label; <del> }); <del> <del> expect(ticks).toEqual(['8PM', '10PM']); <del> }); <del> }); <del> }); <del> <del> describe('Version 2.5.0', function() { <del> describe('Chart.PluginBase', function() { <del> it('should exist and extendable', function() { <del> expect(Chart.PluginBase).toBeDefined(); <del> expect(Chart.PluginBase.extend).toBeDefined(); <del> }); <del> }); <del> <del> describe('IPlugin.afterScaleUpdate', function() { <del> it('should be called after the chart as been layed out', function() { <del> var sequence = []; <del> var plugin = {}; <del> var hooks = [ <del> 'beforeLayout', <del> 'afterScaleUpdate', <del> 'afterLayout' <del> ]; <del> <del> var override = Chart.layouts.update; <del> Chart.layouts.update = function() { <del> sequence.push('layoutUpdate'); <del> override.apply(this, arguments); <del> }; <del> <del> hooks.forEach(function(name) { <del> plugin[name] = function() { <del> sequence.push(name); <del> }; <del> }); <del> <del> window.acquireChart({plugins: [plugin]}); <del> expect(sequence).toEqual([].concat( <del> 'beforeLayout', <del> 'layoutUpdate', <del> 'afterScaleUpdate', <del> 'afterLayout' <del> )); <del> }); <del> }); <del> }); <del> <del> describe('Version 2.4.0', function() { <del> describe('x-axis mode', function() { <del> it ('behaves like index mode with intersect: false', function() { <del> var data = { <del> datasets: [{ <del> label: 'Dataset 1', <del> data: [10, 20, 30], <del> pointHoverBorderColor: 'rgb(255, 0, 0)', <del> pointHoverBackgroundColor: 'rgb(0, 255, 0)' <del> }, { <del> label: 'Dataset 2', <del> data: [40, 40, 40], <del> pointHoverBorderColor: 'rgb(0, 0, 255)', <del> pointHoverBackgroundColor: 'rgb(0, 255, 255)' <del> }], <del> labels: ['Point 1', 'Point 2', 'Point 3'] <del> }; <del> <del> var chart = window.acquireChart({ <del> type: 'line', <del> data: data <del> }); <del> var meta0 = chart.getDatasetMeta(0); <del> var meta1 = chart.getDatasetMeta(1); <del> <del> var evt = { <del> type: 'click', <del> chart: chart, <del> native: true, // needed otherwise things its a DOM event <del> x: 0, <del> y: 0 <del> }; <del> <del> var elements = Chart.Interaction.modes['x-axis'](chart, evt); <del> expect(elements).toEqual([meta0.data[0], meta1.data[0]]); <del> }); <del> }); <del> }); <del> <del> describe('Version 2.1.5', function() { <del> // https://github.com/chartjs/Chart.js/pull/2752 <del> describe('Chart.pluginService', function() { <del> it('should be defined and an alias of Chart.plugins', function() { <del> expect(Chart.pluginService).toBeDefined(); <del> expect(Chart.pluginService).toBe(Chart.plugins); <del> }); <del> }); <del> <del> describe('Chart.Legend', function() { <del> it('should be defined and an instance of Chart.Element', function() { <del> var legend = new Chart.Legend({}); <del> expect(Chart.Legend).toBeDefined(); <del> expect(legend).not.toBe(undefined); <del> expect(legend instanceof Chart.Element).toBeTruthy(); <del> }); <del> }); <del> <del> describe('Chart.Title', function() { <del> it('should be defined and an instance of Chart.Element', function() { <del> var title = new Chart.Title({}); <del> expect(Chart.Title).toBeDefined(); <del> expect(title).not.toBe(undefined); <del> expect(title instanceof Chart.Element).toBeTruthy(); <del> }); <del> }); <del> }); <del>});
9
Text
Text
add some links and update test commands
1dccaaaaa27a4db91d5271438688bc96e199e561
<ide><path>README.md <del>Angular <del>====== <add>AngularJS <add>========= <add> <add>* Web site: http://angularjs.org <add>* Tutorial: http://docs.angularjs.org/#!/tutorial <add>* API Docs: http://docs.angularjs.org <add>* Developer Guide: http://docs.angularjs.org/#!/guide <ide> <ide> Compiling <ide> --------- <ide> rake compile <ide> <ide> Running Tests <ide> ------------- <del> rake server:start <del> rake test <add> ./server.sh # start the server <add> open http://localhost:9876/capture # capture browser <add> ./test.sh # run all unit tests <add> <ide>
1
Text
Text
add v3.20.3 to changelog.md
0bd4855c2d2b77f1b4ad92372a6e7c96d52430a9
<ide><path>CHANGELOG.md <ide> - [#19048](https://github.com/emberjs/ember.js/pull/19048) [BUGFIX] Update router.js to ensure transition.abort works for query param only transitions. <ide> - [#19056](https://github.com/emberjs/ember.js/pull/19056) [BUGFIX] Update glimmer-vm to 0.54.2. <ide> <del>### v3.20.2 (July 26, 2020) <del> <del>- [#19056](https://github.com/emberjs/ember.js/pull/19056) Update Glimmer rendering engine to 0.54.2. Fixes an issue with (private for now) destroyables work to enable the destroyables polyfill to work more appropriately. <del> <ide> ### v3.21.0-beta.2 (July 20, 2020) <ide> <ide> - [#19040](https://github.com/emberjs/ember.js/pull/19040) [BUGFIX] Fix a memory leak that occurred when changing the array passed to `{{each}}` <ide> - [#18993](https://github.com/emberjs/ember.js/pull/18993) [DEPRECATION] Deprecate `getWithDefault` per [RFC #554](https://github.com/emberjs/rfcs/blob/master/text/0554-deprecate-getwithdefault.md). <ide> - [#17571](https://github.com/emberjs/ember.js/pull/17571) [BUGFIX] Avoid tampering `queryParam` argument in RouterService#isActive <ide> <add>### v3.20.3 (July 30, 2020) <add> <add>- [#19048](https://github.com/emberjs/ember.js/pull/19048) [BUGFIX] Update `router.js` to ensure `transition.abort` works for query param only transitions <add>- [#19059](https://github.com/emberjs/ember.js/pull/19059) [BUGFIX] Prevent `<base target="_parent">` from erroring in `HistoryLocation` <add>- [#19060](https://github.com/emberjs/ember.js/pull/19060) [BUGFIX] Update rendering engine to `@glimmer/*` 0.55.1 <add>- [#19063](https://github.com/emberjs/ember.js/pull/19063) [DOC] Fix missing docs for `{{#in-element}}` <add> <add>### v3.20.2 (July 26, 2020) <add> <add>- [#19056](https://github.com/emberjs/ember.js/pull/19056) Update Glimmer rendering engine to 0.54.2. Fixes an issue with (private for now) destroyables work to enable the destroyables polyfill to work more appropriately. <add> <ide> ### v3.20.1 (July 13, 2020) <ide> <ide> - [#19040](https://github.com/emberjs/ember.js/pull/19040) [BUGFIX] Fix a memory leak that occurred when changing the array passed to `{{each}}`
1
Python
Python
add missing parameters to npyio.genfromtxt, fix
479437d295edde0158cff805c40fe3e5a17d3954
<ide><path>numpy/lib/npyio.py <ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None, <ide> The string used to separate values. By default, any consecutive <ide> whitespaces act as delimiter. An integer or sequence of integers <ide> can also be provided as width(s) of each field. <add> skip_rows : int, optional <add> `skip_rows` was deprecated in numpy 1.5, and will be removed in <add> numpy 2.0. Please use `skip_header` instead. <ide> skip_header : int, optional <ide> The numbers of lines to skip at the beginning of the file. <ide> skip_footer : int, optional <del> The numbers of lines to skip at the end of the file <add> The numbers of lines to skip at the end of the file. <ide> converters : variable, optional <ide> The set of functions that convert the data of a column to a value. <ide> The converters can also be used to provide a default value <ide> for missing data: ``converters = {3: lambda s: float(s or 0)}``. <add> missing : variable, optional <add> `missing` was deprecated in numpy 1.5, and will be removed in <add> numpy 2.0. Please use `missing_values` instead. <ide> missing_values : variable, optional <ide> The set of strings corresponding to missing data. <ide> filling_values : variable, optional <ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None, <ide> usemask : bool, optional <ide> If True, return a masked array. <ide> If False, return a regular array. <add> loose : bool, optional <add> If True, do not raise errors for invalid values. <ide> invalid_raise : bool, optional <ide> If True, an exception is raised if an inconsistency is detected in the <ide> number of columns.
1
Javascript
Javascript
ignore textnode's in quoted class ast transform
9e45c360163b19e9e41e51e8245bd1aa33f7485b
<ide><path>packages/ember-htmlbars/lib/plugins/transform-quoted-class.js <ide> export default function(ast) { <ide> var eachValue, currentValue, parts, containsNonStringLiterals; <ide> var i, l; <ide> while (eachValue = values[eachIndex]) { <add> if (eachValue.type === 'TextNode') { <add> return; // TextNode means no dynamic parts <add> } <add> <ide> if (eachValue.type === 'StringLiteral') { <ide> parts = eachValue.value.split(' '); <ide> for (i=0,l=parts.length;i<l;i++) {
1
Ruby
Ruby
add inbound email
627bbd34e142fa7caff49fd660a9a586f3ed6826
<ide><path>app/models/action_mailbox/inbound_email.rb <add>class ActionMailbox::InboundEmail < ActiveRecord::Base <add> self.table_name = "action_mailbox_inbound_email" <add> <add> after_create_commit :deliver_to_mailroom_later <add> has_one_attached :raw_message <add> <add> enum status: %i[ pending processing delivered failed bounced ] <add> <add> def mail <add> @mail ||= Mail.new(Mail::Utilities.binary_unsafe_to_crlf(raw_message.download)) <add> end <add> <add> private <add> def deliver_to_mailroom_later <add> ActionMailbox::DeliverInboundEmailToMailroomJob.perform_later self <add> end <add>end <ide><path>app/models/jobs/action_mailbox/deliver_inbound_email_to_mailbox.rb <add>class ActionMailbox::DeliverInboundEmailToMailroomJob < ApplicationJob <add> queue_as :action_mailbox_inbound_email <add> <add> # Occasional `SSL_read: decryption failed or bad record mac` that resolve on retry <add> retry_on OpenSSL::SSL::SSLError <add> <add> def perform(inbound_email) <add> ApplicationMailbox.receive inbound_email <add> end <add>end <ide><path>db/migrate/20180917164000_create_action_mailbox_tables.rb <add>class CreateActionMailboxTables < ActiveRecord::Migration[5.2] <add> def change <add> create_table :action_mailbox_inbound_emails do |t| <add> t.integer :status, default: 0, null: false <add> <add> t.datetime :created_at, precision: 6 <add> t.datetime :updated_at, precision: 6 <add> end <add> end <add>end
3
Python
Python
add check for ndarray/scalar in build_err_msg
2e58804fe546bf6d476d09ba186c36a69bc577c4
<ide><path>numpy/testing/utils.py <ide> import re <ide> import operator <ide> import warnings <add>from functools import partial <ide> from .nosetester import import_nose <del>from numpy.core import float32, empty, arange, array_repr <add>from numpy.core import float32, empty, arange, array_repr, ndarray <ide> <ide> if sys.version_info[0] >= 3: <ide> from io import StringIO <ide> def build_err_msg(arrays, err_msg, header='Items are not equal:', <ide> msg.append(err_msg) <ide> if verbose: <ide> for i, a in enumerate(arrays): <add> <add> if isinstance(a, ndarray): <add> # precision argument is only needed if the objects are ndarrays <add> r_func = partial(array_repr, precision=precision) <add> else: <add> r_func = repr <add> <ide> try: <del> r = array_repr(a, precision=precision) <add> r = r_func(a) <ide> except: <ide> r = '[repr failed]' <ide> if r.count('\n') > 3:
1
Ruby
Ruby
fix rubocop warnings
0f09674fe61f58572190f263d9173422d4e417d8
<ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_pour_bottle_dsl <ide> url "foo-1.0" <ide> pour_bottle? do <ide> reason "true reason" <del> satisfy { var == var } <add> satisfy { true } <ide> end <ide> end <ide> assert f_true.pour_bottle? <ide> class OutdatedVersionsTests < Homebrew::TestCase <ide> attr_reader :f <ide> <ide> def setup <del> @f = formula { url "foo"; version "1.20" } <add> @f = formula do <add> url "foo" <add> version "1.20" <add> end <ide> @outdated_prefix = HOMEBREW_CELLAR/"#{f.name}/1.11" <ide> @same_prefix = HOMEBREW_CELLAR/"#{f.name}/1.20" <ide> @greater_prefix = HOMEBREW_CELLAR/"#{f.name}/1.21"
1
Python
Python
add status codes as per rfc 6585
edd8f5963cb32063931a1557d3c6ac29d19b3425
<ide><path>djangorestframework/status.py <ide> """ <ide> Descriptive HTTP status codes, for code readability. <ide> <del>See RFC 2616 - Sec 10: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html <del>Also see django.core.handlers.wsgi.STATUS_CODE_TEXT <add>See RFC 2616 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html <add>And RFC 6585 - http://tools.ietf.org/html/rfc6585 <ide> """ <ide> <ide> HTTP_100_CONTINUE = 100 <ide> HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415 <ide> HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416 <ide> HTTP_417_EXPECTATION_FAILED = 417 <add>HTTP_428_PRECONDITION_REQUIRED = 428 <add>HTTP_429_TOO_MANY_REQUESTS = 429 <add>HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431 <ide> HTTP_500_INTERNAL_SERVER_ERROR = 500 <ide> HTTP_501_NOT_IMPLEMENTED = 501 <ide> HTTP_502_BAD_GATEWAY = 502 <ide> HTTP_503_SERVICE_UNAVAILABLE = 503 <ide> HTTP_504_GATEWAY_TIMEOUT = 504 <ide> HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505 <add>HTTP_511_NETWORD_AUTHENTICATION_REQUIRED = 511
1
Python
Python
use managers for queue synchronization
5649c70822e0866b4c6ec01bc7706c77599d0d7c
<ide><path>airflow/utils/dag_processing.py <ide> def end(self): <ide> self.log.info("Killing manager process: %s", manager_process.pid) <ide> manager_process.kill() <ide> manager_process.wait() <del> self._result_queue.join() <add> # TODO: bring it back once we replace process termination above with multiprocess-friendly <add> # way (https://issues.apache.org/jira/browse/AIRFLOW-4440) <add> # self._result_queue.join() <ide> self._manager.shutdown() <ide> <ide>
1
Java
Java
introduce reset() method in contextcache
2a4f4cd258967494ba41fba1ef48d98fedaf1e85
<ide><path>spring-test/src/main/java/org/springframework/test/context/ContextCache.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.util.Assert; <ide> <ide> /** <del> * Cache for Spring {@link ApplicationContext ApplicationContexts} in a test environment. <add> * Cache for Spring {@link ApplicationContext ApplicationContexts} in a test <add> * environment. <ide> * <del> * <p>Maintains a cache of {@code ApplicationContexts} keyed by <del> * {@link MergedContextConfiguration} instances. <add> * <p>{@code ContextCache} maintains a cache of {@code ApplicationContexts} <add> * keyed by {@link MergedContextConfiguration} instances. <ide> * <del> * <p>This has significant performance benefits if initializing the context would take time. <del> * While initializing a Spring context itself is very quick, some beans in a context, such <del> * as a {@code LocalSessionFactoryBean} for working with Hibernate, may take some time to <del> * initialize. Hence it often makes sense to perform that initialization only once per <del> * test suite. <add> * <p>Caching has significant performance benefits if initializing the context <add> * takes a considerable about of time. Although initializing a Spring context <add> * itself is very quick, some beans in a context, such as a <add> * {@code LocalSessionFactoryBean} for working with Hibernate, may take some <add> * time to initialize. Hence it often makes sense to perform that initialization <add> * only once per test suite. <ide> * <ide> * @author Sam Brannen <ide> * @author Juergen Hoeller <ide> class ContextCache { <ide> <ide> private final AtomicInteger missCount = new AtomicInteger(); <ide> <add> /** <add> * Reset all state maintained by this cache. <add> * @see #clear() <add> * @see #clearStatistics() <add> */ <add> public void reset() { <add> synchronized (contextMap) { <add> clear(); <add> clearStatistics(); <add> } <add> } <ide> <ide> /** <ide> * Clear all contexts from the cache and clear context hierarchy information as well. <ide> */ <ide> public void clear() { <del> this.contextMap.clear(); <del> this.hierarchyMap.clear(); <add> synchronized (contextMap) { <add> this.contextMap.clear(); <add> this.hierarchyMap.clear(); <add> } <ide> } <ide> <ide> /** <ide> * Clear hit and miss count statistics for the cache (i.e., reset counters to zero). <ide> */ <ide> public void clearStatistics() { <del> this.hitCount.set(0); <del> this.missCount.set(0); <add> synchronized (contextMap) { <add> this.hitCount.set(0); <add> this.missCount.set(0); <add> } <ide> } <ide> <ide> /** <ide> public ApplicationContext get(MergedContextConfiguration key) { <ide> <ide> /** <ide> * Get the overall hit count for this cache. <del> * <p>A <em>hit</em> is an access to the cache, which returned a non-null context <del> * for a queried key. <add> * <p>A <em>hit</em> is any access to the cache that returns a non-null <add> * context for the queried key. <ide> */ <ide> public int getHitCount() { <ide> return this.hitCount.get(); <ide> } <ide> <ide> /** <ide> * Get the overall miss count for this cache. <del> * <p>A <em>miss</em> is an access to the cache, which returned a {@code null} context <del> * for a queried key. <add> * <p>A <em>miss</em> is any access to the cache that returns a {@code null} <add> * context for the queried key. <ide> */ <ide> public int getMissCount() { <ide> return this.missCount.get(); <ide> } <ide> <ide> /** <del> * Explicitly add an {@code ApplicationContext} instance to the cache under the given key. <add> * Explicitly add an {@code ApplicationContext} instance to the cache <add> * under the given key. <ide> * @param key the context key (never {@code null}) <ide> * @param context the {@code ApplicationContext} instance (never {@code null}) <ide> */ <ide> public int getParentContextCount() { <ide> } <ide> <ide> /** <del> * Generate a text string, which contains the {@linkplain #size} as well <del> * as the {@linkplain #getHitCount() hit}, {@linkplain #getMissCount() miss}, <del> * and {@linkplain #getParentContextCount() parent context} counts. <add> * Generate a text string containing the statistics for this cache. <add> * <p>Specifically, the returned string contains the {@linkplain #size}, <add> * {@linkplain #getHitCount() hit count}, {@linkplain #getMissCount() miss count}, <add> * and {@linkplain #getParentContextCount() parent context count}. <add> * @return the statistics for this cache <ide> */ <ide> @Override <ide> public String toString() { <ide><path>spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTestNGTests.java <ide> private static final void runTestClassAndAssertStats(Class<?> testClass, int exp <ide> @BeforeClass <ide> public static void verifyInitialCacheState() { <ide> ContextCache contextCache = TestContextManager.contextCache; <del> contextCache.clear(); <del> contextCache.clearStatistics(); <add> contextCache.reset(); <ide> cacheHits.set(0); <ide> cacheMisses.set(0); <ide> assertContextCacheStatistics("BeforeClass", 0, cacheHits.get(), cacheMisses.get()); <ide><path>spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java <ide> private static final void runTestClassAndAssertStats(Class<?> testClass, int exp <ide> @BeforeClass <ide> public static void verifyInitialCacheState() { <ide> ContextCache contextCache = TestContextManager.contextCache; <del> contextCache.clear(); <del> contextCache.clearStatistics(); <add> contextCache.reset(); <ide> cacheHits.set(0); <ide> cacheMisses.set(0); <ide> assertContextCacheStatistics("BeforeClass", 0, cacheHits.get(), cacheMisses.get()); <ide><path>spring-test/src/test/java/org/springframework/test/context/SpringRunnerContextCacheTests.java <ide> public class SpringRunnerContextCacheTests { <ide> public static void verifyInitialCacheState() { <ide> dirtiedApplicationContext = null; <ide> ContextCache contextCache = TestContextManager.contextCache; <del> contextCache.clear(); <del> contextCache.clearStatistics(); <add> contextCache.reset(); <ide> assertContextCacheStatistics("BeforeClass", 0, 0, 0); <ide> } <ide>
4
Python
Python
add exception for tf + ntm
ef3ef71ee6836a69201f908c9ea907f08151bfef
<ide><path>keras/datasets/data_utils.py <ide> def get_file(fname, origin, untar=False): <ide> <ide> if not os.path.exists(fpath): <ide> print('Downloading data from', origin) <add> global progbar <ide> progbar = None <ide> <ide> def dl_progress(count, block_size, total_size): <ide><path>keras/layers/ntm.py <ide> import numpy as np <ide> from scipy.linalg import circulant <ide> <add>from .. import backend as K <ide> import theano <ide> import theano.tensor as T <ide> floatX = theano.config.floatX <ide> def __init__(self, output_dim, n_slots, m_length, shift_range=3, <ide> inner_rnn='gru', truncate_gradient=-1, return_sequences=False, <ide> init='glorot_uniform', inner_init='orthogonal', <ide> input_dim=None, input_length=None, **kwargs): <add> if K._BACKEND != 'theano': <add> raise Exception('NeuralTuringMachine is only available for Theano for the time being. ' + <add> 'It will be adapted to TensorFlow soon.') <ide> self.output_dim = output_dim <ide> self.n_slots = n_slots <ide> self.m_length = m_length
2
Python
Python
fix post_process_signature for floating point
b5612acd748b90dc5853cd11f357536a20dba1ec
<ide><path>docs/autogen.py <ide> def get_class_signature(cls): <ide> <ide> <ide> def post_process_signature(signature): <del> parts = signature.split('.') <add> parts = re.split('\.(?!\d)', signature) <ide> if len(parts) >= 4: <ide> if parts[1] == 'layers': <ide> signature = 'keras.layers.' + '.'.join(parts[3:])
1
Javascript
Javascript
remove unnecessary return values
3ed1f732211f6f6578014fd86f31978ad905ca82
<ide><path>client/gatsby-node.js <ide> exports.createPages = function createPages({ graphql, actions, reporter }) { <ide> } = edge; <ide> <ide> if (!fields) { <del> return null; <add> return; <ide> } <ide> const { slug, nodeIdentity } = fields; <ide> if (slug.includes('LICENCE')) { <del> return null; <add> return; <ide> } <ide> try { <ide> if (nodeIdentity === 'blockIntroMarkdown') { <del> if (!blocks.some(block => block === frontmatter.block)) { <del> return null; <add> if (!blocks.includes(frontmatter.block)) { <add> return; <ide> } <del> } else if ( <del> !superBlocks.some( <del> superBlock => superBlock === frontmatter.superBlock <del> ) <del> ) { <del> return null; <add> } else if (!superBlocks.includes(frontmatter.superBlock)) { <add> return; <ide> } <ide> const pageBuilder = createByIdentityMap[nodeIdentity](createPage); <del> return pageBuilder(edge); <add> pageBuilder(edge); <ide> } catch (e) { <ide> console.log(` <ide> ident: ${nodeIdentity} does not belong to a function <ide> exports.createPages = function createPages({ graphql, actions, reporter }) { <ide> <ide> `); <ide> } <del> return null; <ide> }); <ide> <ide> return null;
1
Ruby
Ruby
fix tests for explain plan + binds
91d3d00240a2f75c74664580398628207bb7d350
<ide><path>activerecord/test/cases/explain_test.rb <ide> def test_collecting_queries_for_explain <ide> <ide> sql, binds = queries[0] <ide> assert_match "SELECT", sql <del> assert_match "honda", sql <del> assert_equal [], binds <add> assert_equal "honda", binds.flatten.last <add> assert_equal 1, binds.length <ide> end <ide> <ide> def test_exec_explain_with_no_binds <ide><path>activerecord/test/cases/hot_compatibility_test.rb <ide> def self.name; 'HotCompatibility'; end <ide> end <ide> <ide> teardown do <del> @klass.connection.drop_table :hot_compatibilities <add> ActiveRecord::Base.connection.drop_table :hot_compatibilities <ide> end <ide> <ide> test "insert after remove_column" do
2
Python
Python
fix incorrect comment
dd84fc077eed7d7ac4bbc6c79d5acf3d111d21a0
<ide><path>numpy/core/arrayprint.py <ide> def __call__(self, x): <ide> i = self.imag_format(x.imag) <ide> return r + i + 'j' <ide> <del># for back-compatibility, we keep the classes for each float type too <add># for back-compatibility, we keep the classes for each complex type too <ide> class ComplexFormat(ComplexFloatingFormat): <ide> def __init__(self, *args, **kwargs): <ide> warnings.warn(
1
Javascript
Javascript
fix slow iterator for set
b9dabc177570d43dca5390a1b7c8da7fe5d053b9
<ide><path>src/Set.js <ide> export class Set extends SetCollection { <ide> // @pragma Modification <ide> <ide> add(value) { <del> return updateSet(this, this._map.set(value, true)); <add> return updateSet(this, this._map.set(value, value)); <ide> } <ide> <ide> remove(value) { <ide> export class Set extends SetCollection { <ide> } <ide> <ide> __iterate(fn, reverse) { <del> return this._map.__iterate((_, k) => fn(k, k, this), reverse); <add> return this._map.__iterate(k => fn(k, k, this), reverse); <ide> } <ide> <ide> __iterator(type, reverse) { <del> return this._map.map((_, k) => k).__iterator(type, reverse); <add> return this._map.__iterator(type, reverse); <ide> } <ide> <ide> __ensureOwner(ownerID) {
1
Javascript
Javascript
convert tab indent to spaces
4f45bf1a41cd69a01e76f81438877461a755872a
<ide><path>src/ngRoute/route.js <ide> function $RouteProvider(){ <ide> for (var i = 1, len = m.length; i < len; ++i) { <ide> var key = keys[i - 1]; <ide> <del> var val = m[i]; <add> var val = m[i]; <ide> <ide> if (key && val) { <ide> params[key.name] = val;
1
PHP
PHP
fix wildcard events
36668bfbe3b7de25cd3d27587024057c9e49b056
<ide><path>src/Illuminate/Events/Dispatcher.php <ide> class Dispatcher { <ide> */ <ide> protected $listeners = array(); <ide> <add> /** <add> * The wildcard listeners. <add> * <add> * @var array <add> */ <add> protected $wildcards = array(); <add> <ide> /** <ide> * The sorted event listeners. <ide> * <ide> public function listen($event, $listener, $priority = 0) <ide> */ <ide> protected function setupWildcardListen($event, $listener, $priority) <ide> { <del> foreach (array_keys($this->listeners) as $key) <del> { <del> if (str_is($event, $key)) $this->listen($key, $listener, $priority); <del> } <add> $this->wildcards[$event][] = $listener; <ide> } <ide> <ide> /** <ide> public function fire($event, $payload = array(), $halt = false) <ide> */ <ide> public function getListeners($eventName) <ide> { <add> $wildcards = $this->getWildcardListeners($eventName); <add> <ide> if ( ! isset($this->sorted[$eventName])) <ide> { <ide> $this->sortListeners($eventName); <ide> } <ide> <del> return $this->sorted[$eventName]; <add> return array_merge($this->sorted[$eventName], $wildcards); <add> } <add> <add> /** <add> * Get the wildcard listeners for the event. <add> * <add> * @param string $eventName <add> * @return array <add> */ <add> protected function getWildcardListeners($eventName) <add> { <add> $wildcards = array(); <add> <add> foreach ($this->wildcards as $key => $listeners) <add> { <add> if (str_is($key, $eventName)) $wildcards = array_merge($wildcards, $listeners); <add> } <add> <add> return $wildcards; <ide> } <ide> <ide> /**
1
PHP
PHP
follow redirects when fetching xml files
689745d7054fb7adae1b1f1faad99945c1a65521
<ide><path>lib/Cake/Utility/Xml.php <ide> public static function build($input, $options = array()) { <ide> } elseif (file_exists($input)) { <ide> return self::_loadXml(file_get_contents($input), $options); <ide> } elseif (strpos($input, 'http://') === 0 || strpos($input, 'https://') === 0) { <del> $socket = new HttpSocket(); <add> $socket = new HttpSocket(array('redirect' => 10)); <ide> $response = $socket->get($input); <ide> if (!$response->isOk()) { <ide> throw new XmlException(__d('cake_dev', 'XML cannot be read.'));
1
Java
Java
use the diamond syntax
c1d44d9a34a34dd657d113a6e0a45d4704628935
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/MethodOverrides.java <ide> */ <ide> public class MethodOverrides { <ide> <del> private final Set<MethodOverride> overrides = <del> Collections.synchronizedSet(new LinkedHashSet<MethodOverride>(0)); <add> private final Set<MethodOverride> overrides = Collections.synchronizedSet(new LinkedHashSet<>(0)); <ide> <ide> private volatile boolean modified = false; <ide> <ide><path>spring-context-indexer/src/main/java/org/springframework/context/index/MetadataCollector.java <ide> */ <ide> class MetadataCollector { <ide> <del> private final List<ItemMetadata> metadataItems = new ArrayList<ItemMetadata>(); <add> private final List<ItemMetadata> metadataItems = new ArrayList<>(); <ide> <ide> private final ProcessingEnvironment processingEnvironment; <ide> <ide> private final CandidateComponentsMetadata previousMetadata; <ide> <ide> private final TypeHelper typeHelper; <ide> <del> private final Set<String> processedSourceTypes = new HashSet<String>(); <add> private final Set<String> processedSourceTypes = new HashSet<>(); <ide> <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java <ide> public void stop() { <ide> } <ide> Collections.sort(this.members, Collections.reverseOrder()); <ide> CountDownLatch latch = new CountDownLatch(this.smartMemberCount); <del> Set<String> countDownBeanNames = Collections.synchronizedSet(new LinkedHashSet<String>()); <add> Set<String> countDownBeanNames = Collections.synchronizedSet(new LinkedHashSet<>()); <ide> for (LifecycleGroupMember member : this.members) { <ide> if (this.lifecycleBeans.containsKey(member.name)) { <ide> doStop(this.lifecycleBeans, member.name, latch, countDownBeanNames); <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/RowMapperResultSetExtractor.java <ide> public RowMapperResultSetExtractor(RowMapper<T> rowMapper, int rowsExpected) { <ide> <ide> @Override <ide> public List<T> extractData(ResultSet rs) throws SQLException { <del> List<T> results = (this.rowsExpected > 0 ? new ArrayList<>(this.rowsExpected) : new ArrayList<T>()); <add> List<T> results = (this.rowsExpected > 0 ? new ArrayList<>(this.rowsExpected) : new ArrayList<>()); <ide> int rowNum = 0; <ide> while (rs.next()) { <ide> results.add(this.rowMapper.mapRow(rs, rowNum++)); <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/AbstractMethodMessageHandler.java <ide> protected String getLookupDestination(@Nullable String destination) { <ide> } <ide> <ide> protected void handleMessageInternal(Message<?> message, String lookupDestination) { <del> List<Match> matches = new ArrayList<Match>(); <add> List<Match> matches = new ArrayList<>(); <ide> <ide> List<T> mappingsByUrl = this.destinationLookup.get(lookupDestination); <ide> if (mappingsByUrl != null) { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/BufferingStompDecoder.java <ide> public class BufferingStompDecoder { <ide> <ide> private final int bufferSizeLimit; <ide> <del> private final Queue<ByteBuffer> chunks = new LinkedBlockingQueue<ByteBuffer>(); <add> private final Queue<ByteBuffer> chunks = new LinkedBlockingQueue<>(); <ide> <ide> private volatile Integer expectedContentLength; <ide> <ide> public List<Message<byte[]>> decode(ByteBuffer newBuffer) { <ide> } <ide> <ide> ByteBuffer bufferToDecode = assembleChunksAndReset(); <del> MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>(); <add> MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); <ide> List<Message<byte[]>> messages = this.stompDecoder.decode(bufferToDecode, headers); <ide> <ide> if (bufferToDecode.hasRemaining()) { <ide><path>spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java <ide> public void setup() { <ide> <ide> @Test <ide> public void receive() { <del> Message<?> expected = new GenericMessage<Object>("payload"); <add> Message<?> expected = new GenericMessage<>("payload"); <ide> this.template.setDefaultDestination("home"); <ide> this.template.setReceiveMessage(expected); <ide> Message<?> actual = this.template.receive(); <ide> public void receiveMissingDefaultDestination() { <ide> <ide> @Test <ide> public void receiveFromDestination() { <del> Message<?> expected = new GenericMessage<Object>("payload"); <add> Message<?> expected = new GenericMessage<>("payload"); <ide> this.template.setReceiveMessage(expected); <ide> Message<?> actual = this.template.receive("somewhere"); <ide> <ide> public void receiveFromDestination() { <ide> <ide> @Test <ide> public void receiveAndConvert() { <del> Message<?> expected = new GenericMessage<Object>("payload"); <add> Message<?> expected = new GenericMessage<>("payload"); <ide> this.template.setDefaultDestination("home"); <ide> this.template.setReceiveMessage(expected); <ide> String payload = this.template.receiveAndConvert(String.class); <ide> public void receiveAndConvert() { <ide> <ide> @Test <ide> public void receiveAndConvertFromDestination() { <del> Message<?> expected = new GenericMessage<Object>("payload"); <add> Message<?> expected = new GenericMessage<>("payload"); <ide> this.template.setReceiveMessage(expected); <ide> String payload = this.template.receiveAndConvert("somewhere", String.class); <ide> <ide> public void receiveAndConvertFromDestination() { <ide> <ide> @Test <ide> public void receiveAndConvertFailed() { <del> Message<?> expected = new GenericMessage<Object>("not a number test"); <add> Message<?> expected = new GenericMessage<>("not a number test"); <ide> this.template.setReceiveMessage(expected); <ide> this.template.setMessageConverter(new GenericMessageConverter()); <ide> <ide> public void receiveAndConvertFailed() { <ide> <ide> @Test <ide> public void receiveAndConvertNoConverter() { <del> Message<?> expected = new GenericMessage<Object>("payload"); <add> Message<?> expected = new GenericMessage<>("payload"); <ide> this.template.setDefaultDestination("home"); <ide> this.template.setReceiveMessage(expected); <ide> this.template.setMessageConverter(new GenericMessageConverter()); <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java <ide> public MockHttpServletRequestBuilder accept(MediaType... mediaTypes) { <ide> */ <ide> public MockHttpServletRequestBuilder accept(String... mediaTypes) { <ide> Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty"); <del> List<MediaType> result = new ArrayList<MediaType>(mediaTypes.length); <add> List<MediaType> result = new ArrayList<>(mediaTypes.length); <ide> for (String mediaType : mediaTypes) { <ide> result.add(MediaType.parseMediaType(mediaType)); <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/filter/CompositeFilter.java <ide> public class CompositeFilter implements Filter { <ide> <ide> <ide> public void setFilters(List<? extends Filter> filters) { <del> this.filters = new ArrayList<Filter>(filters); <add> this.filters = new ArrayList<>(filters); <ide> } <ide> <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultRenderingResponseBuilder.java <ide> class DefaultRenderingResponseBuilder implements RenderingResponse.Builder { <ide> <ide> private final HttpHeaders headers = new HttpHeaders(); <ide> <del> private final Map<String, Object> model = new LinkedHashMap<String, Object>(); <add> private final Map<String, Object> model = new LinkedHashMap<>(); <ide> <ide> <ide> public DefaultRenderingResponseBuilder(String name) { <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/HeadersRequestCondition.java <ide> private HeadersRequestCondition(Collection<HeaderExpression> conditions) { <ide> <ide> <ide> private static Collection<HeaderExpression> parseExpressions(String... headers) { <del> Set<HeaderExpression> expressions = new LinkedHashSet<HeaderExpression>(); <add> Set<HeaderExpression> expressions = new LinkedHashSet<>(); <ide> if (headers != null) { <ide> for (String header : headers) { <ide> HeaderExpression expr = new HeaderExpression(header); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java <ide> public Mono<HandlerMethod> getHandlerInternal(ServerWebExchange exchange) { <ide> protected HandlerMethod lookupHandlerMethod(String lookupPath, ServerWebExchange exchange) <ide> throws Exception { <ide> <del> List<Match> matches = new ArrayList<Match>(); <add> List<Match> matches = new ArrayList<>(); <ide> List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath); <ide> if (directPathMatches != null) { <ide> addMatchingMappings(directPathMatches, matches, exchange); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerComposite.java <ide> */ <ide> class WebMvcConfigurerComposite implements WebMvcConfigurer { <ide> <del> private final List<WebMvcConfigurer> delegates = new ArrayList<WebMvcConfigurer>(); <add> private final List<WebMvcConfigurer> delegates = new ArrayList<>(); <ide> <ide> <ide> public void addWebMvcConfigurers(List<WebMvcConfigurer> configurers) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java <ide> protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Ex <ide> */ <ide> @Nullable <ide> protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception { <del> List<Match> matches = new ArrayList<Match>(); <add> List<Match> matches = new ArrayList<>(); <ide> List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath); <ide> if (directPathMatches != null) { <ide> addMatchingMappings(directPathMatches, matches, request); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketExtension.java <ide> public String toString() { <ide> public static List<WebSocketExtension> parseExtensions(String extensions) { <ide> if (StringUtils.hasText(extensions)) { <ide> String[] tokens = StringUtils.tokenizeToStringArray(extensions, ","); <del> List<WebSocketExtension> result = new ArrayList<WebSocketExtension>(tokens.length); <add> List<WebSocketExtension> result = new ArrayList<>(tokens.length); <ide> for (String token : tokens) { <ide> result.add(parseExtension(token)); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java <ide> public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE <ide> <ide> private MessageHeaderInitializer headerInitializer; <ide> <del> private final Map<String, Principal> stompAuthentications = new ConcurrentHashMap<String, Principal>(); <add> private final Map<String, Principal> stompAuthentications = new ConcurrentHashMap<>(); <ide> <ide> private Boolean immutableMessageInterceptorPresent; <ide>
16
Javascript
Javascript
remove old seed code
912e7a5c2f179b4a9526045c7450a3d5b799574b
<ide><path>curriculum/index.js <del>/* eslint-disable no-process-exit */ <del>require('babel-register'); <del>require('dotenv').load(); <del>const adler32 = require('adler32'); <del> <del>const Rx = require('rx'); <del>const _ = require('lodash'); <del>const createDebugger = require('debug'); <del>const { dasherize, nameify } = require('../utils/slugs'); <del>const getChallenges = require('./getChallenges'); <del>const { validateChallenge } = require('./schema/challengeSchema'); <del>const app = require('../server/server'); <del> <del>const log = createDebugger('fcc:seed'); <del>// force logger to always output <del>// this may be brittle <del>log.enabled = true; <del> <del>const Observable = Rx.Observable; <del>const Challenge = app.models.Challenge; <del> <del>const destroyChallenges = Observable.fromNodeCallback( <del> Challenge.destroyAll, <del> Challenge <del>); <del>const createChallenges = Observable.fromNodeCallback( <del> Challenge.create, <del> Challenge <del>); <del> <del>const Block = app.models.Block; <del>const destroyBlocks = Observable.fromNodeCallback(Block.destroyAll, Block); <del>const createBlocks = Observable.fromNodeCallback(Block.create, Block); <del>const arrToString = arr => <del> Array.isArray(arr) ? arr.join('\n') : _.toString(arr); <del> <del>Observable.combineLatest(destroyChallenges(), destroyBlocks()) <del> .last() <del> .flatMap(function() { <del> return Observable.from(getChallenges()); <del> }) <del> .flatMap(function(challengeSpec) { <del> const order = challengeSpec.order; <del> const blockName = challengeSpec.name; <del> const superBlock = challengeSpec.superBlock; <del> const superOrder = challengeSpec.superOrder; <del> const isBeta = !!challengeSpec.isBeta; <del> const isComingSoon = !!challengeSpec.isComingSoon; <del> const fileName = challengeSpec.fileName; <del> const helpRoom = challengeSpec.helpRoom || 'Help'; <del> const time = challengeSpec.time; <del> const isLocked = !!challengeSpec.isLocked; <del> const message = challengeSpec.message; <del> const required = challengeSpec.required || []; <del> const template = challengeSpec.template; <del> const isPrivate = !!challengeSpec.isPrivate; <del> <del> log('parsed %s successfully', blockName); <del> <del> // challenge file has no challenges... <del> if (challengeSpec.challenges.length === 0) { <del> return Rx.Observable.just([{ block: 'empty ' + blockName }]); <del> } <del> <del> const block = { <del> title: blockName, <del> name: nameify(blockName), <del> dashedName: dasherize(blockName), <del> superOrder, <del> superBlock, <del> superBlockMessage: message, <del> order, <del> time, <del> isLocked, <del> isPrivate <del> }; <del> <del> return createBlocks(block) <del> .map(block => { <del> log('successfully created %s block', block.name); <del> <del> return challengeSpec.challenges.map(function(challenge, index) { <del> challenge.name = nameify(challenge.title); <del> <del> challenge.dashedName = dasherize(challenge.name); <del> <del> challenge.checksum = adler32.sum( <del> Buffer( <del> challenge.title + <del> JSON.stringify(challenge.description) + <del> JSON.stringify(challenge.challengeSeed) + <del> JSON.stringify(challenge.tests) <del> ) <del> ); <del> <del> if (challenge.files) { <del> challenge.files = _.reduce( <del> challenge.files, <del> (map, file) => { <del> map[file.key] = { <del> ...file, <del> head: arrToString(file.head), <del> contents: arrToString(file.contents), <del> tail: arrToString(file.tail) <del> }; <del> return map; <del> }, <del> {} <del> ); <del> } <del> challenge.fileName = fileName; <del> challenge.helpRoom = helpRoom; <del> challenge.order = order; <del> challenge.suborder = index + 1; <del> challenge.block = dasherize(blockName); <del> challenge.blockId = '' + block.id; <del> challenge.isBeta = challenge.isBeta || isBeta; <del> challenge.isComingSoon = challenge.isComingSoon || isComingSoon; <del> challenge.isLocked = challenge.isLocked || isLocked; <del> challenge.isPrivate = challenge.isPrivate || isPrivate; <del> challenge.time = challengeSpec.time; <del> challenge.superOrder = superOrder; <del> challenge.superBlock = superBlock <del> .split('-') <del> .map(function(word) { <del> return _.capitalize(word); <del> }) <del> .join(' '); <del> challenge.required = (challenge.required || []).concat(required); <del> challenge.template = challenge.template || template; <del> return _.omit(challenge, [ <del> 'betaSolutions', <del> 'betaTests', <del> 'hints', <del> 'MDNlinks', <del> 'null', <del> 'rawSolutions', <del> 'react', <del> 'reactRedux', <del> 'redux', <del> 'releasedOn', <del> 'translations', <del> 'type' <del> ]); <del> }); <del> }) <del> .flatMap(challenges => { <del> challenges.forEach(challenge => { <del> const result = validateChallenge(challenge); <del> if (result.error) { <del> console.log(result.value); <del> throw new Error(result.error); <del> } <del> }); <del> return createChallenges(challenges); <del> }); <del> }) <del> .subscribe( <del> function(challenges) { <del> log('%s successfully saved', challenges[0].block); <del> }, <del> function(err) { <del> throw err; <del> }, <del> function() { <del> log('challenge seed completed'); <del> process.exit(0); <del> } <del> );
1
Text
Text
correct apm command
5091efab8ef2902553a217769435dae610ce011a
<ide><path>docs/proposals/private-beta-tasks.md <ide> package authors about breaking API changes. <ide> <ide> * Finish APM backend (integrate with GitHub Releases) <ide> * Streamline Dev workflow <del> * `api create` - create package scaffolding <add> * `apm create` - create package scaffolding <ide> * `apm test` - so users can run focused package tests <ide> * `apm publish` - should integrate release best practices (ie npm version) <ide> * Determine which classes and methods should be included in the public API
1
Ruby
Ruby
fix undefined method error on exception
f48dc782167fea0a1f13759ed6596a004dd746f3
<ide><path>activerecord/lib/active_record/tasks/mysql_database_tasks.rb <ide> def create <ide> end <ide> rescue error_class => error <ide> if error.respond_to?(:errno) && error.errno == ACCESS_DENIED_ERROR <del> $stdout.print error.error <add> $stdout.print error.message <ide> establish_connection root_configuration_without_database <ide> connection.create_database configuration['database'], creation_options <ide> if configuration['username'] != 'root'
1
Javascript
Javascript
update route-recognizer with wildcard fixes
a5d45f66e1f71bb5eda417c688db0ea08b474903
<ide><path>packages/ember-routing/lib/vendor/route-recognizer.js <ide> define("route-recognizer", <ide> <ide> charSpec = child.charSpec; <ide> <del> if (chars = charSpec.validChars) { <add> if (typeof (chars = charSpec.validChars) !== 'undefined') { <ide> if (chars.indexOf(char) !== -1) { returned.push(child); } <del> } else if (chars = charSpec.invalidChars) { <add> } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { <ide> if (chars.indexOf(char) === -1) { returned.push(child); } <ide> } <ide> }
1
Text
Text
update changelog.md for readability
8e86d161dfba57c8d77a701d92debf19b850c601
<ide><path>actionview/CHANGELOG.md <ide> <ide> *Bernerd Schaefer* <ide> <del>* `number_to_currency` and `number_with_delimiter` now accept custom `delimiter_pattern` option <add>* `number_to_currency` and `number_with_delimiter` now accepts acustom `delimiter_pattern` option <ide> to handle placement of delimiter, to support currency formats like INR <ide> <ide> Example:
1
Text
Text
improve readability of cachehelper section
34f5704b8561571c0992b4f1dacff30aacb0e249
<ide><path>guides/source/action_view_overview.md <ide> This would add something like "Process data files (0.34523)" to the log, which y <ide> <ide> #### cache <ide> <del>A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See `ActionController::Caching::Fragments` for more information. <add>A method for caching fragments of a view rather than an entire action or page. This technique is useful for caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See `ActionController::Caching::Fragments` for more information. <ide> <ide> ```erb <ide> <% cache do %>
1
Text
Text
add benchmarking tutorial
4c6fec902fcaaebd70716e429fb37914d48f735f
<ide><path>docs/docs/addons-perf.md <ide> React is usually quite fast out of the box. However, in situations where you nee <ide> <ide> In addition to giving you an overview of your app's overall performance, `Perf` is a profiling tool that tells you exactly where you need to put these hooks. <ide> <del>See these articles by the [Benchling Engineering Team](http://benchling.engineering) for a in-depth introduction to performance tooling: <add>See these articles for an introduction to React performance tooling: <ide> <add> - ["How to Benchmark React Components"](https://medium.com/code-life/how-to-benchmark-react-components-the-quick-and-dirty-guide-f595baf1014c) <ide> - ["Performance Engineering with React"](http://benchling.engineering/performance-engineering-with-react/) <del> - ["A Deep Dive into React Perf Debugging"](http://benchling.engineering/deep-dive-react-perf-debugging/) <add> - ["A Deep Dive into React Perf Debugging"](http://benchling.engineering/deep-dive-react-perf-debugging/) <ide> <ide> ### Development vs. Production Builds <ide>
1
Mixed
Javascript
change android permission module to use promises
6df41d518434c22105930462085efe26b65dc328
<ide><path>Libraries/PermissionsAndroid/PermissionsAndroid.js <ide> 'use strict'; <ide> <ide> const DialogManagerAndroid = require('NativeModules').DialogManagerAndroid; <del>const AndroidPermissions = require('NativeModules').AndroidPermissions; <add>const Permissions = require('NativeModules').PermissionsAndroid; <ide> <ide> type Rationale = { <del> title: string, <del> message: string, <add> title: string; <add> message: string; <ide> } <ide> <ide> /** <ide> class PermissionsAndroid { <ide> * permissions has been granted <ide> */ <ide> checkPermission(permission: string) : Promise<boolean> { <del> return new Promise((resolve, reject) => { <del> AndroidPermissions.checkPermission( <del> permission, <del> function(perm: string, result: boolean) { resolve(result); }, <del> function(error: string) { reject(error); }, <del> ); <del> }); <add> return Permissions.checkPermission(permission); <ide> } <ide> <ide> /** <ide> class PermissionsAndroid { <ide> * (https://developer.android.com/training/permissions/requesting.html#explain) <ide> * and then shows the system permission dialog <ide> */ <del> requestPermission(permission: string, rationale?: Rationale) : Promise<boolean> { <del> return new Promise((resolve, reject) => { <del> const requestPermission = () => { <del> AndroidPermissions.requestPermission( <del> permission, <del> function(perm: string, result: boolean) { resolve(result); }, <del> function(error: string) { reject(error); }, <del> ); <del> }; <add> async requestPermission(permission: string, rationale?: Rationale) : Promise<boolean> { <add> if (rationale) { <add> const shouldShowRationale = await Permissions.shouldShowRequestPermissionRationale(permission); <ide> <del> if (rationale) { <del> AndroidPermissions.shouldShowRequestPermissionRationale( <del> permission, <del> function(perm: string, shouldShowRationale: boolean) { <del> if (shouldShowRationale) { <del> DialogManagerAndroid.showAlert( <del> rationale, <del> () => { <del> DialogManagerAndroid.showAlert({ <del> message: 'Error Requesting Permissions' <del> }, {}, {}); <del> reject(); <del> }, <del> requestPermission <del> ); <del> } else { <del> requestPermission(); <del> } <del> }, <del> function(error: string) { reject(error); }, <del> ); <del> } else { <del> requestPermission(); <add> if (shouldShowRationale) { <add> return new Promise((resolve, reject) => { <add> DialogManagerAndroid.showAlert( <add> rationale, <add> () => reject(new Error('Error showing rationale')), <add> () => resolve(Permissions.requestPermission(permission)) <add> ); <add> }); <ide> } <del> }); <add> } <add> return Permissions.requestPermission(permission); <ide> } <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/permissions/PermissionsModule.java <ide> import android.util.SparseArray; <ide> <ide> import com.facebook.react.bridge.Callback; <add>import com.facebook.react.bridge.Promise; <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> import com.facebook.react.bridge.ReactContextBaseJavaModule; <ide> import com.facebook.react.bridge.ReactMethod; <ide> public PermissionsModule(ReactApplicationContext reactContext) { <ide> <ide> @Override <ide> public String getName() { <del> return "AndroidPermissions"; <add> return "PermissionsAndroid"; <ide> } <ide> <ide> /** <ide> * Check if the app has the permission given. successCallback is called with true if the <ide> * permission had been granted, false otherwise. See {@link Activity#checkSelfPermission}. <ide> */ <ide> @ReactMethod <del> public void checkPermission( <del> final String permission, <del> final Callback successCallback, <del> final Callback errorCallback) { <add> public void checkPermission(final String permission, final Promise promise) { <ide> PermissionAwareActivity activity = getPermissionAwareActivity(); <ide> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { <del> successCallback.invoke( <del> permission, <del> activity.checkPermission(permission, Process.myPid(), Process.myUid()) == <del> PackageManager.PERMISSION_GRANTED); <add> promise.resolve(activity.checkPermission(permission, Process.myPid(), Process.myUid()) == <add> PackageManager.PERMISSION_GRANTED); <ide> return; <ide> } <del> successCallback.invoke( <del> permission, <del> activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED); <add> promise.resolve(activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED); <ide> } <ide> <ide> /** <ide> public void checkPermission( <ide> * See {@link Activity#shouldShowRequestPermissionRationale}. <ide> */ <ide> @ReactMethod <del> public void shouldShowRequestPermissionRationale( <del> final String permission, <del> final Callback successCallback, <del> final Callback errorCallback) { <add> public void shouldShowRequestPermissionRationale(final String permission, final Promise promise) { <ide> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { <del> successCallback.invoke(permission, false); <add> promise.resolve(false); <ide> return; <ide> } <del> successCallback.invoke( <del> permission, <del> getPermissionAwareActivity().shouldShowRequestPermissionRationale(permission)); <add> promise.resolve(getPermissionAwareActivity().shouldShowRequestPermissionRationale(permission)); <ide> } <ide> <ide> /** <ide> public void shouldShowRequestPermissionRationale( <ide> * See {@link Activity#checkSelfPermission}. <ide> */ <ide> @ReactMethod <del> public void requestPermission( <del> final String permission, <del> final Callback successCallback, <del> final Callback errorCallback) { <add> public void requestPermission(final String permission, final Promise promise) { <ide> PermissionAwareActivity activity = getPermissionAwareActivity(); <ide> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { <del> successCallback.invoke( <del> permission, <del> activity.checkPermission(permission, Process.myPid(), Process.myUid()) == <add> promise.resolve(activity.checkPermission(permission, Process.myPid(), Process.myUid()) == <ide> PackageManager.PERMISSION_GRANTED); <ide> return; <ide> } <ide> if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) { <del> successCallback.invoke(permission, true); <add> promise.resolve(true); <ide> return; <ide> } <ide> <ide> mCallbacks.put( <ide> mRequestCode, new Callback() { <ide> @Override <ide> public void invoke(Object... args) { <del> successCallback.invoke(permission, args[0].equals(PackageManager.PERMISSION_GRANTED)); <add> promise.resolve(args[0].equals(PackageManager.PERMISSION_GRANTED)); <ide> } <ide> }); <ide>
2
Ruby
Ruby
remove test with too much implementation knowledge
662560e40d347b996efe85313f9be1f852a31fd3
<ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_class_naming <ide> assert_equal 'FooBar', Formula.class_s('foo_bar') <ide> end <ide> <del> def test_mirror_support <del> f = Class.new(Formula) do <del> url "file:///#{TEST_FOLDER}/bad_url/testball-0.1.tbz" <del> mirror "file:///#{TEST_FOLDER}/tarballs/testball-0.1.tbz" <del> end.new("test_mirror_support") <del> <del> shutup { f.fetch } <del> <del> assert_equal "file:///#{TEST_FOLDER}/bad_url/testball-0.1.tbz", f.url <del> assert_equal "file:///#{TEST_FOLDER}/tarballs/testball-0.1.tbz", <del> f.downloader.instance_variable_get(:@url) <del> end <del> <ide> def test_formula_spec_integration <ide> f = Class.new(Formula) do <ide> homepage 'http://example.com'
1
Go
Go
do nothing in bulksync if nodes is empty
af3158ecdb75d907df621a9f99cb491cf5b80f6f
<ide><path>libnetwork/networkdb/cluster.go <ide> func (nDB *NetworkDB) bulkSync(nid string, nodes []string, all bool) ([]string, <ide> nodes = nDB.mRandomNodes(1, nodes) <ide> } <ide> <add> if len(nodes) == 0 { <add> return nil, nil <add> } <add> <ide> logrus.Debugf("%s: Initiating bulk sync with nodes %v", nDB.config.NodeName, nodes) <ide> var err error <ide> var networks []string
1
Javascript
Javascript
move concat into hooks module
cb7d7cd80b05a6db36974f55894e4e7015148de6
<ide><path>packages/ember-htmlbars/lib/attr_nodes/concat.js <ide> */ <ide> <ide> import SimpleAttrNode from "./simple"; <del>import concat from "ember-htmlbars/system/concat"; <ide> import { create as o_create } from "ember-metal/platform"; <ide> <ide> function ConcatAttrNode(element, attrName, attrValue, dom) { <add><path>packages/ember-htmlbars/lib/hooks/concat.js <del><path>packages/ember-htmlbars/lib/system/concat.js <ide> import Stream from "ember-metal/streams/stream"; <ide> import {readArray} from "ember-metal/streams/utils"; <ide> <add>// TODO: Create subclass ConcatStream < Stream. Defer <add>// subscribing to streams until the value() is called. <ide> export default function concat(params) { <ide> var stream = new Stream(function() { <ide> return readArray(params).join(''); <ide><path>packages/ember-htmlbars/lib/main.js <ide> import component from "ember-htmlbars/hooks/component"; <ide> import element from "ember-htmlbars/hooks/element"; <ide> import subexpr from "ember-htmlbars/hooks/subexpr"; <ide> import attribute from "ember-htmlbars/hooks/attribute"; <add>import concat from "ember-htmlbars/hooks/concat"; <ide> import get from "ember-htmlbars/hooks/get"; <ide> import set from "ember-htmlbars/hooks/set"; <ide> import { DOMHelper } from "morph"; <ide> import { <ide> helper, <ide> default as helpers <ide> } from "ember-htmlbars/helpers"; <del>import concat from "ember-htmlbars/system/concat"; <ide> import { bindHelper } from "ember-htmlbars/helpers/binding"; <ide> import { viewHelper } from "ember-htmlbars/helpers/view"; <ide> import { yieldHelper } from "ember-htmlbars/helpers/yield";
3
Javascript
Javascript
replace the atomapplication test suite
c4f3b519d3801a0037422a7f3b8b921c23d9b2d6
<ide><path>spec/main-process/atom-application.new.test.js <del>/* globals assert */ <del> <del>const path = require('path') <del>const {EventEmitter} = require('events') <del>const temp = require('temp').track() <del>const fs = require('fs-plus') <del>const electron = require('electron') <del>const {sandbox} = require('sinon') <del> <del>const AtomApplication = require('../../src/main-process/atom-application') <del>const parseCommandLine = require('../../src/main-process/parse-command-line') <del>const {emitterEventPromise, conditionPromise} = require('../async-spec-helpers') <del> <del>describe('AtomApplication', function () { <del> let scenario, sinon <del> <del> beforeEach(async function () { <del> sinon = sandbox.create() <del> scenario = await LaunchScenario.create(sinon) <del> }) <del> <del> afterEach(async function () { <del> await scenario.destroy() <del> sinon.restore() <del> }) <del> <del> describe('command-line interface behavior', function () { <del> describe('with no open windows', function () { <del> // This is also the case when a user clicks on a file in their file manager <del> it('opens a file', async function () { <del> await scenario.open(parseCommandLine(['a/1.md'])) <del> await scenario.assert('[_ 1.md]') <del> }) <del> <del> // This is also the case when a user clicks on a folder in their file manager <del> // (or, on macOS, drags the folder to Atom in their doc) <del> it('opens a directory', async function () { <del> await scenario.open(parseCommandLine(['a'])) <del> await scenario.assert('[a _]') <del> }) <del> <del> it('opens a file with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <del> await scenario.assert('[_ 1.md]') <del> }) <del> <del> it('opens a directory with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a'])) <del> await scenario.assert('[a _]') <del> }) <del> <del> it('opens a file with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <del> await scenario.assert('[_ 1.md]') <del> }) <del> <del> it('opens a directory with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a'])) <del> await scenario.assert('[a _]') <del> }) <del> <del> describe('with previous window state', function () { <del> let app <del> <del> beforeEach(function () { <del> app = scenario.addApplication({ <del> applicationJson: [ <del> { initialPaths: ['b'] }, <del> { initialPaths: ['c'] } <del> ] <del> }) <del> }) <del> <del> describe('with core.restorePreviousWindowsOnStart set to "no"', function () { <del> beforeEach(function () { <del> app.config.set('core.restorePreviousWindowsOnStart', 'no') <del> }) <del> <del> it("doesn't restore windows when launched with no arguments", async function () { <del> await scenario.launch({app}) <del> await scenario.assert('[_ _]') <del> }) <del> <del> it("doesn't restore windows when launched with paths to open", async function () { <del> await scenario.launch({app, pathsToOpen: ['a/1.md']}) <del> await scenario.assert('[_ 1.md]') <del> }) <del> <del> it("doesn't restore windows when --new-window is provided", async function () { <del> await scenario.launch({app, newWindow: true}) <del> await scenario.assert('[_ _]') <del> }) <del> }) <del> <del> describe('with core.restorePreviousWindowsOnStart set to "yes"', function () { <del> beforeEach(function () { <del> app.config.set('core.restorePreviousWindowsOnStart', 'yes') <del> }) <del> <del> it('restores windows when launched with no arguments', async function () { <del> await scenario.launch({app}) <del> await scenario.assert('[b _] [c _]') <del> }) <del> <del> it("doesn't restore windows when launched with paths to open", async function () { <del> await scenario.launch({app, pathsToOpen: ['a/1.md']}) <del> await scenario.assert('[_ 1.md]') <del> }) <del> <del> it("doesn't restore windows when --new-window is provided", async function () { <del> await scenario.launch({app, newWindow: true}) <del> await scenario.assert('[_ _]') <del> }) <del> }) <del> <del> describe('with core.restorePreviousWindowsOnStart set to "always"', function () { <del> beforeEach(function () { <del> app.config.set('core.restorePreviousWindowsOnStart', 'always') <del> }) <del> <del> it('restores windows when launched with no arguments', async function () { <del> await scenario.launch({app}) <del> await scenario.assert('[b _] [c _]') <del> }) <del> <del> it('restores windows when launched with paths to open', async function () { <del> await scenario.launch({app, pathsToOpen: ['a']}) <del> await scenario.assert('[a _] [b _] [c _]') <del> }) <del> <del> it('collapses new paths into restored windows when appropriate', async function () { <del> await scenario.launch({app, pathsToOpen: ['b/2.md']}) <del> await scenario.assert('[b 2.md] [c _]') <del> }) <del> <del> it("doesn't restore windows when --new-window is provided", async function () { <del> await scenario.launch({app, newWindow: true}) <del> await scenario.assert('[_ _]') <del> }) <del> <del> it("doesn't restore windows on open, just launch", async function () { <del> await scenario.launch({app, pathsToOpen: ['a'], newWindow: true}) <del> await scenario.open(parseCommandLine(['b'])) <del> await scenario.assert('[a _] [b _]') <del> }) <del> }) <del> }) <del> }) <del> <del> describe('with one empty window', function () { <del> beforeEach(async function () { <del> await scenario.preconditions('[_ _]') <del> }) <del> <del> // This is also the case when a user clicks on a file in their file manager <del> it('opens a file', async function () { <del> await scenario.open(parseCommandLine(['a/1.md'])) <del> await scenario.assert('[_ 1.md]') <del> }) <del> <del> // This is also the case when a user clicks on a folder in their file manager <del> it('opens a directory', async function () { <del> await scenario.open(parseCommandLine(['a'])) <del> await scenario.assert('[a _]') <del> }) <del> <del> it('opens a file with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <del> await scenario.assert('[_ 1.md]') <del> }) <del> <del> it('opens a directory with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a'])) <del> await scenario.assert('[a _]') <del> }) <del> <del> it('opens a file with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <del> await scenario.assert('[_ _] [_ 1.md]') <del> }) <del> <del> it('opens a directory with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a'])) <del> await scenario.assert('[_ _] [a _]') <del> }) <del> }) <del> <del> describe('with one window that has a project root', function () { <del> beforeEach(async function () { <del> await scenario.preconditions('[a _]') <del> }) <del> <del> // This is also the case when a user clicks on a file within the project root in their file manager <del> it('opens a file within the project root', async function () { <del> await scenario.open(parseCommandLine(['a/1.md'])) <del> await scenario.assert('[a 1.md]') <del> }) <del> <del> // This is also the case when a user clicks on a project root folder in their file manager <del> it('opens a directory that matches the project root', async function () { <del> await scenario.open(parseCommandLine(['a'])) <del> await scenario.assert('[a _]') <del> }) <del> <del> // This is also the case when a user clicks on a file outside the project root in their file manager <del> it('opens a file outside the project root', async function () { <del> await scenario.open(parseCommandLine(['b/2.md'])) <del> await scenario.assert('[a 2.md]') <del> }) <del> <del> // This is also the case when a user clicks on a new folder in their file manager <del> it('opens a directory other than the project root', async function () { <del> await scenario.open(parseCommandLine(['b'])) <del> await scenario.assert('[a _] [b _]') <del> }) <del> <del> it('opens a file within the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <del> await scenario.assert('[a 1.md]') <del> }) <del> <del> it('opens a directory that matches the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a'])) <del> await scenario.assert('[a _]') <del> }) <del> <del> it('opens a file outside the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'b/2.md'])) <del> await scenario.assert('[a 2.md]') <del> }) <del> <del> it('opens a directory other than the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'b'])) <del> await scenario.assert('[a,b _]') <del> }) <del> <del> it('opens a file within the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <del> await scenario.assert('[a _] [_ 1.md]') <del> }) <del> <del> it('opens a directory that matches the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a'])) <del> await scenario.assert('[a _] [a _]') <del> }) <del> <del> it('opens a file outside the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'b/2.md'])) <del> await scenario.assert('[a _] [_ 2.md]') <del> }) <del> <del> it('opens a directory other than the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'b'])) <del> await scenario.assert('[a _] [b _]') <del> }) <del> }) <del> <del> describe('with two windows, one with a project root and one empty', function () { <del> beforeEach(async function () { <del> await scenario.preconditions('[a _] [_ _]') <del> }) <del> <del> // This is also the case when a user clicks on a file within the project root in their file manager <del> it('opens a file within the project root', async function () { <del> await scenario.open(parseCommandLine(['a/1.md'])) <del> await scenario.assert('[a 1.md] [_ _]') <del> }) <del> <del> // This is also the case when a user clicks on a project root folder in their file manager <del> it('opens a directory that matches the project root', async function () { <del> await scenario.open(parseCommandLine(['a'])) <del> await scenario.assert('[a _] [_ _]') <del> }) <del> <del> // This is also the case when a user clicks on a file outside the project root in their file manager <del> it('opens a file outside the project root', async function () { <del> await scenario.open(parseCommandLine(['b/2.md'])) <del> await scenario.assert('[a _] [_ 2.md]') <del> }) <del> <del> // This is also the case when a user clicks on a new folder in their file manager <del> it('opens a directory other than the project root', async function () { <del> await scenario.open(parseCommandLine(['b'])) <del> await scenario.assert('[a _] [b _]') <del> }) <del> <del> it('opens a file within the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <del> await scenario.assert('[a 1.md] [_ _]') <del> }) <del> <del> it('opens a directory that matches the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a'])) <del> await scenario.assert('[a _] [_ _]') <del> }) <del> <del> it('opens a file outside the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'b/2.md'])) <del> await scenario.assert('[a _] [_ 2.md]') <del> }) <del> <del> it('opens a directory other than the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'b'])) <del> await scenario.assert('[a _] [b _]') <del> }) <del> <del> it('opens a file within the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <del> await scenario.assert('[a _] [_ _] [_ 1.md]') <del> }) <del> <del> it('opens a directory that matches the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a'])) <del> await scenario.assert('[a _] [_ _] [a _]') <del> }) <del> <del> it('opens a file outside the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'b/2.md'])) <del> await scenario.assert('[a _] [_ _] [_ 2.md]') <del> }) <del> <del> it('opens a directory other than the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'b'])) <del> await scenario.assert('[a _] [_ _] [b _]') <del> }) <del> }) <del> <del> describe('with two windows, one empty and one with a project root', function () { <del> beforeEach(async function () { <del> await scenario.preconditions('[_ _] [a _]') <del> }) <del> <del> // This is also the case when a user clicks on a file within the project root in their file manager <del> it('opens a file within the project root', async function () { <del> await scenario.open(parseCommandLine(['a/1.md'])) <del> await scenario.assert('[_ _] [a 1.md]') <del> }) <del> <del> // This is also the case when a user clicks on a project root folder in their file manager <del> it('opens a directory that matches the project root', async function () { <del> await scenario.open(parseCommandLine(['a'])) <del> await scenario.assert('[_ _] [a _]') <del> }) <del> <del> // This is also the case when a user clicks on a file outside the project root in their file manager <del> it('opens a file outside the project root', async function () { <del> await scenario.open(parseCommandLine(['b/2.md'])) <del> await scenario.assert('[_ 2.md] [a _]') <del> }) <del> <del> // This is also the case when a user clicks on a new folder in their file manager <del> it('opens a directory other than the project root', async function () { <del> await scenario.open(parseCommandLine(['b'])) <del> await scenario.assert('[b _] [a _]') <del> }) <del> <del> it('opens a file within the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <del> await scenario.assert('[_ _] [a 1.md]') <del> }) <del> <del> it('opens a directory that matches the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'a'])) <del> await scenario.assert('[_ _] [a _]') <del> }) <del> <del> it('opens a file outside the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'b/2.md'])) <del> await scenario.assert('[_ _] [a 2.md]') <del> }) <del> <del> it('opens a directory other than the project root with --add', async function () { <del> await scenario.open(parseCommandLine(['--add', 'b'])) <del> await scenario.assert('[_ _] [a,b _]') <del> }) <del> <del> it('opens a file within the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <del> await scenario.assert('[_ _] [a _] [_ 1.md]') <del> }) <del> <del> it('opens a directory that matches the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'a'])) <del> await scenario.assert('[_ _] [a _] [a _]') <del> }) <del> <del> it('opens a file outside the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'b/2.md'])) <del> await scenario.assert('[_ _] [a _] [_ 2.md]') <del> }) <del> <del> it('opens a directory other than the project root with --new-window', async function () { <del> await scenario.open(parseCommandLine(['--new-window', 'b'])) <del> await scenario.assert('[_ _] [a _] [b _]') <del> }) <del> }) <del> <del> describe('--wait', function () { <del> it('kills the specified pid after a newly-opened window is closed', async function () { <del> const [w0] = await scenario.launch(parseCommandLine(['--new-window', '--wait', '--pid', '101'])) <del> const w1 = await scenario.open(parseCommandLine(['--new-window', '--wait', '--pid', '202'])) <del> <del> assert.lengthOf(scenario.killedPids, 0) <del> <del> w0.browserWindow.emit('closed') <del> assert.deepEqual(scenario.killedPids, [101]) <del> <del> w1.browserWindow.emit('closed') <del> assert.deepEqual(scenario.killedPids, [101, 202]) <del> }) <del> <del> it('kills the specified pid after all newly-opened files in an existing window are closed', async function () { <del> const [w] = await scenario.launch(parseCommandLine(['--new-window', 'a'])) <del> await scenario.open(parseCommandLine(['--add', '--wait', '--pid', '303', 'a/1.md', 'b/2.md'])) <del> await scenario.assert('[a 1.md,2.md]') <del> <del> assert.lengthOf(scenario.killedPids, 0) <del> <del> scenario.getApplication(0).windowDidClosePathWithWaitSession(w, scenario.convertEditorPath('b/2.md')) <del> assert.lengthOf(scenario.killedPids, 0) <del> scenario.getApplication(0).windowDidClosePathWithWaitSession(w, scenario.convertEditorPath('a/1.md')) <del> assert.deepEqual(scenario.killedPids, [303]) <del> }) <del> <del> it('kills the specified pid after a newly-opened directory in an existing window is closed', async function () { <del> const [w] = await scenario.launch(parseCommandLine(['--new-window', 'a'])) <del> await scenario.open(parseCommandLine(['--add', '--wait', '--pid', '404', 'b'])) <del> await scenario.assert('[a,b _]') <del> <del> assert.lengthOf(scenario.killedPids, 0) <del> <del> scenario.getApplication(0).windowDidClosePathWithWaitSession(w, scenario.convertRootPath('b')) <del> assert.deepEqual(scenario.killedPids, [404]) <del> }) <del> }) <del> <del> describe('atom:// URLs', function () { <del> describe('with a package-name host', function () { <del> it("loads the package's urlMain in a new window", async function () { <del> await scenario.launch({}) <del> <del> const app = scenario.getApplication(0) <del> app.packages = { <del> getAvailablePackageMetadata: () => [{name: 'package-with-url-main', urlMain: 'some/url-main'}], <del> resolvePackagePath: () => path.resolve('dot-atom/package-with-url-main') <del> } <del> <del> const [w1, w2] = await scenario.open(parseCommandLine([ <del> 'atom://package-with-url-main/test1', <del> 'atom://package-with-url-main/test2' <del> ])) <del> <del> assert.strictEqual( <del> w1.loadSettings.windowInitializationScript, <del> path.resolve('dot-atom/package-with-url-main/some/url-main') <del> ) <del> assert.strictEqual( <del> w1.loadSettings.urlToOpen, <del> 'atom://package-with-url-main/test1' <del> ) <del> <del> assert.strictEqual( <del> w2.loadSettings.windowInitializationScript, <del> path.resolve('dot-atom/package-with-url-main/some/url-main') <del> ) <del> assert.strictEqual( <del> w2.loadSettings.urlToOpen, <del> 'atom://package-with-url-main/test2' <del> ) <del> }) <del> <del> it('sends a URI message to the most recently focused non-spec window', async function () { <del> const [w0] = await scenario.launch({}) <del> const w1 = await scenario.open(parseCommandLine(['--new-window'])) <del> const w2 = await scenario.open(parseCommandLine(['--new-window'])) <del> const w3 = await scenario.open(parseCommandLine(['--test', 'a/1.md'])) <del> <del> const app = scenario.getApplication(0) <del> app.packages = { <del> getAvailablePackageMetadata: () => [] <del> } <del> <del> const [uw] = await scenario.open(parseCommandLine(['atom://package-without-url-main/test'])) <del> assert.strictEqual(uw, w2) <del> <del> assert.isTrue(w2.sendURIMessage.calledWith('atom://package-without-url-main/test')) <del> assert.strictEqual(w2.focus.callCount, 2) <del> <del> for (const other of [w0, w1, w3]) { <del> assert.isFalse(other.sendURIMessage.called) <del> } <del> }) <del> <del> it('creates a new window and sends a URI message to it once it loads', async function () { <del> const [w0] = await scenario.launch(parseCommandLine(['--test', 'a/1.md'])) <del> <del> const app = scenario.getApplication(0) <del> app.packages = { <del> getAvailablePackageMetadata: () => [] <del> } <del> <del> const [uw] = await scenario.open(parseCommandLine(['atom://package-without-url-main/test'])) <del> assert.notStrictEqual(uw, w0) <del> assert.strictEqual( <del> uw.loadSettings.windowInitializationScript, <del> path.resolve(__dirname, '../../src/initialize-application-window.coffee') <del> ) <del> <del> uw.emit('window:loaded') <del> assert.isTrue(uw.sendURIMessage.calledWith('atom://package-without-url-main/test')) <del> }) <del> }) <del> <del> describe('with a "core" host', function () { <del> it('sends a URI message to the most recently focused non-spec window that owns the open locations', async function () { <del> const [w0] = await scenario.launch(parseCommandLine(['a'])) <del> const w1 = await scenario.open(parseCommandLine(['--new-window', 'a'])) <del> const w2 = await scenario.open(parseCommandLine(['--new-window', 'b'])) <del> <del> const uri = `atom://core/open/file?filename=${encodeURIComponent(scenario.convertEditorPath('a/1.md'))}` <del> const [uw] = await scenario.open(parseCommandLine([uri])) <del> assert.strictEqual(uw, w1) <del> assert.isTrue(w1.sendURIMessage.calledWith(uri)) <del> <del> for (const other of [w0, w2]) { <del> assert.isFalse(other.sendURIMessage.called) <del> } <del> }) <del> <del> it('creates a new window and sends a URI message to it once it loads', async function () { <del> const [w0] = await scenario.launch(parseCommandLine(['--test', 'a/1.md'])) <del> <del> const uri = `atom://core/open/file?filename=${encodeURIComponent(scenario.convertEditorPath('b/2.md'))}` <del> const [uw] = await scenario.open(parseCommandLine([uri])) <del> assert.notStrictEqual(uw, w0) <del> <del> uw.emit('window:loaded') <del> assert.isTrue(uw.sendURIMessage.calledWith(uri)) <del> }) <del> }) <del> }) <del> <del> it('opens a file to a specific line number', async function () { <del> await scenario.open(parseCommandLine(['a/1.md:10'])) <del> await scenario.assert('[_ 1.md]') <del> <del> const w = scenario.getWindow(0) <del> assert.lengthOf(w._locations, 1) <del> assert.strictEqual(w._locations[0].initialLine, 9) <del> assert.isNull(w._locations[0].initialColumn) <del> }) <del> <del> it('opens a file to a specific line number', async function () { <del> await scenario.open(parseCommandLine('b/2.md:12:5')) <del> await scenario.assert('[_ 2.md]') <del> <del> const w = scenario.getWindow(0) <del> assert.lengthOf(w._locations, 1) <del> assert.strictEqual(w._locations[0].initialLine, 11) <del> assert.strictEqual(w._locations[0].initialColumn, 4) <del> }) <del> <del> it('opens a directory with a non-file protocol', async function () { <del> await scenario.open(parseCommandLine(['remote://server:3437/some/directory/path'])) <del> <del> const w = scenario.getWindow(0) <del> assert.lengthOf(w._locations, 1) <del> assert.strictEqual(w._locations[0].pathToOpen, 'remote://server:3437/some/directory/path') <del> assert.isFalse(w._locations[0].exists) <del> assert.isFalse(w._locations[0].isDirectory) <del> assert.isFalse(w._locations[0].isFile) <del> }) <del> <del> it('truncates trailing whitespace and colons', async function () { <del> await scenario.open(parseCommandLine('b/2.md:: ')) <del> await scenario.assert('[_ 2.md]') <del> <del> const w = scenario.getWindow(0) <del> assert.lengthOf(w._locations, 1) <del> assert.isNull(w._locations[0].initialLine) <del> assert.isNull(w._locations[0].initialColumn) <del> }) <del> }) <del> <del> if (process.platform === 'darwin' || process.platform === 'win32') { <del> it('positions new windows at an offset from the previous window', async function () { <del> const [w0] = await scenario.launch(parseCommandLine(['a'])) <del> w0.setSize(400, 400) <del> const d0 = w0.getDimensions() <del> <del> const w1 = await scenario.open(parseCommandLine(['b'])) <del> const d1 = w1.getDimensions() <del> <del> assert.isAbove(d0.x, d1.x) <del> assert.isAbove(d0.y, d1.y) <del> }) <del> } <del> <del> if (process.platform === 'darwin') { <del> describe('with no windows open', function () { <del> let app <del> <del> beforeEach(async function () { <del> const [w] = await scenario.launch(parseCommandLine([])) <del> <del> app = scenario.getApplication(0) <del> app.removeWindow(w) <del> sinon.stub(app, 'promptForPathToOpen') <del> }) <del> <del> it('opens a new file', function () { <del> app.emit('application:open-file') <del> assert.isTrue(app.promptForPathToOpen.calledWith('file', {devMode: false, safeMode: false, window: null})) <del> }) <del> <del> it('opens a new directory', function () { <del> app.emit('application:open-folder') <del> assert.isTrue(app.promptForPathToOpen.calledWith('folder', {devMode: false, safeMode: false, window: null})) <del> }) <del> <del> it('opens a new file or directory', function () { <del> app.emit('application:open') <del> assert.isTrue(app.promptForPathToOpen.calledWith('all', {devMode: false, safeMode: false, window: null})) <del> }) <del> <del> it('reopens a project in a new window', async function () { <del> const paths = scenario.convertPaths(['a', 'b']) <del> app.emit('application:reopen-project', {paths}) <del> <del> await conditionPromise(() => app.getAllWindows().length > 0) <del> <del> assert.deepEqual(app.getAllWindows().map(w => Array.from(w._rootPaths)), [paths]) <del> }) <del> }) <del> } <del> <del> describe('existing application re-use', function () { <del> let createApplication <del> <del> const version = electron.app.getVersion() <del> <del> beforeEach(function () { <del> createApplication = async options => { <del> options.version = version <del> <del> const app = scenario.addApplication(options) <del> await app.listenForArgumentsFromNewProcess() <del> await app.launch(options) <del> return app <del> } <del> }) <del> <del> it('creates a new application when no socket is present', async function () { <del> const app0 = await AtomApplication.open({createApplication, version}) <del> app0.deleteSocketSecretFile() <del> <del> const app1 = await AtomApplication.open({createApplication, version}) <del> assert.isNotNull(app1) <del> assert.notStrictEqual(app0, app1) <del> }) <del> <del> it('creates a new application for spec windows', async function () { <del> const app0 = await AtomApplication.open({createApplication, version}) <del> <del> const app1 = await AtomApplication.open({createApplication, version, ...parseCommandLine(['--test', 'a'])}) <del> assert.isNotNull(app1) <del> assert.notStrictEqual(app0, app1) <del> }) <del> <del> it('sends a request to an existing application when a socket is present', async function () { <del> const app0 = await AtomApplication.open({createApplication, version}) <del> assert.lengthOf(app0.getAllWindows(), 1) <del> <del> const app1 = await AtomApplication.open({createApplication, version, ...parseCommandLine(['--new-window'])}) <del> assert.isNull(app1) <del> assert.isTrue(electron.app.quit.called) <del> <del> await conditionPromise(() => app0.getAllWindows().length === 2) <del> await scenario.assert('[_ _] [_ _]') <del> }) <del> }) <del> <del> describe('window state serialization', function () { <del> it('occurs immediately when adding a window', async function () { <del> await scenario.launch(parseCommandLine(['a'])) <del> <del> const promise = emitterEventPromise(scenario.getApplication(0), 'application:did-save-state') <del> await scenario.open(parseCommandLine(['c', 'b'])) <del> await promise <del> <del> assert.isTrue(scenario.getApplication(0).storageFolder.store.calledWith( <del> 'application.json', <del> [ <del> {initialPaths: [scenario.convertRootPath('a')]}, <del> {initialPaths: [scenario.convertRootPath('b'), scenario.convertRootPath('c')]} <del> ] <del> )) <del> }) <del> <del> it('occurs immediately when removing a window', async function () { <del> await scenario.launch(parseCommandLine(['a'])) <del> const w = await scenario.open(parseCommandLine(['b'])) <del> <del> const promise = emitterEventPromise(scenario.getApplication(0), 'application:did-save-state') <del> scenario.getApplication(0).removeWindow(w) <del> await promise <del> <del> assert.isTrue(scenario.getApplication(0).storageFolder.store.calledWith( <del> 'application.json', <del> [ <del> {initialPaths: [scenario.convertRootPath('a')]} <del> ] <del> )) <del> }) <del> <del> it('occurs when the window is blurred', async function () { <del> const [w] = await scenario.launch(parseCommandLine(['a'])) <del> const promise = emitterEventPromise(scenario.getApplication(0), 'application:did-save-state') <del> w.browserWindow.emit('blur') <del> await promise <del> }) <del> }) <del> <del> describe('when closing the last window', function () { <del> if (process.platform === 'linux' || process.platform === 'win32') { <del> it('quits the application', async function () { <del> const [w] = await scenario.launch(parseCommandLine(['a'])) <del> w.browserWindow.emit('closed') <del> assert.isTrue(electron.app.quit.called) <del> }) <del> } else if (process.platform === 'darwin') { <del> it('leaves the application open', async function () { <del> const [w] = await scenario.launch(parseCommandLine(['a'])) <del> w.browserWindow.emit('closed') <del> assert.isFalse(electron.app.quit.called) <del> }) <del> } <del> }) <del> <del> describe('quitting', function () { <del> it('waits until all windows have saved their state before quitting', async function () { <del> const [w0] = await scenario.launch(parseCommandLine(['a'])) <del> const w1 = await scenario.open(parseCommandLine(['b'])) <del> <del> sinon.spy(w0, 'close') <del> let resolveUnload0 <del> w0.prepareToUnload = () => new Promise(resolve => { resolveUnload0 = resolve }) <del> <del> sinon.spy(w1, 'close') <del> let resolveUnload1 <del> w1.prepareToUnload = () => new Promise(resolve => { resolveUnload1 = resolve }) <del> <del> const evt = {preventDefault: sinon.spy()} <del> electron.app.emit('before-quit', evt) <del> await new Promise(process.nextTick) <del> assert.isTrue(evt.preventDefault.called) <del> assert.isFalse(electron.app.quit.called) <del> <del> resolveUnload1(true) <del> await new Promise(process.nextTick) <del> assert.isFalse(electron.app.quit.called) <del> <del> resolveUnload0(true) <del> await scenario.getApplication(0).lastBeforeQuitPromise <del> assert.isTrue(electron.app.quit.called) <del> <del> assert.isTrue(w0.close.called) <del> assert.isTrue(w1.close.called) <del> }) <del> <del> it('prevents a quit if a user cancels when prompted to save', async function () { <del> const [w] = await scenario.launch(parseCommandLine(['a'])) <del> let resolveUnload <del> w.prepareToUnload = () => new Promise(resolve => { resolveUnload = resolve }) <del> <del> const evt = {preventDefault: sinon.spy()} <del> electron.app.emit('before-quit', evt) <del> await new Promise(process.nextTick) <del> assert.isTrue(evt.preventDefault.called) <del> <del> resolveUnload(false) <del> await scenario.getApplication(0).lastBeforeQuitPromise <del> <del> assert.isFalse(electron.app.quit.called) <del> }) <del> <del> it('closes successfully unloaded windows', async function () { <del> const [w0] = await scenario.launch(parseCommandLine(['a'])) <del> const w1 = await scenario.open(parseCommandLine(['b'])) <del> <del> sinon.spy(w0, 'close') <del> let resolveUnload0 <del> w0.prepareToUnload = () => new Promise(resolve => { resolveUnload0 = resolve }) <del> <del> sinon.spy(w1, 'close') <del> let resolveUnload1 <del> w1.prepareToUnload = () => new Promise(resolve => { resolveUnload1 = resolve }) <del> <del> const evt = {preventDefault () {}} <del> electron.app.emit('before-quit', evt) <del> <del> resolveUnload0(false) <del> resolveUnload1(true) <del> <del> await scenario.getApplication(0).lastBeforeQuitPromise <del> <del> assert.isFalse(electron.app.quit.called) <del> assert.isFalse(w0.close.called) <del> assert.isTrue(w1.close.called) <del> }) <del> }) <del>}) <del> <del>class StubWindow extends EventEmitter { <del> constructor (sinon, loadSettings, options) { <del> super() <del> <del> this.loadSettings = loadSettings <del> <del> this._dimensions = {x: 100, y: 100} <del> this._position = {x: 0, y: 0} <del> this._locations = [] <del> this._rootPaths = new Set() <del> this._editorPaths = new Set() <del> <del> let resolveClosePromise <del> this.closedPromise = new Promise(resolve => { resolveClosePromise = resolve }) <del> <del> this.minimize = sinon.spy() <del> this.maximize = sinon.spy() <del> this.center = sinon.spy() <del> this.focus = sinon.spy() <del> this.show = sinon.spy() <del> this.hide = sinon.spy() <del> this.prepareToUnload = sinon.spy() <del> this.close = resolveClosePromise <del> <del> this.replaceEnvironment = sinon.spy() <del> this.disableZoom = sinon.spy() <del> <del> this.isFocused = sinon.stub().returns(options.isFocused !== undefined ? options.isFocused : false) <del> this.isMinimized = sinon.stub().returns(options.isMinimized !== undefined ? options.isMinimized : false) <del> this.isMaximized = sinon.stub().returns(options.isMaximized !== undefined ? options.isMaximized : false) <del> <del> this.sendURIMessage = sinon.spy() <del> this.didChangeUserSettings = sinon.spy() <del> this.didFailToReadUserSettings = sinon.spy() <del> <del> this.isSpec = loadSettings.isSpec !== undefined ? loadSettings.isSpec : false <del> this.devMode = loadSettings.devMode !== undefined ? loadSettings.devMode : false <del> this.safeMode = loadSettings.safeMode !== undefined ? loadSettings.safeMode : false <del> <del> this.browserWindow = new EventEmitter() <del> this.browserWindow.webContents = new EventEmitter() <del> <del> const locationsToOpen = this.loadSettings.locationsToOpen || [] <del> if (!(locationsToOpen.length === 1 && locationsToOpen[0].pathToOpen == null) && !this.isSpec) { <del> this.openLocations(locationsToOpen) <del> } <del> } <del> <del> openPath (pathToOpen, initialLine, initialColumn) { <del> return this.openLocations([{pathToOpen, initialLine, initialColumn}]) <del> } <del> <del> openLocations (locations) { <del> this._locations.push(...locations) <del> for (const location of locations) { <del> if (location.pathToOpen) { <del> if (location.isDirectory) { <del> this._rootPaths.add(location.pathToOpen) <del> } else if (location.isFile) { <del> this._editorPaths.add(location.pathToOpen) <del> } <del> } <del> } <del> <del> this.projectRoots = Array.from(this._rootPaths) <del> this.projectRoots.sort() <del> <del> this.emit('window:locations-opened') <del> } <del> <del> setSize (x, y) { <del> this._dimensions = {x, y} <del> } <del> <del> setPosition (x, y) { <del> this._position = {x, y} <del> } <del> <del> isSpecWindow () { <del> return this.isSpec <del> } <del> <del> hasProjectPaths () { <del> return this._rootPaths.size > 0 <del> } <del> <del> containsLocations (locations) { <del> return locations.every(location => this.containsLocation(location)) <del> } <del> <del> containsLocation (location) { <del> if (!location.pathToOpen) return false <del> <del> return Array.from(this._rootPaths).some(projectPath => { <del> if (location.pathToOpen === projectPath) return true <del> if (location.pathToOpen.startsWith(path.join(projectPath, path.sep))) { <del> if (!location.exists) return true <del> if (!location.isDirectory) return true <del> } <del> return false <del> }) <del> } <del> <del> getDimensions () { <del> return this._dimensions <del> } <del>} <del> <del>class LaunchScenario { <del> static async create (sandbox) { <del> const scenario = new this(sandbox) <del> await scenario.init() <del> return scenario <del> } <del> <del> constructor (sandbox) { <del> this.sinon = sandbox <del> <del> this.applications = new Set() <del> this.windows = new Set() <del> this.root = null <del> this.atomHome = null <del> this.projectRootPool = new Map() <del> this.filePathPool = new Map() <del> <del> this.killedPids = [] <del> this.originalAtomHome = null <del> } <del> <del> async init () { <del> if (this.root !== null) { <del> return this.root <del> } <del> <del> this.root = await new Promise((resolve, reject) => { <del> temp.mkdir('launch-', (err, rootPath) => { <del> if (err) { reject(err) } else { resolve(rootPath) } <del> }) <del> }) <del> <del> this.atomHome = path.join(this.root, '.atom') <del> await new Promise((resolve, reject) => { <del> fs.makeTree(this.atomHome, err => { <del> if (err) { reject(err) } else { resolve() } <del> }) <del> }) <del> this.originalAtomHome = process.env.ATOM_HOME <del> process.env.ATOM_HOME = this.atomHome <del> <del> await Promise.all( <del> ['a', 'b', 'c'].map(dirPath => new Promise((resolve, reject) => { <del> const fullDirPath = path.join(this.root, dirPath) <del> fs.makeTree(fullDirPath, err => { <del> if (err) { <del> reject(err) <del> } else { <del> this.projectRootPool.set(dirPath, fullDirPath) <del> resolve() <del> } <del> }) <del> })) <del> ) <del> <del> await Promise.all( <del> ['a/1.md', 'b/2.md'].map(filePath => new Promise((resolve, reject) => { <del> const fullFilePath = path.join(this.root, filePath) <del> fs.writeFile(fullFilePath, `file: ${filePath}\n`, {encoding: 'utf8'}, err => { <del> if (err) { <del> reject(err) <del> } else { <del> this.filePathPool.set(filePath, fullFilePath) <del> this.filePathPool.set(path.basename(filePath), fullFilePath) <del> resolve() <del> } <del> }) <del> })) <del> ) <del> <del> this.sinon.stub(electron.app, 'quit') <del> } <del> <del> async preconditions (source) { <del> const app = this.addApplication() <del> const windowPromises = [] <del> <del> for (const windowSpec of this.parseWindowSpecs(source)) { <del> if (windowSpec.editors.length === 0) { <del> windowSpec.editors.push(null) <del> } <del> <del> windowPromises.push(((theApp, foldersToOpen, pathsToOpen) => { <del> return theApp.openPaths({ newWindow: true, foldersToOpen, pathsToOpen }) <del> })(app, windowSpec.roots, windowSpec.editors)) <del> } <del> await Promise.all(windowPromises) <del> } <del> <del> launch (options) { <del> const app = options.app || this.addApplication() <del> delete options.app <del> <del> if (options.pathsToOpen) { <del> options.pathsToOpen = this.convertPaths(options.pathsToOpen) <del> } <del> <del> return app.launch(options) <del> } <del> <del> open (options) { <del> if (this.applications.size === 0) { <del> return this.launch(options) <del> } <del> <del> let app = options.app <del> if (!app) { <del> const apps = Array.from(this.applications) <del> app = apps[apps.length - 1] <del> } else { <del> delete options.app <del> } <del> <del> if (options.pathsToOpen) { <del> options.pathsToOpen = this.convertPaths(options.pathsToOpen) <del> } <del> options.preserveFocus = true <del> <del> return app.openWithOptions(options) <del> } <del> <del> async assert (source) { <del> const windowSpecs = this.parseWindowSpecs(source) <del> let specIndex = 0 <del> <del> const windowPromises = [] <del> for (const window of this.windows) { <del> windowPromises.push((async (theWindow, theSpec) => { <del> const {_rootPaths: rootPaths, _editorPaths: editorPaths} = theWindow <del> <del> const comparison = { <del> ok: true, <del> extraWindow: false, <del> missingWindow: false, <del> extraRoots: [], <del> missingRoots: [], <del> extraEditors: [], <del> missingEditors: [], <del> roots: rootPaths, <del> editors: editorPaths <del> } <del> <del> if (!theSpec) { <del> comparison.ok = false <del> comparison.extraWindow = true <del> comparison.extraRoots = rootPaths <del> comparison.extraEditors = editorPaths <del> } else { <del> const [missingRoots, extraRoots] = this.compareSets(theSpec.roots, rootPaths) <del> const [missingEditors, extraEditors] = this.compareSets(theSpec.editors, editorPaths) <del> <del> comparison.ok = missingRoots.length === 0 && <del> extraRoots.length === 0 && <del> missingEditors.length === 0 && <del> extraEditors.length === 0 <del> comparison.extraRoots = extraRoots <del> comparison.missingRoots = missingRoots <del> comparison.extraEditors = extraEditors <del> comparison.missingEditors = missingEditors <del> } <del> <del> return comparison <del> })(window, windowSpecs[specIndex++])) <del> } <del> <del> const comparisons = await Promise.all(windowPromises) <del> for (; specIndex < windowSpecs.length; specIndex++) { <del> const spec = windowSpecs[specIndex] <del> comparisons.push({ <del> ok: false, <del> extraWindow: false, <del> missingWindow: true, <del> extraRoots: [], <del> missingRoots: spec.roots, <del> extraEditors: [], <del> missingEditors: spec.editors, <del> roots: null, <del> editors: null <del> }) <del> } <del> <del> const shorthandParts = [] <del> const descriptionParts = [] <del> for (const comparison of comparisons) { <del> if (comparison.roots !== null && comparison.editors !== null) { <del> const shortRoots = Array.from(comparison.roots, r => path.basename(r)).join(',') <del> const shortPaths = Array.from(comparison.editors, e => path.basename(e)).join(',') <del> shorthandParts.push(`[${shortRoots} ${shortPaths}]`) <del> } <del> <del> if (comparison.ok) { <del> continue <del> } <del> <del> let parts = [] <del> if (comparison.extraWindow) { <del> parts.push('extra window\n') <del> } else if (comparison.missingWindow) { <del> parts.push('missing window\n') <del> } else { <del> parts.push('incorrect window\n') <del> } <del> <del> const shorten = fullPaths => fullPaths.map(fullPath => path.basename(fullPath)).join(', ') <del> <del> if (comparison.extraRoots.length > 0) { <del> parts.push(`* extra roots ${shorten(comparison.extraRoots)}\n`) <del> } <del> if (comparison.missingRoots.length > 0) { <del> parts.push(`* missing roots ${shorten(comparison.missingRoots)}\n`) <del> } <del> if (comparison.extraEditors.length > 0) { <del> parts.push(`* extra editors ${shorten(comparison.extraEditors)}\n`) <del> } <del> if (comparison.missingEditors.length > 0) { <del> parts.push(`* missing editors ${shorten(comparison.missingEditors)}\n`) <del> } <del> <del> descriptionParts.push(parts.join('')) <del> } <del> <del> if (descriptionParts.length !== 0) { <del> descriptionParts.unshift(shorthandParts.join(' ') + '\n') <del> descriptionParts.unshift('Launched windows did not match spec\n') <del> } <del> <del> assert.isTrue(descriptionParts.length === 0, descriptionParts.join('')) <del> } <del> <del> async destroy () { <del> await Promise.all( <del> Array.from(this.applications, app => app.destroy()) <del> ) <del> <del> if (this.originalAtomHome) { <del> process.env.ATOM_HOME = this.originalAtomHome <del> } <del> } <del> <del> addApplication (options = {}) { <del> const app = new AtomApplication({ <del> resourcePath: path.resolve(__dirname, '../..'), <del> atomHomeDirPath: this.atomHome, <del> preserveFocus: true, <del> killProcess: pid => { this.killedPids.push(pid) }, <del> ...options <del> }) <del> this.sinon.stub(app, 'createWindow', loadSettings => { <del> const newWindow = new StubWindow(this.sinon, loadSettings, options) <del> this.windows.add(newWindow) <del> return newWindow <del> }) <del> this.sinon.stub(app.storageFolder, 'load', () => Promise.resolve( <del> (options.applicationJson || []).map(each => ({ <del> initialPaths: this.convertPaths(each.initialPaths) <del> })) <del> )) <del> this.sinon.stub(app.storageFolder, 'store', () => Promise.resolve()) <del> this.applications.add(app) <del> return app <del> } <del> <del> getApplication (index) { <del> const app = Array.from(this.applications)[index] <del> if (!app) { <del> throw new Error(`Application ${index} does not exist`) <del> } <del> return app <del> } <del> <del> getWindow (index) { <del> const window = Array.from(this.windows)[index] <del> if (!window) { <del> throw new Error(`Window ${index} does not exist`) <del> } <del> return window <del> } <del> <del> compareSets (expected, actual) { <del> const expectedItems = new Set(expected) <del> const extra = [] <del> const missing = [] <del> <del> for (const actualItem of actual) { <del> if (!expectedItems.delete(actualItem)) { <del> // actualItem was present, but not expected <del> extra.push(actualItem) <del> } <del> } <del> for (const remainingItem of expectedItems) { <del> // remainingItem was expected, but not present <del> missing.push(remainingItem) <del> } <del> return [missing, extra] <del> } <del> <del> convertRootPath (shortRootPath) { <del> if (shortRootPath.startsWith('atom://') || shortRootPath.startsWith('remote://')) { return shortRootPath } <del> <del> const fullRootPath = this.projectRootPool.get(shortRootPath) <del> if (!fullRootPath) { <del> throw new Error(`Unexpected short project root path: ${shortRootPath}`) <del> } <del> return fullRootPath <del> } <del> <del> convertEditorPath (shortEditorPath) { <del> const [truncatedPath, ...suffix] = shortEditorPath.split(/(?=:)/) <del> const fullEditorPath = this.filePathPool.get(truncatedPath) <del> if (!fullEditorPath) { <del> throw new Error(`Unexpected short editor path: ${shortEditorPath}`) <del> } <del> return fullEditorPath + suffix.join('') <del> } <del> <del> convertPaths (paths) { <del> return paths.map(shortPath => { <del> if (shortPath.startsWith('atom://') || shortPath.startsWith('remote://')) { return shortPath } <del> <del> const fullRoot = this.projectRootPool.get(shortPath) <del> if (fullRoot) { return fullRoot } <del> <del> const [truncatedPath, ...suffix] = shortPath.split(/(?=:)/) <del> const fullEditor = this.filePathPool.get(truncatedPath) <del> if (fullEditor) { return fullEditor + suffix.join('') } <del> <del> throw new Error(`Unexpected short path: ${shortPath}`) <del> }) <del> } <del> <del> parseWindowSpecs (source) { <del> const specs = [] <del> <del> const rx = /\s*\[(?:_|(\S+)) (?:_|(\S+))\]/g <del> let match = rx.exec(source) <del> <del> while (match) { <del> const roots = match[1] ? match[1].split(',').map(shortPath => this.convertRootPath(shortPath)) : [] <del> const editors = match[2] ? match[2].split(',').map(shortPath => this.convertEditorPath(shortPath)) : [] <del> specs.push({ roots, editors }) <del> <del> match = rx.exec(source) <del> } <del> <del> return specs <del> } <del>} <ide><path>spec/main-process/atom-application.test.js <ide> /* globals assert */ <ide> <add>const path = require('path') <add>const {EventEmitter} = require('events') <ide> const temp = require('temp').track() <del>const season = require('season') <del>const dedent = require('dedent') <del>const electron = require('electron') <ide> const fs = require('fs-plus') <del>const path = require('path') <del>const sinon = require('sinon') <add>const electron = require('electron') <add>const {sandbox} = require('sinon') <add> <ide> const AtomApplication = require('../../src/main-process/atom-application') <ide> const parseCommandLine = require('../../src/main-process/parse-command-line') <del>const { <del> timeoutPromise, <del> conditionPromise, <del> emitterEventPromise <del>} = require('../async-spec-helpers') <del> <del>const ATOM_RESOURCE_PATH = path.resolve(__dirname, '..', '..') <del> <del>describe.skip('AtomApplication', function () { <del> this.timeout(60 * 1000) <del> <del> let originalAppQuit, <del> originalShowMessageBox, <del> originalAtomHome, <del> atomApplicationsToDestroy <del> <del> beforeEach(() => { <del> originalAppQuit = electron.app.quit <del> originalShowMessageBox = electron.dialog.showMessageBox <del> mockElectronAppQuit() <del> originalAtomHome = process.env.ATOM_HOME <del> process.env.ATOM_HOME = makeTempDir('atom-home') <del> // Symlinking the compile cache into the temporary home dir makes the windows load much faster <del> fs.symlinkSync( <del> path.join(originalAtomHome, 'compile-cache'), <del> path.join(process.env.ATOM_HOME, 'compile-cache'), <del> 'junction' <del> ) <del> season.writeFileSync(path.join(process.env.ATOM_HOME, 'config.cson'), { <del> '*': { <del> welcome: { showOnStartup: false }, <del> core: { telemetryConsent: 'no' } <del> } <del> }) <del> atomApplicationsToDestroy = [] <add>const {emitterEventPromise, conditionPromise} = require('../async-spec-helpers') <add> <add>describe('AtomApplication', function () { <add> let scenario, sinon <add> <add> beforeEach(async function () { <add> sinon = sandbox.create() <add> scenario = await LaunchScenario.create(sinon) <ide> }) <ide> <del> afterEach(async () => { <del> process.env.ATOM_HOME = originalAtomHome <del> for (let atomApplication of atomApplicationsToDestroy) { <del> await atomApplication.destroy() <del> } <del> await clearElectronSession() <del> electron.app.quit = originalAppQuit <del> electron.dialog.showMessageBox = originalShowMessageBox <add> afterEach(async function () { <add> await scenario.destroy() <add> sinon.restore() <ide> }) <ide> <del> describe('launch', () => { <del> describe('with no paths', () => { <del> // Covered <del> it('reopens any previously opened windows', async () => { <del> if (process.platform === 'win32') return // Test is too flakey on Windows <del> <del> const tempDirPath1 = makeTempDir() <del> const tempDirPath2 = makeTempDir() <del> <del> const atomApplication1 = buildAtomApplication() <del> const [app1Window1] = await atomApplication1.launch( <del> parseCommandLine([tempDirPath1]) <del> ) <del> await emitterEventPromise(app1Window1, 'window:locations-opened') <del> <del> const [app1Window2] = await atomApplication1.launch( <del> parseCommandLine([tempDirPath2]) <del> ) <del> await emitterEventPromise(app1Window2, 'window:locations-opened') <del> <del> await Promise.all([ <del> app1Window1.prepareToUnload(), <del> app1Window2.prepareToUnload() <del> ]) <del> <del> const atomApplication2 = buildAtomApplication() <del> const [app2Window1, app2Window2] = await atomApplication2.launch( <del> parseCommandLine([]) <del> ) <del> await Promise.all([ <del> emitterEventPromise(app2Window1, 'window:locations-opened'), <del> emitterEventPromise(app2Window2, 'window:locations-opened') <del> ]) <del> <del> assert.deepEqual(await getTreeViewRootDirectories(app2Window1), [ <del> tempDirPath1 <del> ]) <del> assert.deepEqual(await getTreeViewRootDirectories(app2Window2), [ <del> tempDirPath2 <del> ]) <del> }) <del> <del> // Covered <del> it('when windows already exist, opens a new window with a single untitled buffer', async () => { <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([])) <del> await focusWindow(window1) <del> const window1EditorTitle = await evalInWebContents( <del> window1.browserWindow.webContents, <del> sendBackToMainProcess => { <del> sendBackToMainProcess( <del> atom.workspace.getActiveTextEditor().getTitle() <del> ) <del> } <del> ) <del> assert.equal(window1EditorTitle, 'untitled') <del> <del> const window2 = atomApplication.openWithOptions(parseCommandLine([])) <del> await window2.loadedPromise <del> const window2EditorTitle = await evalInWebContents( <del> window1.browserWindow.webContents, <del> sendBackToMainProcess => { <del> sendBackToMainProcess( <del> atom.workspace.getActiveTextEditor().getTitle() <del> ) <del> } <del> ) <del> assert.equal(window2EditorTitle, 'untitled') <del> <del> assert.deepEqual(atomApplication.getAllWindows(), [window2, window1]) <del> }) <del> <del> // Covered <del> it('when no windows are open but --new-window is passed, opens a new window with a single untitled buffer', async () => { <del> // Populate some saved state <del> const tempDirPath1 = makeTempDir() <del> const tempDirPath2 = makeTempDir() <del> <del> const atomApplication1 = buildAtomApplication() <del> const [app1Window1] = await atomApplication1.launch( <del> parseCommandLine([tempDirPath1]) <del> ) <del> await emitterEventPromise(app1Window1, 'window:locations-opened') <del> <del> const [app1Window2] = await atomApplication1.launch( <del> parseCommandLine([tempDirPath2]) <del> ) <del> await emitterEventPromise(app1Window2, 'window:locations-opened') <del> <del> await Promise.all([ <del> app1Window1.prepareToUnload(), <del> app1Window2.prepareToUnload() <del> ]) <del> <del> // Launch with --new-window <del> const atomApplication2 = buildAtomApplication() <del> const appWindows2 = await atomApplication2.launch( <del> parseCommandLine(['--new-window']) <del> ) <del> assert.lengthOf(appWindows2, 1) <del> const [appWindow2] = appWindows2 <del> await appWindow2.loadedPromise <del> const window2EditorTitle = await evalInWebContents( <del> appWindow2.browserWindow.webContents, <del> sendBackToMainProcess => { <del> sendBackToMainProcess( <del> atom.workspace.getActiveTextEditor().getTitle() <del> ) <del> } <del> ) <del> assert.equal(window2EditorTitle, 'untitled') <del> }) <del> <del> // Covered <del> it('does not open an empty editor if core.openEmptyEditorOnStart is false', async () => { <del> const configPath = path.join(process.env.ATOM_HOME, 'config.cson') <del> const config = season.readFileSync(configPath) <del> if (!config['*'].core) config['*'].core = {} <del> config['*'].core.openEmptyEditorOnStart = false <del> season.writeFileSync(configPath, config) <del> <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([])) <del> await focusWindow(window1) <del> <del> // wait a bit just to make sure we don't pass due to querying the render process before it loads <del> await timeoutPromise(1000) <del> <del> const itemCount = await evalInWebContents( <del> window1.browserWindow.webContents, <del> sendBackToMainProcess => { <del> sendBackToMainProcess( <del> atom.workspace.getActivePane().getItems().length <del> ) <del> } <del> ) <del> assert.equal(itemCount, 0) <add> describe('command-line interface behavior', function () { <add> describe('with no open windows', function () { <add> // This is also the case when a user clicks on a file in their file manager <add> it('opens a file', async function () { <add> await scenario.open(parseCommandLine(['a/1.md'])) <add> await scenario.assert('[_ 1.md]') <ide> }) <del> }) <ide> <del> describe('with file or folder paths', () => { <del> // Covered <del> it('shows all directories in the tree view when multiple directory paths are passed to Atom', async () => { <del> const dirAPath = makeTempDir('a') <del> const dirBPath = makeTempDir('b') <del> const dirBSubdirPath = path.join(dirBPath, 'c') <del> fs.mkdirSync(dirBSubdirPath) <del> <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch( <del> parseCommandLine([dirAPath, dirBPath]) <del> ) <del> await focusWindow(window1) <del> <del> await conditionPromise( <del> async () => (await getTreeViewRootDirectories(window1)).length === 2 <del> ) <del> assert.deepEqual(await getTreeViewRootDirectories(window1), [ <del> dirAPath, <del> dirBPath <del> ]) <del> }) <del> <del> // Covered <del> it('can open to a specific line number of a file', async () => { <del> const filePath = path.join(makeTempDir(), 'new-file') <del> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <del> const atomApplication = buildAtomApplication() <del> <del> const [window] = await atomApplication.launch( <del> parseCommandLine([filePath + ':3']) <del> ) <del> await focusWindow(window) <del> <del> const cursorRow = await evalInWebContents( <del> window.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(textEditor => { <del> sendBackToMainProcess(textEditor.getCursorBufferPosition().row) <del> }) <del> } <del> ) <add> // This is also the case when a user clicks on a folder in their file manager <add> // (or, on macOS, drags the folder to Atom in their doc) <add> it('opens a directory', async function () { <add> await scenario.open(parseCommandLine(['a'])) <add> await scenario.assert('[a _]') <add> }) <ide> <del> assert.equal(cursorRow, 2) <add> it('opens a file with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <add> await scenario.assert('[_ 1.md]') <ide> }) <ide> <del> // Covered <del> it('can open to a specific line and column of a file', async () => { <del> const filePath = path.join(makeTempDir(), 'new-file') <del> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <del> const atomApplication = buildAtomApplication() <add> it('opens a directory with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a'])) <add> await scenario.assert('[a _]') <add> }) <ide> <del> const [window] = await atomApplication.launch( <del> parseCommandLine([filePath + ':2:2']) <del> ) <del> await focusWindow(window) <add> it('opens a file with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <add> await scenario.assert('[_ 1.md]') <add> }) <ide> <del> const cursorPosition = await evalInWebContents( <del> window.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(textEditor => { <del> sendBackToMainProcess(textEditor.getCursorBufferPosition()) <del> }) <del> } <del> ) <add> it('opens a directory with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a'])) <add> await scenario.assert('[a _]') <add> }) <add> <add> describe('with previous window state', function () { <add> let app <add> <add> beforeEach(function () { <add> app = scenario.addApplication({ <add> applicationJson: [ <add> { initialPaths: ['b'] }, <add> { initialPaths: ['c'] } <add> ] <add> }) <add> }) <add> <add> describe('with core.restorePreviousWindowsOnStart set to "no"', function () { <add> beforeEach(function () { <add> app.config.set('core.restorePreviousWindowsOnStart', 'no') <add> }) <add> <add> it("doesn't restore windows when launched with no arguments", async function () { <add> await scenario.launch({app}) <add> await scenario.assert('[_ _]') <add> }) <add> <add> it("doesn't restore windows when launched with paths to open", async function () { <add> await scenario.launch({app, pathsToOpen: ['a/1.md']}) <add> await scenario.assert('[_ 1.md]') <add> }) <add> <add> it("doesn't restore windows when --new-window is provided", async function () { <add> await scenario.launch({app, newWindow: true}) <add> await scenario.assert('[_ _]') <add> }) <add> }) <add> <add> describe('with core.restorePreviousWindowsOnStart set to "yes"', function () { <add> beforeEach(function () { <add> app.config.set('core.restorePreviousWindowsOnStart', 'yes') <add> }) <add> <add> it('restores windows when launched with no arguments', async function () { <add> await scenario.launch({app}) <add> await scenario.assert('[b _] [c _]') <add> }) <add> <add> it("doesn't restore windows when launched with paths to open", async function () { <add> await scenario.launch({app, pathsToOpen: ['a/1.md']}) <add> await scenario.assert('[_ 1.md]') <add> }) <add> <add> it("doesn't restore windows when --new-window is provided", async function () { <add> await scenario.launch({app, newWindow: true}) <add> await scenario.assert('[_ _]') <add> }) <add> }) <add> <add> describe('with core.restorePreviousWindowsOnStart set to "always"', function () { <add> beforeEach(function () { <add> app.config.set('core.restorePreviousWindowsOnStart', 'always') <add> }) <add> <add> it('restores windows when launched with no arguments', async function () { <add> await scenario.launch({app}) <add> await scenario.assert('[b _] [c _]') <add> }) <add> <add> it('restores windows when launched with paths to open', async function () { <add> await scenario.launch({app, pathsToOpen: ['a']}) <add> await scenario.assert('[a _] [b _] [c _]') <add> }) <add> <add> it('collapses new paths into restored windows when appropriate', async function () { <add> await scenario.launch({app, pathsToOpen: ['b/2.md']}) <add> await scenario.assert('[b 2.md] [c _]') <add> }) <add> <add> it("doesn't restore windows when --new-window is provided", async function () { <add> await scenario.launch({app, newWindow: true}) <add> await scenario.assert('[_ _]') <add> }) <add> <add> it("doesn't restore windows on open, just launch", async function () { <add> await scenario.launch({app, pathsToOpen: ['a'], newWindow: true}) <add> await scenario.open(parseCommandLine(['b'])) <add> await scenario.assert('[a _] [b _]') <add> }) <add> }) <add> }) <add> }) <ide> <del> assert.deepEqual(cursorPosition, { row: 1, column: 1 }) <add> describe('with one empty window', function () { <add> beforeEach(async function () { <add> await scenario.preconditions('[_ _]') <ide> }) <ide> <del> it('removes all trailing whitespace and colons from the specified path', async () => { <del> let filePath = path.join(makeTempDir(), 'new-file') <del> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <del> const atomApplication = buildAtomApplication() <add> // This is also the case when a user clicks on a file in their file manager <add> it('opens a file', async function () { <add> await scenario.open(parseCommandLine(['a/1.md'])) <add> await scenario.assert('[_ 1.md]') <add> }) <ide> <del> const [window] = await atomApplication.launch( <del> parseCommandLine([filePath + ':: ']) <del> ) <del> await focusWindow(window) <add> // This is also the case when a user clicks on a folder in their file manager <add> it('opens a directory', async function () { <add> await scenario.open(parseCommandLine(['a'])) <add> await scenario.assert('[a _]') <add> }) <ide> <del> const openedPath = await evalInWebContents( <del> window.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(textEditor => { <del> sendBackToMainProcess(textEditor.getPath()) <del> }) <del> } <del> ) <del> <del> assert.equal(openedPath, filePath) <del> }) <del> <del> // Covered <del> it('opens an empty text editor when launched with a new file path', async () => { <del> // Choosing "Don't save" <del> mockElectronShowMessageBox({ response: 2 }) <del> <del> const atomApplication = buildAtomApplication() <del> const newFilePath = path.join(makeTempDir(), 'new-file') <del> const [window] = await atomApplication.launch( <del> parseCommandLine([newFilePath]) <del> ) <del> await focusWindow(window) <del> const { editorTitle, editorText } = await evalInWebContents( <del> window.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(editor => { <del> sendBackToMainProcess({ <del> editorTitle: editor.getTitle(), <del> editorText: editor.getText() <del> }) <del> }) <del> } <del> ) <del> assert.equal(editorTitle, path.basename(newFilePath)) <del> assert.equal(editorText, '') <del> assert.deepEqual(await getTreeViewRootDirectories(window), []) <add> it('opens a file with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <add> await scenario.assert('[_ 1.md]') <add> }) <add> <add> it('opens a directory with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a'])) <add> await scenario.assert('[a _]') <add> }) <add> <add> it('opens a file with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <add> await scenario.assert('[_ _] [_ 1.md]') <add> }) <add> <add> it('opens a directory with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a'])) <add> await scenario.assert('[_ _] [a _]') <ide> }) <ide> }) <ide> <del> describe('when the --add option is specified', () => { <del> // Covered <del> it('adds folders to existing windows when the --add option is used', async () => { <del> const dirAPath = makeTempDir('a') <del> const dirBPath = makeTempDir('b') <del> const dirCPath = makeTempDir('c') <del> const existingDirCFilePath = path.join(dirCPath, 'existing-file') <del> fs.writeFileSync(existingDirCFilePath, 'this is an existing file') <del> <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch( <del> parseCommandLine([dirAPath]) <del> ) <del> await focusWindow(window1) <del> <del> await conditionPromise( <del> async () => (await getTreeViewRootDirectories(window1)).length === 1 <del> ) <del> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath]) <del> <del> // When opening *files* with --add, reuses an existing window <del> let [reusedWindow] = await atomApplication.launch( <del> parseCommandLine([existingDirCFilePath, '--add']) <del> ) <del> assert.equal(reusedWindow, window1) <del> assert.deepEqual(atomApplication.getAllWindows(), [window1]) <del> let activeEditorPath = await evalInWebContents( <del> window1.browserWindow.webContents, <del> sendBackToMainProcess => { <del> const subscription = atom.workspace.onDidChangeActivePaneItem( <del> textEditor => { <del> sendBackToMainProcess(textEditor.getPath()) <del> subscription.dispose() <del> } <del> ) <del> } <del> ) <del> assert.equal(activeEditorPath, existingDirCFilePath) <del> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath]) <del> <del> // When opening *directories* with --add, reuses an existing window and adds the directory to the project <del> reusedWindow = (await atomApplication.launch( <del> parseCommandLine([dirBPath, '-a']) <del> ))[0] <del> assert.equal(reusedWindow, window1) <del> assert.deepEqual(atomApplication.getAllWindows(), [window1]) <del> <del> await conditionPromise( <del> async () => <del> (await getTreeViewRootDirectories(reusedWindow)).length === 2 <del> ) <del> assert.deepEqual(await getTreeViewRootDirectories(window1), [ <del> dirAPath, <del> dirBPath <del> ]) <add> describe('with one window that has a project root', function () { <add> beforeEach(async function () { <add> await scenario.preconditions('[a _]') <add> }) <add> <add> // This is also the case when a user clicks on a file within the project root in their file manager <add> it('opens a file within the project root', async function () { <add> await scenario.open(parseCommandLine(['a/1.md'])) <add> await scenario.assert('[a 1.md]') <add> }) <add> <add> // This is also the case when a user clicks on a project root folder in their file manager <add> it('opens a directory that matches the project root', async function () { <add> await scenario.open(parseCommandLine(['a'])) <add> await scenario.assert('[a _]') <add> }) <add> <add> // This is also the case when a user clicks on a file outside the project root in their file manager <add> it('opens a file outside the project root', async function () { <add> await scenario.open(parseCommandLine(['b/2.md'])) <add> await scenario.assert('[a 2.md]') <add> }) <add> <add> // This is also the case when a user clicks on a new folder in their file manager <add> it('opens a directory other than the project root', async function () { <add> await scenario.open(parseCommandLine(['b'])) <add> await scenario.assert('[a _] [b _]') <add> }) <add> <add> it('opens a file within the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <add> await scenario.assert('[a 1.md]') <add> }) <add> <add> it('opens a directory that matches the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a'])) <add> await scenario.assert('[a _]') <add> }) <add> <add> it('opens a file outside the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'b/2.md'])) <add> await scenario.assert('[a 2.md]') <add> }) <add> <add> it('opens a directory other than the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'b'])) <add> await scenario.assert('[a,b _]') <add> }) <add> <add> it('opens a file within the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <add> await scenario.assert('[a _] [_ 1.md]') <add> }) <add> <add> it('opens a directory that matches the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a'])) <add> await scenario.assert('[a _] [a _]') <add> }) <add> <add> it('opens a file outside the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'b/2.md'])) <add> await scenario.assert('[a _] [_ 2.md]') <add> }) <add> <add> it('opens a directory other than the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'b'])) <add> await scenario.assert('[a _] [b _]') <ide> }) <ide> }) <ide> <del> if (process.platform === 'darwin' || process.platform === 'win32') { <del> // Covered <del> it('positions new windows at an offset distance from the previous window', async () => { <del> const atomApplication = buildAtomApplication() <add> describe('with two windows, one with a project root and one empty', function () { <add> beforeEach(async function () { <add> await scenario.preconditions('[a _] [_ _]') <add> }) <ide> <del> const [window1] = await atomApplication.launch( <del> parseCommandLine([makeTempDir()]) <del> ) <del> await focusWindow(window1) <del> window1.browserWindow.setBounds({ width: 400, height: 400, x: 0, y: 0 }) <add> // This is also the case when a user clicks on a file within the project root in their file manager <add> it('opens a file within the project root', async function () { <add> await scenario.open(parseCommandLine(['a/1.md'])) <add> await scenario.assert('[a 1.md] [_ _]') <add> }) <ide> <del> const [window2] = await atomApplication.launch( <del> parseCommandLine([makeTempDir()]) <del> ) <del> await focusWindow(window2) <add> // This is also the case when a user clicks on a project root folder in their file manager <add> it('opens a directory that matches the project root', async function () { <add> await scenario.open(parseCommandLine(['a'])) <add> await scenario.assert('[a _] [_ _]') <add> }) <ide> <del> assert.notEqual(window1, window2) <del> const window1Dimensions = window1.getDimensions() <del> const window2Dimensions = window2.getDimensions() <del> assert.isAbove(window2Dimensions.x, window1Dimensions.x) <del> assert.isAbove(window2Dimensions.y, window1Dimensions.y) <add> // This is also the case when a user clicks on a file outside the project root in their file manager <add> it('opens a file outside the project root', async function () { <add> await scenario.open(parseCommandLine(['b/2.md'])) <add> await scenario.assert('[a _] [_ 2.md]') <ide> }) <del> } <ide> <del> // Covered <del> it('persists window state based on the project directories', async () => { <del> // Choosing "Don't save" <del> mockElectronShowMessageBox({ response: 2 }) <del> <del> const tempDirPath = makeTempDir() <del> const atomApplication = buildAtomApplication() <del> const nonExistentFilePath = path.join(tempDirPath, 'new-file') <del> <del> const [window1] = await atomApplication.launch( <del> parseCommandLine([tempDirPath, nonExistentFilePath]) <del> ) <del> await evalInWebContents( <del> window1.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(textEditor => { <del> textEditor.insertText('Hello World!') <del> sendBackToMainProcess(null) <del> }) <del> } <del> ) <del> await window1.prepareToUnload() <del> window1.close() <del> await window1.closedPromise <del> <del> // Restore unsaved state when opening the same project directory <del> const [window2] = await atomApplication.launch( <del> parseCommandLine([tempDirPath]) <del> ) <del> await window2.loadedPromise <del> const window2Text = await evalInWebContents( <del> window2.browserWindow.webContents, <del> sendBackToMainProcess => { <del> const textEditor = atom.workspace.getActiveTextEditor() <del> textEditor.moveToBottom() <del> textEditor.insertText(' How are you?') <del> sendBackToMainProcess(textEditor.getText()) <del> } <del> ) <del> assert.equal(window2Text, 'Hello World! How are you?') <add> // This is also the case when a user clicks on a new folder in their file manager <add> it('opens a directory other than the project root', async function () { <add> await scenario.open(parseCommandLine(['b'])) <add> await scenario.assert('[a _] [b _]') <add> }) <add> <add> it('opens a file within the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <add> await scenario.assert('[a 1.md] [_ _]') <add> }) <add> <add> it('opens a directory that matches the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a'])) <add> await scenario.assert('[a _] [_ _]') <add> }) <add> <add> it('opens a file outside the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'b/2.md'])) <add> await scenario.assert('[a _] [_ 2.md]') <add> }) <add> <add> it('opens a directory other than the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'b'])) <add> await scenario.assert('[a _] [b _]') <add> }) <add> <add> it('opens a file within the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <add> await scenario.assert('[a _] [_ _] [_ 1.md]') <add> }) <add> <add> it('opens a directory that matches the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a'])) <add> await scenario.assert('[a _] [_ _] [a _]') <add> }) <add> <add> it('opens a file outside the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'b/2.md'])) <add> await scenario.assert('[a _] [_ _] [_ 2.md]') <add> }) <add> <add> it('opens a directory other than the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'b'])) <add> await scenario.assert('[a _] [_ _] [b _]') <add> }) <ide> }) <ide> <del> // Covered <del> it('adds a remote directory to the project when launched with a remote directory', async () => { <del> const packagePath = path.join( <del> __dirname, <del> '..', <del> 'fixtures', <del> 'packages', <del> 'package-with-directory-provider' <del> ) <del> const packagesDirPath = path.join(process.env.ATOM_HOME, 'packages') <del> fs.mkdirSync(packagesDirPath) <del> fs.symlinkSync( <del> packagePath, <del> path.join(packagesDirPath, 'package-with-directory-provider'), <del> 'junction' <del> ) <del> <del> const atomApplication = buildAtomApplication() <del> atomApplication.config.set('core.disabledPackages', ['fuzzy-finder']) <del> <del> const remotePath = 'remote://server:3437/some/directory/path' <del> let [window] = await atomApplication.launch( <del> parseCommandLine([remotePath]) <del> ) <del> <del> await focusWindow(window) <del> await conditionPromise( <del> async () => (await getProjectDirectories()).length > 0 <del> ) <del> let directories = await getProjectDirectories() <del> assert.deepEqual(directories, [ <del> { type: 'FakeRemoteDirectory', path: remotePath } <del> ]) <del> <del> await window.reload() <del> await focusWindow(window) <del> directories = await getProjectDirectories() <del> assert.deepEqual(directories, [ <del> { type: 'FakeRemoteDirectory', path: remotePath } <del> ]) <del> <del> function getProjectDirectories () { <del> return evalInWebContents( <del> window.browserWindow.webContents, <del> sendBackToMainProcess => { <del> sendBackToMainProcess( <del> atom.project <del> .getDirectories() <del> .map(d => ({ type: d.constructor.name, path: d.getPath() })) <del> ) <del> } <del> ) <del> } <add> describe('with two windows, one empty and one with a project root', function () { <add> beforeEach(async function () { <add> await scenario.preconditions('[_ _] [a _]') <add> }) <add> <add> // This is also the case when a user clicks on a file within the project root in their file manager <add> it('opens a file within the project root', async function () { <add> await scenario.open(parseCommandLine(['a/1.md'])) <add> await scenario.assert('[_ _] [a 1.md]') <add> }) <add> <add> // This is also the case when a user clicks on a project root folder in their file manager <add> it('opens a directory that matches the project root', async function () { <add> await scenario.open(parseCommandLine(['a'])) <add> await scenario.assert('[_ _] [a _]') <add> }) <add> <add> // This is also the case when a user clicks on a file outside the project root in their file manager <add> it('opens a file outside the project root', async function () { <add> await scenario.open(parseCommandLine(['b/2.md'])) <add> await scenario.assert('[_ 2.md] [a _]') <add> }) <add> <add> // This is also the case when a user clicks on a new folder in their file manager <add> it('opens a directory other than the project root', async function () { <add> await scenario.open(parseCommandLine(['b'])) <add> await scenario.assert('[b _] [a _]') <add> }) <add> <add> it('opens a file within the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a/1.md'])) <add> await scenario.assert('[_ _] [a 1.md]') <add> }) <add> <add> it('opens a directory that matches the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'a'])) <add> await scenario.assert('[_ _] [a _]') <add> }) <add> <add> it('opens a file outside the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'b/2.md'])) <add> await scenario.assert('[_ _] [a 2.md]') <add> }) <add> <add> it('opens a directory other than the project root with --add', async function () { <add> await scenario.open(parseCommandLine(['--add', 'b'])) <add> await scenario.assert('[_ _] [a,b _]') <add> }) <add> <add> it('opens a file within the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a/1.md'])) <add> await scenario.assert('[_ _] [a _] [_ 1.md]') <add> }) <add> <add> it('opens a directory that matches the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'a'])) <add> await scenario.assert('[_ _] [a _] [a _]') <add> }) <add> <add> it('opens a file outside the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'b/2.md'])) <add> await scenario.assert('[_ _] [a _] [_ 2.md]') <add> }) <add> <add> it('opens a directory other than the project root with --new-window', async function () { <add> await scenario.open(parseCommandLine(['--new-window', 'b'])) <add> await scenario.assert('[_ _] [a _] [b _]') <add> }) <ide> }) <ide> <del> // Covered <del> it('does not reopen any previously opened windows when launched with no path and `core.restorePreviousWindowsOnStart` is no', async () => { <del> const atomApplication1 = buildAtomApplication() <del> const [app1Window1] = await atomApplication1.launch( <del> parseCommandLine([makeTempDir()]) <del> ) <del> await focusWindow(app1Window1) <del> <del> const [app1Window2] = await atomApplication1.launch( <del> parseCommandLine([makeTempDir()]) <del> ) <del> await focusWindow(app1Window2) <del> <del> const configPath = path.join(process.env.ATOM_HOME, 'config.cson') <del> const config = season.readFileSync(configPath) <del> if (!config['*'].core) config['*'].core = {} <del> config['*'].core.restorePreviousWindowsOnStart = 'no' <del> season.writeFileSync(configPath, config) <del> <del> const atomApplication2 = buildAtomApplication() <del> const [app2Window] = await atomApplication2.launch(parseCommandLine([])) <del> await focusWindow(app2Window) <del> assert.deepEqual(app2Window.initialProjectRoots, []) <add> describe('--wait', function () { <add> it('kills the specified pid after a newly-opened window is closed', async function () { <add> const [w0] = await scenario.launch(parseCommandLine(['--new-window', '--wait', '--pid', '101'])) <add> const w1 = await scenario.open(parseCommandLine(['--new-window', '--wait', '--pid', '202'])) <add> <add> assert.lengthOf(scenario.killedPids, 0) <add> <add> w0.browserWindow.emit('closed') <add> assert.deepEqual(scenario.killedPids, [101]) <add> <add> w1.browserWindow.emit('closed') <add> assert.deepEqual(scenario.killedPids, [101, 202]) <add> }) <add> <add> it('kills the specified pid after all newly-opened files in an existing window are closed', async function () { <add> const [w] = await scenario.launch(parseCommandLine(['--new-window', 'a'])) <add> await scenario.open(parseCommandLine(['--add', '--wait', '--pid', '303', 'a/1.md', 'b/2.md'])) <add> await scenario.assert('[a 1.md,2.md]') <add> <add> assert.lengthOf(scenario.killedPids, 0) <add> <add> scenario.getApplication(0).windowDidClosePathWithWaitSession(w, scenario.convertEditorPath('b/2.md')) <add> assert.lengthOf(scenario.killedPids, 0) <add> scenario.getApplication(0).windowDidClosePathWithWaitSession(w, scenario.convertEditorPath('a/1.md')) <add> assert.deepEqual(scenario.killedPids, [303]) <add> }) <add> <add> it('kills the specified pid after a newly-opened directory in an existing window is closed', async function () { <add> const [w] = await scenario.launch(parseCommandLine(['--new-window', 'a'])) <add> await scenario.open(parseCommandLine(['--add', '--wait', '--pid', '404', 'b'])) <add> await scenario.assert('[a,b _]') <add> <add> assert.lengthOf(scenario.killedPids, 0) <add> <add> scenario.getApplication(0).windowDidClosePathWithWaitSession(w, scenario.convertRootPath('b')) <add> assert.deepEqual(scenario.killedPids, [404]) <add> }) <ide> }) <ide> <del> describe('when the `--wait` flag is passed', () => { <del> let killedPids, atomApplication, onDidKillProcess <add> describe('atom:// URLs', function () { <add> describe('with a package-name host', function () { <add> it("loads the package's urlMain in a new window", async function () { <add> await scenario.launch({}) <ide> <del> beforeEach(() => { <del> killedPids = [] <del> onDidKillProcess = null <del> atomApplication = buildAtomApplication({ <del> killProcess (pid) { <del> killedPids.push(pid) <del> if (onDidKillProcess) onDidKillProcess() <add> const app = scenario.getApplication(0) <add> app.packages = { <add> getAvailablePackageMetadata: () => [{name: 'package-with-url-main', urlMain: 'some/url-main'}], <add> resolvePackagePath: () => path.resolve('dot-atom/package-with-url-main') <ide> } <del> }) <del> }) <ide> <del> // Covered <del> it('kills the specified pid after a newly-opened window is closed', async () => { <del> const [window1] = await atomApplication.launch( <del> parseCommandLine(['--wait', '--pid', '101']) <del> ) <del> await focusWindow(window1) <add> const [w1, w2] = await scenario.open(parseCommandLine([ <add> 'atom://package-with-url-main/test1', <add> 'atom://package-with-url-main/test2' <add> ])) <ide> <del> const [window2] = await atomApplication.launch( <del> parseCommandLine(['--new-window', '--wait', '--pid', '102']) <del> ) <del> await focusWindow(window2) <del> assert.deepEqual(killedPids, []) <add> assert.strictEqual( <add> w1.loadSettings.windowInitializationScript, <add> path.resolve('dot-atom/package-with-url-main/some/url-main') <add> ) <add> assert.strictEqual( <add> w1.loadSettings.urlToOpen, <add> 'atom://package-with-url-main/test1' <add> ) <ide> <del> let processKillPromise = new Promise(resolve => { <del> onDidKillProcess = resolve <add> assert.strictEqual( <add> w2.loadSettings.windowInitializationScript, <add> path.resolve('dot-atom/package-with-url-main/some/url-main') <add> ) <add> assert.strictEqual( <add> w2.loadSettings.urlToOpen, <add> 'atom://package-with-url-main/test2' <add> ) <ide> }) <del> window1.close() <del> await processKillPromise <del> assert.deepEqual(killedPids, [101]) <ide> <del> processKillPromise = new Promise(resolve => { <del> onDidKillProcess = resolve <del> }) <del> window2.close() <del> await processKillPromise <del> assert.deepEqual(killedPids, [101, 102]) <del> }) <del> <del> // Covered <del> it('kills the specified pid after a newly-opened file in an existing window is closed', async () => { <del> const projectDir = makeTempDir('existing') <del> const filePath1 = path.join(projectDir, 'file-1') <del> const filePath2 = path.join(projectDir, 'file-2') <del> fs.writeFileSync(filePath1, 'File 1') <del> fs.writeFileSync(filePath2, 'File 2') <del> <del> const [window] = await atomApplication.launch( <del> parseCommandLine(['--wait', '--pid', '101', projectDir]) <del> ) <del> await focusWindow(window) <del> <del> const [reusedWindow] = await atomApplication.launch( <del> parseCommandLine([ <del> '--add', <del> '--wait', <del> '--pid', <del> '102', <del> filePath1, <del> filePath2 <del> ]) <del> ) <del> assert.equal(reusedWindow, window) <del> <del> const activeEditorPath = await evalInWebContents( <del> window.browserWindow.webContents, <del> send => { <del> const subscription = atom.workspace.onDidChangeActivePaneItem( <del> editor => { <del> send(editor.getPath()) <del> subscription.dispose() <del> } <del> ) <add> it('sends a URI message to the most recently focused non-spec window', async function () { <add> const [w0] = await scenario.launch({}) <add> const w1 = await scenario.open(parseCommandLine(['--new-window'])) <add> const w2 = await scenario.open(parseCommandLine(['--new-window'])) <add> const w3 = await scenario.open(parseCommandLine(['--test', 'a/1.md'])) <add> <add> const app = scenario.getApplication(0) <add> app.packages = { <add> getAvailablePackageMetadata: () => [] <ide> } <del> ) <ide> <del> assert([filePath1, filePath2].includes(activeEditorPath)) <del> assert.deepEqual(killedPids, []) <add> const [uw] = await scenario.open(parseCommandLine(['atom://package-without-url-main/test'])) <add> assert.strictEqual(uw, w2) <ide> <del> await evalInWebContents(window.browserWindow.webContents, send => { <del> atom.workspace.getActivePaneItem().destroy() <del> send() <del> }) <del> await timeoutPromise(100) <del> assert.deepEqual(killedPids, []) <add> assert.isTrue(w2.sendURIMessage.calledWith('atom://package-without-url-main/test')) <add> assert.strictEqual(w2.focus.callCount, 2) <ide> <del> let processKillPromise = new Promise(resolve => { <del> onDidKillProcess = resolve <add> for (const other of [w0, w1, w3]) { <add> assert.isFalse(other.sendURIMessage.called) <add> } <ide> }) <del> await evalInWebContents(window.browserWindow.webContents, send => { <del> atom.workspace.getActivePaneItem().destroy() <del> send() <add> <add> it('creates a new window and sends a URI message to it once it loads', async function () { <add> const [w0] = await scenario.launch(parseCommandLine(['--test', 'a/1.md'])) <add> <add> const app = scenario.getApplication(0) <add> app.packages = { <add> getAvailablePackageMetadata: () => [] <add> } <add> <add> const [uw] = await scenario.open(parseCommandLine(['atom://package-without-url-main/test'])) <add> assert.notStrictEqual(uw, w0) <add> assert.strictEqual( <add> uw.loadSettings.windowInitializationScript, <add> path.resolve(__dirname, '../../src/initialize-application-window.coffee') <add> ) <add> <add> uw.emit('window:loaded') <add> assert.isTrue(uw.sendURIMessage.calledWith('atom://package-without-url-main/test')) <ide> }) <del> await processKillPromise <del> assert.deepEqual(killedPids, [102]) <add> }) <ide> <del> processKillPromise = new Promise(resolve => { <del> onDidKillProcess = resolve <add> describe('with a "core" host', function () { <add> it('sends a URI message to the most recently focused non-spec window that owns the open locations', async function () { <add> const [w0] = await scenario.launch(parseCommandLine(['a'])) <add> const w1 = await scenario.open(parseCommandLine(['--new-window', 'a'])) <add> const w2 = await scenario.open(parseCommandLine(['--new-window', 'b'])) <add> <add> const uri = `atom://core/open/file?filename=${encodeURIComponent(scenario.convertEditorPath('a/1.md'))}` <add> const [uw] = await scenario.open(parseCommandLine([uri])) <add> assert.strictEqual(uw, w1) <add> assert.isTrue(w1.sendURIMessage.calledWith(uri)) <add> <add> for (const other of [w0, w2]) { <add> assert.isFalse(other.sendURIMessage.called) <add> } <ide> }) <del> window.close() <del> await processKillPromise <del> assert.deepEqual(killedPids, [102, 101]) <del> }) <del> <del> // Covered <del> it('kills the specified pid after a newly-opened directory in an existing window is closed', async () => { <del> const [window] = await atomApplication.launch(parseCommandLine([])) <del> await focusWindow(window) <del> <del> const dirPath1 = makeTempDir() <del> const [reusedWindow] = await atomApplication.launch( <del> parseCommandLine(['--add', '--wait', '--pid', '101', dirPath1]) <del> ) <del> assert.equal(reusedWindow, window) <del> await conditionPromise( <del> async () => (await getTreeViewRootDirectories(window)).length === 1 <del> ) <del> assert.deepEqual(await getTreeViewRootDirectories(window), [dirPath1]) <del> assert.deepEqual(killedPids, []) <del> <del> const dirPath2 = makeTempDir() <del> await evalInWebContents( <del> window.browserWindow.webContents, <del> (send, dirPath1, dirPath2) => { <del> atom.project.setPaths([dirPath1, dirPath2]) <del> send() <del> }, <del> dirPath1, <del> dirPath2 <del> ) <del> await timeoutPromise(100) <del> assert.deepEqual(killedPids, []) <del> <del> let processKillPromise = new Promise(resolve => { <del> onDidKillProcess = resolve <add> <add> it('creates a new window and sends a URI message to it once it loads', async function () { <add> const [w0] = await scenario.launch(parseCommandLine(['--test', 'a/1.md'])) <add> <add> const uri = `atom://core/open/file?filename=${encodeURIComponent(scenario.convertEditorPath('b/2.md'))}` <add> const [uw] = await scenario.open(parseCommandLine([uri])) <add> assert.notStrictEqual(uw, w0) <add> <add> uw.emit('window:loaded') <add> assert.isTrue(uw.sendURIMessage.calledWith(uri)) <ide> }) <del> await evalInWebContents( <del> window.browserWindow.webContents, <del> (send, dirPath2) => { <del> atom.project.setPaths([dirPath2]) <del> send() <del> }, <del> dirPath2 <del> ) <del> await processKillPromise <del> assert.deepEqual(killedPids, [101]) <ide> }) <ide> }) <ide> <del> describe('when closing the last window', () => { <del> if (process.platform === 'linux' || process.platform === 'win32') { <del> // Covered <del> it('quits the application', async () => { <del> const atomApplication = buildAtomApplication() <del> const [window] = await atomApplication.launch( <del> parseCommandLine([path.join(makeTempDir('a'), 'file-a')]) <del> ) <del> await focusWindow(window) <del> await emitterEventPromise(window, 'window:locations-opened') <add> it('opens a file to a specific line number', async function () { <add> await scenario.open(parseCommandLine(['a/1.md:10'])) <add> await scenario.assert('[_ 1.md]') <ide> <del> // Choosing "Don't save" <del> mockElectronShowMessageBox({ response: 2 }) <add> const w = scenario.getWindow(0) <add> assert.lengthOf(w._locations, 1) <add> assert.strictEqual(w._locations[0].initialLine, 9) <add> assert.isNull(w._locations[0].initialColumn) <add> }) <ide> <del> window.close() <del> await window.closedPromise <del> await atomApplication.lastBeforeQuitPromise <del> assert(electron.app.didQuit()) <del> }) <del> } else if (process.platform === 'darwin') { <del> // Covered <del> it('leaves the application open', async () => { <del> const atomApplication = buildAtomApplication() <del> const [window] = await atomApplication.launch( <del> parseCommandLine([path.join(makeTempDir('a'), 'file-a')]) <del> ) <del> await focusWindow(window) <del> await emitterEventPromise(window, 'window:locations-opened') <add> it('opens a file to a specific line number', async function () { <add> await scenario.open(parseCommandLine('b/2.md:12:5')) <add> await scenario.assert('[_ 2.md]') <ide> <del> // Choosing "Don't save" <del> mockElectronShowMessageBox({ response: 2 }) <add> const w = scenario.getWindow(0) <add> assert.lengthOf(w._locations, 1) <add> assert.strictEqual(w._locations[0].initialLine, 11) <add> assert.strictEqual(w._locations[0].initialColumn, 4) <add> }) <ide> <del> window.close() <del> await window.closedPromise <del> await timeoutPromise(1000) <del> assert(!electron.app.didQuit()) <del> }) <del> } <add> it('opens a directory with a non-file protocol', async function () { <add> await scenario.open(parseCommandLine(['remote://server:3437/some/directory/path'])) <add> <add> const w = scenario.getWindow(0) <add> assert.lengthOf(w._locations, 1) <add> assert.strictEqual(w._locations[0].pathToOpen, 'remote://server:3437/some/directory/path') <add> assert.isFalse(w._locations[0].exists) <add> assert.isFalse(w._locations[0].isDirectory) <add> assert.isFalse(w._locations[0].isFile) <ide> }) <ide> <del> describe('when adding or removing project folders', () => { <del> // Covered <del> it('stores the window state immediately', async () => { <del> const dirA = makeTempDir() <del> const dirB = makeTempDir() <del> <del> const atomApplication = buildAtomApplication() <del> const [window0] = await atomApplication.launch( <del> parseCommandLine([dirA, dirB]) <del> ) <del> await focusWindow(window0) <del> await conditionPromise( <del> async () => (await getTreeViewRootDirectories(window0)).length === 2 <del> ) <del> assert.deepEqual(await getTreeViewRootDirectories(window0), [ <del> dirA, <del> dirB <del> ]) <del> <del> const saveStatePromise = emitterEventPromise( <del> atomApplication, <del> 'application:did-save-state' <del> ) <del> await evalInWebContents( <del> window0.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.project.removePath(atom.project.getPaths()[0]) <del> sendBackToMainProcess(null) <del> } <del> ) <del> assert.deepEqual(await getTreeViewRootDirectories(window0), [dirB]) <del> await saveStatePromise <del> <del> // Window state should be saved when the project folder is removed <del> const atomApplication2 = buildAtomApplication() <del> const [window2] = await atomApplication2.launch(parseCommandLine([])) <del> await focusWindow(window2) <del> await conditionPromise( <del> async () => (await getTreeViewRootDirectories(window2)).length === 1 <del> ) <del> assert.deepEqual(await getTreeViewRootDirectories(window2), [dirB]) <del> }) <add> it('truncates trailing whitespace and colons', async function () { <add> await scenario.open(parseCommandLine('b/2.md:: ')) <add> await scenario.assert('[_ 2.md]') <add> <add> const w = scenario.getWindow(0) <add> assert.lengthOf(w._locations, 1) <add> assert.isNull(w._locations[0].initialLine) <add> assert.isNull(w._locations[0].initialColumn) <ide> }) <add> }) <ide> <del> describe('when opening atom:// URLs', () => { <del> // Covered <del> it('loads the urlMain file in a new window', async () => { <del> const packagePath = path.join( <del> __dirname, <del> '..', <del> 'fixtures', <del> 'packages', <del> 'package-with-url-main' <del> ) <del> const packagesDirPath = path.join(process.env.ATOM_HOME, 'packages') <del> fs.mkdirSync(packagesDirPath) <del> fs.symlinkSync( <del> packagePath, <del> path.join(packagesDirPath, 'package-with-url-main'), <del> 'junction' <del> ) <del> <del> const atomApplication = buildAtomApplication() <del> const launchOptions = parseCommandLine([]) <del> launchOptions.urlsToOpen = ['atom://package-with-url-main/test'] <del> let [windows] = await atomApplication.launch(launchOptions) <del> await windows[0].loadedPromise <del> <del> let reached = await evalInWebContents( <del> windows[0].browserWindow.webContents, <del> sendBackToMainProcess => { <del> sendBackToMainProcess(global.reachedUrlMain) <del> } <del> ) <del> assert.isTrue(reached) <del> windows[0].close() <del> }) <del> <del> // Covered <del> it('triggers /core/open/file in the correct window', async function () { <del> const dirAPath = makeTempDir('a') <del> const dirBPath = makeTempDir('b') <del> <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch( <del> parseCommandLine([path.join(dirAPath)]) <del> ) <del> await focusWindow(window1) <del> const [window2] = await atomApplication.launch( <del> parseCommandLine([path.join(dirBPath)]) <del> ) <del> await focusWindow(window2) <del> <del> const fileA = path.join(dirAPath, 'file-a') <del> const uriA = `atom://core/open/file?filename=${fileA}` <del> const fileB = path.join(dirBPath, 'file-b') <del> const uriB = `atom://core/open/file?filename=${fileB}` <del> <del> sinon.spy(window1, 'sendURIMessage') <del> sinon.spy(window2, 'sendURIMessage') <del> <del> atomApplication.launch(parseCommandLine(['--uri-handler', uriA])) <del> await conditionPromise( <del> () => window1.sendURIMessage.calledWith(uriA), <del> `window1 to be focused from ${fileA}` <del> ) <del> <del> atomApplication.launch(parseCommandLine(['--uri-handler', uriB])) <del> await conditionPromise( <del> () => window2.sendURIMessage.calledWith(uriB), <del> `window2 to be focused from ${fileB}` <del> ) <add> if (process.platform === 'darwin' || process.platform === 'win32') { <add> it('positions new windows at an offset from the previous window', async function () { <add> const [w0] = await scenario.launch(parseCommandLine(['a'])) <add> w0.setSize(400, 400) <add> const d0 = w0.getDimensions() <add> <add> const w1 = await scenario.open(parseCommandLine(['b'])) <add> const d1 = w1.getDimensions() <add> <add> assert.isAbove(d0.x, d1.x) <add> assert.isAbove(d0.y, d1.y) <add> }) <add> } <add> <add> if (process.platform === 'darwin') { <add> describe('with no windows open', function () { <add> let app <add> <add> beforeEach(async function () { <add> const [w] = await scenario.launch(parseCommandLine([])) <add> <add> app = scenario.getApplication(0) <add> app.removeWindow(w) <add> sinon.stub(app, 'promptForPathToOpen') <add> }) <add> <add> it('opens a new file', function () { <add> app.emit('application:open-file') <add> assert.isTrue(app.promptForPathToOpen.calledWith('file', {devMode: false, safeMode: false, window: null})) <add> }) <add> <add> it('opens a new directory', function () { <add> app.emit('application:open-folder') <add> assert.isTrue(app.promptForPathToOpen.calledWith('folder', {devMode: false, safeMode: false, window: null})) <add> }) <add> <add> it('opens a new file or directory', function () { <add> app.emit('application:open') <add> assert.isTrue(app.promptForPathToOpen.calledWith('all', {devMode: false, safeMode: false, window: null})) <add> }) <add> <add> it('reopens a project in a new window', async function () { <add> const paths = scenario.convertPaths(['a', 'b']) <add> app.emit('application:reopen-project', {paths}) <add> <add> await conditionPromise(() => app.getAllWindows().length > 0) <add> <add> assert.deepEqual(app.getAllWindows().map(w => Array.from(w._rootPaths)), [paths]) <ide> }) <ide> }) <del> }) <add> } <ide> <del> // Covered <del> it('waits until all the windows have saved their state before quitting', async () => { <del> const dirAPath = makeTempDir('a') <del> const dirBPath = makeTempDir('b') <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([dirAPath])) <del> await focusWindow(window1) <del> const [window2] = await atomApplication.launch(parseCommandLine([dirBPath])) <del> await focusWindow(window2) <del> electron.app.quit() <del> await new Promise(process.nextTick) <del> assert(!electron.app.didQuit()) <del> <del> await Promise.all([ <del> window1.lastPrepareToUnloadPromise, <del> window2.lastPrepareToUnloadPromise <del> ]) <del> assert(!electron.app.didQuit()) <del> await atomApplication.lastBeforeQuitPromise <del> await new Promise(process.nextTick) <del> assert(electron.app.didQuit()) <del> }) <add> describe('existing application re-use', function () { <add> let createApplication <add> <add> const version = electron.app.getVersion() <ide> <del> // Covered <del> it('prevents quitting if user cancels when prompted to save an item', async () => { <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([])) <del> const [window2] = await atomApplication.launch(parseCommandLine([])) <del> await Promise.all([window1.loadedPromise, window2.loadedPromise]) <del> await evalInWebContents( <del> window1.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.workspace.getActiveTextEditor().insertText('unsaved text') <del> sendBackToMainProcess() <add> beforeEach(function () { <add> createApplication = async options => { <add> options.version = version <add> <add> const app = scenario.addApplication(options) <add> await app.listenForArgumentsFromNewProcess() <add> await app.launch(options) <add> return app <ide> } <del> ) <add> }) <add> <add> it('creates a new application when no socket is present', async function () { <add> const app0 = await AtomApplication.open({createApplication, version}) <add> app0.deleteSocketSecretFile() <add> <add> const app1 = await AtomApplication.open({createApplication, version}) <add> assert.isNotNull(app1) <add> assert.notStrictEqual(app0, app1) <add> }) <add> <add> it('creates a new application for spec windows', async function () { <add> const app0 = await AtomApplication.open({createApplication, version}) <add> <add> const app1 = await AtomApplication.open({createApplication, version, ...parseCommandLine(['--test', 'a'])}) <add> assert.isNotNull(app1) <add> assert.notStrictEqual(app0, app1) <add> }) <ide> <del> // Choosing "Cancel" <del> mockElectronShowMessageBox({ response: 1 }) <del> electron.app.quit() <del> await atomApplication.lastBeforeQuitPromise <del> assert(!electron.app.didQuit()) <del> assert.equal(electron.app.quit.callCount, 1) // Ensure choosing "Cancel" doesn't try to quit the electron app more than once (regression) <del> <del> // Choosing "Don't save" <del> mockElectronShowMessageBox({ response: 2 }) <del> electron.app.quit() <del> await atomApplication.lastBeforeQuitPromise <del> assert(electron.app.didQuit()) <add> it('sends a request to an existing application when a socket is present', async function () { <add> const app0 = await AtomApplication.open({createApplication, version}) <add> assert.lengthOf(app0.getAllWindows(), 1) <add> <add> const app1 = await AtomApplication.open({createApplication, version, ...parseCommandLine(['--new-window'])}) <add> assert.isNull(app1) <add> assert.isTrue(electron.app.quit.called) <add> <add> await conditionPromise(() => app0.getAllWindows().length === 2) <add> await scenario.assert('[_ _] [_ _]') <add> }) <ide> }) <ide> <del> // Covered <del> it('closes successfully unloaded windows when quitting', async () => { <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([])) <del> const [window2] = await atomApplication.launch(parseCommandLine([])) <del> await Promise.all([window1.loadedPromise, window2.loadedPromise]) <del> await evalInWebContents( <del> window1.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.workspace.getActiveTextEditor().insertText('unsaved text') <del> sendBackToMainProcess() <del> } <del> ) <add> describe('window state serialization', function () { <add> it('occurs immediately when adding a window', async function () { <add> await scenario.launch(parseCommandLine(['a'])) <add> <add> const promise = emitterEventPromise(scenario.getApplication(0), 'application:did-save-state') <add> await scenario.open(parseCommandLine(['c', 'b'])) <add> await promise <add> <add> assert.isTrue(scenario.getApplication(0).storageFolder.store.calledWith( <add> 'application.json', <add> [ <add> {initialPaths: [scenario.convertRootPath('a')]}, <add> {initialPaths: [scenario.convertRootPath('b'), scenario.convertRootPath('c')]} <add> ] <add> )) <add> }) <add> <add> it('occurs immediately when removing a window', async function () { <add> await scenario.launch(parseCommandLine(['a'])) <add> const w = await scenario.open(parseCommandLine(['b'])) <add> <add> const promise = emitterEventPromise(scenario.getApplication(0), 'application:did-save-state') <add> scenario.getApplication(0).removeWindow(w) <add> await promise <add> <add> assert.isTrue(scenario.getApplication(0).storageFolder.store.calledWith( <add> 'application.json', <add> [ <add> {initialPaths: [scenario.convertRootPath('a')]} <add> ] <add> )) <add> }) <add> <add> it('occurs when the window is blurred', async function () { <add> const [w] = await scenario.launch(parseCommandLine(['a'])) <add> const promise = emitterEventPromise(scenario.getApplication(0), 'application:did-save-state') <add> w.browserWindow.emit('blur') <add> await promise <add> }) <add> }) <ide> <del> // Choosing "Cancel" <del> mockElectronShowMessageBox({ response: 1 }) <del> electron.app.quit() <del> await atomApplication.lastBeforeQuitPromise <del> assert(atomApplication.getAllWindows().length === 1) <del> <del> // Choosing "Don't save" <del> mockElectronShowMessageBox({ response: 2 }) <del> electron.app.quit() <del> await atomApplication.lastBeforeQuitPromise <del> assert(atomApplication.getAllWindows().length === 0) <add> describe('when closing the last window', function () { <add> if (process.platform === 'linux' || process.platform === 'win32') { <add> it('quits the application', async function () { <add> const [w] = await scenario.launch(parseCommandLine(['a'])) <add> w.browserWindow.emit('closed') <add> assert.isTrue(electron.app.quit.called) <add> }) <add> } else if (process.platform === 'darwin') { <add> it('leaves the application open', async function () { <add> const [w] = await scenario.launch(parseCommandLine(['a'])) <add> w.browserWindow.emit('closed') <add> assert.isFalse(electron.app.quit.called) <add> }) <add> } <ide> }) <ide> <del> if (process.platform === 'darwin') { <del> // Covered <del> it('allows opening a new folder after all windows are closed', async () => { <del> const atomApplication = buildAtomApplication() <del> sinon.stub(atomApplication, 'promptForPathToOpen') <del> <del> // Open a window and then close it, leaving the app running <del> const [window] = await atomApplication.launch(parseCommandLine([])) <del> await focusWindow(window) <del> window.close() <del> await window.closedPromise <del> <del> atomApplication.emit('application:open') <del> await conditionPromise(() => <del> atomApplication.promptForPathToOpen.calledWith('all') <del> ) <del> atomApplication.promptForPathToOpen.reset() <del> <del> atomApplication.emit('application:open-file') <del> await conditionPromise(() => <del> atomApplication.promptForPathToOpen.calledWith('file') <del> ) <del> atomApplication.promptForPathToOpen.reset() <del> <del> atomApplication.emit('application:open-folder') <del> await conditionPromise(() => <del> atomApplication.promptForPathToOpen.calledWith('folder') <del> ) <del> atomApplication.promptForPathToOpen.reset() <add> describe('quitting', function () { <add> it('waits until all windows have saved their state before quitting', async function () { <add> const [w0] = await scenario.launch(parseCommandLine(['a'])) <add> const w1 = await scenario.open(parseCommandLine(['b'])) <add> <add> sinon.spy(w0, 'close') <add> let resolveUnload0 <add> w0.prepareToUnload = () => new Promise(resolve => { resolveUnload0 = resolve }) <add> <add> sinon.spy(w1, 'close') <add> let resolveUnload1 <add> w1.prepareToUnload = () => new Promise(resolve => { resolveUnload1 = resolve }) <add> <add> const evt = {preventDefault: sinon.spy()} <add> electron.app.emit('before-quit', evt) <add> await new Promise(process.nextTick) <add> assert.isTrue(evt.preventDefault.called) <add> assert.isFalse(electron.app.quit.called) <add> <add> resolveUnload1(true) <add> await new Promise(process.nextTick) <add> assert.isFalse(electron.app.quit.called) <add> <add> resolveUnload0(true) <add> await scenario.getApplication(0).lastBeforeQuitPromise <add> assert.isTrue(electron.app.quit.called) <add> <add> assert.isTrue(w0.close.called) <add> assert.isTrue(w1.close.called) <ide> }) <ide> <del> // Covered <del> it('allows reopening an existing project after all windows are closed', async () => { <del> const tempDirPath = makeTempDir('reopen') <add> it('prevents a quit if a user cancels when prompted to save', async function () { <add> const [w] = await scenario.launch(parseCommandLine(['a'])) <add> let resolveUnload <add> w.prepareToUnload = () => new Promise(resolve => { resolveUnload = resolve }) <ide> <del> const atomApplication = buildAtomApplication() <del> sinon.stub(atomApplication, 'promptForPathToOpen') <add> const evt = {preventDefault: sinon.spy()} <add> electron.app.emit('before-quit', evt) <add> await new Promise(process.nextTick) <add> assert.isTrue(evt.preventDefault.called) <ide> <del> // Open a window and then close it, leaving the app running <del> const [window] = await atomApplication.launch(parseCommandLine([])) <del> await focusWindow(window) <del> window.close() <del> await window.closedPromise <add> resolveUnload(false) <add> await scenario.getApplication(0).lastBeforeQuitPromise <ide> <del> // Reopen one of the recent projects <del> atomApplication.emit('application:reopen-project', { paths: [tempDirPath] }) <add> assert.isFalse(electron.app.quit.called) <add> }) <ide> <del> const windows = atomApplication.getAllWindows() <add> it('closes successfully unloaded windows', async function () { <add> const [w0] = await scenario.launch(parseCommandLine(['a'])) <add> const w1 = await scenario.open(parseCommandLine(['b'])) <ide> <del> assert(windows.length === 1) <add> sinon.spy(w0, 'close') <add> let resolveUnload0 <add> w0.prepareToUnload = () => new Promise(resolve => { resolveUnload0 = resolve }) <ide> <del> await focusWindow(windows[0]) <add> sinon.spy(w1, 'close') <add> let resolveUnload1 <add> w1.prepareToUnload = () => new Promise(resolve => { resolveUnload1 = resolve }) <ide> <del> await conditionPromise( <del> async () => (await getTreeViewRootDirectories(windows[0])).length === 1 <del> ) <add> const evt = {preventDefault () {}} <add> electron.app.emit('before-quit', evt) <ide> <del> // Check that the project was opened correctly. <del> assert.deepEqual( <del> await evalInWebContents( <del> windows[0].browserWindow.webContents, <del> send => { <del> send(atom.project.getPaths()) <del> } <del> ), <del> [tempDirPath] <del> ) <add> resolveUnload0(false) <add> resolveUnload1(true) <add> <add> await scenario.getApplication(0).lastBeforeQuitPromise <add> <add> assert.isFalse(electron.app.quit.called) <add> assert.isFalse(w0.close.called) <add> assert.isTrue(w1.close.called) <ide> }) <add> }) <add>}) <add> <add>class StubWindow extends EventEmitter { <add> constructor (sinon, loadSettings, options) { <add> super() <add> <add> this.loadSettings = loadSettings <add> <add> this._dimensions = {x: 100, y: 100} <add> this._position = {x: 0, y: 0} <add> this._locations = [] <add> this._rootPaths = new Set() <add> this._editorPaths = new Set() <add> <add> let resolveClosePromise <add> this.closedPromise = new Promise(resolve => { resolveClosePromise = resolve }) <add> <add> this.minimize = sinon.spy() <add> this.maximize = sinon.spy() <add> this.center = sinon.spy() <add> this.focus = sinon.spy() <add> this.show = sinon.spy() <add> this.hide = sinon.spy() <add> this.prepareToUnload = sinon.spy() <add> this.close = resolveClosePromise <add> <add> this.replaceEnvironment = sinon.spy() <add> this.disableZoom = sinon.spy() <add> <add> this.isFocused = sinon.stub().returns(options.isFocused !== undefined ? options.isFocused : false) <add> this.isMinimized = sinon.stub().returns(options.isMinimized !== undefined ? options.isMinimized : false) <add> this.isMaximized = sinon.stub().returns(options.isMaximized !== undefined ? options.isMaximized : false) <add> <add> this.sendURIMessage = sinon.spy() <add> this.didChangeUserSettings = sinon.spy() <add> this.didFailToReadUserSettings = sinon.spy() <add> <add> this.isSpec = loadSettings.isSpec !== undefined ? loadSettings.isSpec : false <add> this.devMode = loadSettings.devMode !== undefined ? loadSettings.devMode : false <add> this.safeMode = loadSettings.safeMode !== undefined ? loadSettings.safeMode : false <add> <add> this.browserWindow = new EventEmitter() <add> this.browserWindow.webContents = new EventEmitter() <add> <add> const locationsToOpen = this.loadSettings.locationsToOpen || [] <add> if (!(locationsToOpen.length === 1 && locationsToOpen[0].pathToOpen == null) && !this.isSpec) { <add> this.openLocations(locationsToOpen) <add> } <ide> } <ide> <del> // Covered <del> it('reuses the main process between invocations', async () => { <del> const tempDirPath1 = makeTempDir() <del> const tempDirPath2 = makeTempDir() <add> openPath (pathToOpen, initialLine, initialColumn) { <add> return this.openLocations([{pathToOpen, initialLine, initialColumn}]) <add> } <ide> <del> const options = { <del> pathsToOpen: [tempDirPath1] <add> openLocations (locations) { <add> this._locations.push(...locations) <add> for (const location of locations) { <add> if (location.pathToOpen) { <add> if (location.isDirectory) { <add> this._rootPaths.add(location.pathToOpen) <add> } else if (location.isFile) { <add> this._editorPaths.add(location.pathToOpen) <add> } <add> } <ide> } <ide> <del> // Open the main application <del> const originalApplication = buildAtomApplication(options) <del> await originalApplication.initialize(options) <add> this.projectRoots = Array.from(this._rootPaths) <add> this.projectRoots.sort() <ide> <del> // Wait until the first window gets opened <del> await conditionPromise( <del> () => originalApplication.getAllWindows().length === 1 <del> ) <add> this.emit('window:locations-opened') <add> } <add> <add> setSize (x, y) { <add> this._dimensions = {x, y} <add> } <add> <add> setPosition (x, y) { <add> this._position = {x, y} <add> } <add> <add> isSpecWindow () { <add> return this.isSpec <add> } <add> <add> hasProjectPaths () { <add> return this._rootPaths.size > 0 <add> } <add> <add> containsLocations (locations) { <add> return locations.every(location => this.containsLocation(location)) <add> } <add> <add> containsLocation (location) { <add> if (!location.pathToOpen) return false <add> <add> return Array.from(this._rootPaths).some(projectPath => { <add> if (location.pathToOpen === projectPath) return true <add> if (location.pathToOpen.startsWith(path.join(projectPath, path.sep))) { <add> if (!location.exists) return true <add> if (!location.isDirectory) return true <add> } <add> return false <add> }) <add> } <add> <add> getDimensions () { <add> return this._dimensions <add> } <add>} <add> <add>class LaunchScenario { <add> static async create (sandbox) { <add> const scenario = new this(sandbox) <add> await scenario.init() <add> return scenario <add> } <add> <add> constructor (sandbox) { <add> this.sinon = sandbox <add> <add> this.applications = new Set() <add> this.windows = new Set() <add> this.root = null <add> this.atomHome = null <add> this.projectRootPool = new Map() <add> this.filePathPool = new Map() <add> <add> this.killedPids = [] <add> this.originalAtomHome = null <add> } <add> <add> async init () { <add> if (this.root !== null) { <add> return this.root <add> } <ide> <del> // Open another instance of the application on a different path. <del> AtomApplication.open({ <del> resourcePath: ATOM_RESOURCE_PATH, <del> atomHomeDirPath: process.env.ATOM_HOME, <del> pathsToOpen: [tempDirPath2] <add> this.root = await new Promise((resolve, reject) => { <add> temp.mkdir('launch-', (err, rootPath) => { <add> if (err) { reject(err) } else { resolve(rootPath) } <add> }) <ide> }) <ide> <del> await conditionPromise( <del> () => originalApplication.getAllWindows().length === 2 <add> this.atomHome = path.join(this.root, '.atom') <add> await new Promise((resolve, reject) => { <add> fs.makeTree(this.atomHome, err => { <add> if (err) { reject(err) } else { resolve() } <add> }) <add> }) <add> this.originalAtomHome = process.env.ATOM_HOME <add> process.env.ATOM_HOME = this.atomHome <add> <add> await Promise.all( <add> ['a', 'b', 'c'].map(dirPath => new Promise((resolve, reject) => { <add> const fullDirPath = path.join(this.root, dirPath) <add> fs.makeTree(fullDirPath, err => { <add> if (err) { <add> reject(err) <add> } else { <add> this.projectRootPool.set(dirPath, fullDirPath) <add> resolve() <add> } <add> }) <add> })) <ide> ) <ide> <del> // Check that the original application now has the two opened windows. <del> assert.notEqual( <del> originalApplication.getAllWindows().find( <del> window => window.loadSettings.initialProjectRoots[0] === tempDirPath1 <del> ), <del> undefined <del> ) <del> assert.notEqual( <del> originalApplication.getAllWindows().find( <del> window => window.loadSettings.initialProjectRoots[0] === tempDirPath2 <del> ), <del> undefined <add> await Promise.all( <add> ['a/1.md', 'b/2.md'].map(filePath => new Promise((resolve, reject) => { <add> const fullFilePath = path.join(this.root, filePath) <add> fs.writeFile(fullFilePath, `file: ${filePath}\n`, {encoding: 'utf8'}, err => { <add> if (err) { <add> reject(err) <add> } else { <add> this.filePathPool.set(filePath, fullFilePath) <add> this.filePathPool.set(path.basename(filePath), fullFilePath) <add> resolve() <add> } <add> }) <add> })) <ide> ) <del> }) <ide> <del> function buildAtomApplication (params = {}) { <del> const atomApplication = new AtomApplication( <del> Object.assign( <del> { <del> resourcePath: ATOM_RESOURCE_PATH, <del> atomHomeDirPath: process.env.ATOM_HOME <del> }, <del> params <del> ) <del> ) <add> this.sinon.stub(electron.app, 'quit') <add> } <add> <add> async preconditions (source) { <add> const app = this.addApplication() <add> const windowPromises = [] <ide> <del> // Make sure that the app does not get updated automatically. <del> atomApplication.config.set('core.automaticallyUpdate', false) <add> for (const windowSpec of this.parseWindowSpecs(source)) { <add> if (windowSpec.editors.length === 0) { <add> windowSpec.editors.push(null) <add> } <ide> <del> atomApplicationsToDestroy.push(atomApplication) <del> return atomApplication <add> windowPromises.push(((theApp, foldersToOpen, pathsToOpen) => { <add> return theApp.openPaths({ newWindow: true, foldersToOpen, pathsToOpen }) <add> })(app, windowSpec.roots, windowSpec.editors)) <add> } <add> await Promise.all(windowPromises) <ide> } <ide> <del> async function focusWindow (window) { <del> window.focus() <del> await window.loadedPromise <del> await conditionPromise( <del> () => window.atomApplication.getLastFocusedWindow() === window <del> ) <add> launch (options) { <add> const app = options.app || this.addApplication() <add> delete options.app <add> <add> if (options.pathsToOpen) { <add> options.pathsToOpen = this.convertPaths(options.pathsToOpen) <add> } <add> <add> return app.launch(options) <ide> } <ide> <del> function mockElectronAppQuit () { <del> let didQuit = false <add> open (options) { <add> if (this.applications.size === 0) { <add> return this.launch(options) <add> } <add> <add> let app = options.app <add> if (!app) { <add> const apps = Array.from(this.applications) <add> app = apps[apps.length - 1] <add> } else { <add> delete options.app <add> } <ide> <del> electron.app.quit = function () { <del> this.quit.callCount++ <del> let defaultPrevented = false <del> this.emit('before-quit', { <del> preventDefault () { <del> defaultPrevented = true <add> if (options.pathsToOpen) { <add> options.pathsToOpen = this.convertPaths(options.pathsToOpen) <add> } <add> options.preserveFocus = true <add> <add> return app.openWithOptions(options) <add> } <add> <add> async assert (source) { <add> const windowSpecs = this.parseWindowSpecs(source) <add> let specIndex = 0 <add> <add> const windowPromises = [] <add> for (const window of this.windows) { <add> windowPromises.push((async (theWindow, theSpec) => { <add> const {_rootPaths: rootPaths, _editorPaths: editorPaths} = theWindow <add> <add> const comparison = { <add> ok: true, <add> extraWindow: false, <add> missingWindow: false, <add> extraRoots: [], <add> missingRoots: [], <add> extraEditors: [], <add> missingEditors: [], <add> roots: rootPaths, <add> editors: editorPaths <add> } <add> <add> if (!theSpec) { <add> comparison.ok = false <add> comparison.extraWindow = true <add> comparison.extraRoots = rootPaths <add> comparison.extraEditors = editorPaths <add> } else { <add> const [missingRoots, extraRoots] = this.compareSets(theSpec.roots, rootPaths) <add> const [missingEditors, extraEditors] = this.compareSets(theSpec.editors, editorPaths) <add> <add> comparison.ok = missingRoots.length === 0 && <add> extraRoots.length === 0 && <add> missingEditors.length === 0 && <add> extraEditors.length === 0 <add> comparison.extraRoots = extraRoots <add> comparison.missingRoots = missingRoots <add> comparison.extraEditors = extraEditors <add> comparison.missingEditors = missingEditors <ide> } <add> <add> return comparison <add> })(window, windowSpecs[specIndex++])) <add> } <add> <add> const comparisons = await Promise.all(windowPromises) <add> for (; specIndex < windowSpecs.length; specIndex++) { <add> const spec = windowSpecs[specIndex] <add> comparisons.push({ <add> ok: false, <add> extraWindow: false, <add> missingWindow: true, <add> extraRoots: [], <add> missingRoots: spec.roots, <add> extraEditors: [], <add> missingEditors: spec.editors, <add> roots: null, <add> editors: null <ide> }) <del> if (!defaultPrevented) didQuit = true <ide> } <ide> <del> electron.app.quit.callCount = 0 <add> const shorthandParts = [] <add> const descriptionParts = [] <add> for (const comparison of comparisons) { <add> if (comparison.roots !== null && comparison.editors !== null) { <add> const shortRoots = Array.from(comparison.roots, r => path.basename(r)).join(',') <add> const shortPaths = Array.from(comparison.editors, e => path.basename(e)).join(',') <add> shorthandParts.push(`[${shortRoots} ${shortPaths}]`) <add> } <add> <add> if (comparison.ok) { <add> continue <add> } <add> <add> let parts = [] <add> if (comparison.extraWindow) { <add> parts.push('extra window\n') <add> } else if (comparison.missingWindow) { <add> parts.push('missing window\n') <add> } else { <add> parts.push('incorrect window\n') <add> } <add> <add> const shorten = fullPaths => fullPaths.map(fullPath => path.basename(fullPath)).join(', ') <add> <add> if (comparison.extraRoots.length > 0) { <add> parts.push(`* extra roots ${shorten(comparison.extraRoots)}\n`) <add> } <add> if (comparison.missingRoots.length > 0) { <add> parts.push(`* missing roots ${shorten(comparison.missingRoots)}\n`) <add> } <add> if (comparison.extraEditors.length > 0) { <add> parts.push(`* extra editors ${shorten(comparison.extraEditors)}\n`) <add> } <add> if (comparison.missingEditors.length > 0) { <add> parts.push(`* missing editors ${shorten(comparison.missingEditors)}\n`) <add> } <add> <add> descriptionParts.push(parts.join('')) <add> } <add> <add> if (descriptionParts.length !== 0) { <add> descriptionParts.unshift(shorthandParts.join(' ') + '\n') <add> descriptionParts.unshift('Launched windows did not match spec\n') <add> } <add> <add> assert.isTrue(descriptionParts.length === 0, descriptionParts.join('')) <add> } <add> <add> async destroy () { <add> await Promise.all( <add> Array.from(this.applications, app => app.destroy()) <add> ) <add> <add> if (this.originalAtomHome) { <add> process.env.ATOM_HOME = this.originalAtomHome <add> } <add> } <ide> <del> electron.app.didQuit = () => didQuit <add> addApplication (options = {}) { <add> const app = new AtomApplication({ <add> resourcePath: path.resolve(__dirname, '../..'), <add> atomHomeDirPath: this.atomHome, <add> preserveFocus: true, <add> killProcess: pid => { this.killedPids.push(pid) }, <add> ...options <add> }) <add> this.sinon.stub(app, 'createWindow', loadSettings => { <add> const newWindow = new StubWindow(this.sinon, loadSettings, options) <add> this.windows.add(newWindow) <add> return newWindow <add> }) <add> this.sinon.stub(app.storageFolder, 'load', () => Promise.resolve( <add> (options.applicationJson || []).map(each => ({ <add> initialPaths: this.convertPaths(each.initialPaths) <add> })) <add> )) <add> this.sinon.stub(app.storageFolder, 'store', () => Promise.resolve()) <add> this.applications.add(app) <add> return app <ide> } <ide> <del> function mockElectronShowMessageBox ({ response }) { <del> electron.dialog.showMessageBox = (window, options, callback) => { <del> callback(response) <add> getApplication (index) { <add> const app = Array.from(this.applications)[index] <add> if (!app) { <add> throw new Error(`Application ${index} does not exist`) <ide> } <add> return app <ide> } <ide> <del> function makeTempDir (name) { <del> return fs.realpathSync(temp.mkdirSync(name)) <add> getWindow (index) { <add> const window = Array.from(this.windows)[index] <add> if (!window) { <add> throw new Error(`Window ${index} does not exist`) <add> } <add> return window <ide> } <ide> <del> let channelIdCounter = 0 <del> function evalInWebContents (webContents, source, ...args) { <del> const channelId = 'eval-result-' + channelIdCounter++ <del> return new Promise(resolve => { <del> electron.ipcMain.on(channelId, receiveResult) <add> compareSets (expected, actual) { <add> const expectedItems = new Set(expected) <add> const extra = [] <add> const missing = [] <ide> <del> function receiveResult (event, result) { <del> electron.ipcMain.removeListener('eval-result', receiveResult) <del> resolve(result) <add> for (const actualItem of actual) { <add> if (!expectedItems.delete(actualItem)) { <add> // actualItem was present, but not expected <add> extra.push(actualItem) <ide> } <add> } <add> for (const remainingItem of expectedItems) { <add> // remainingItem was expected, but not present <add> missing.push(remainingItem) <add> } <add> return [missing, extra] <add> } <ide> <del> const js = dedent` <del> function sendBackToMainProcess (result) { <del> require('electron').ipcRenderer.send('${channelId}', result) <del> } <del> (${source})(sendBackToMainProcess, ${args <del> .map(JSON.stringify) <del> .join(', ')}) <del> ` <del> // console.log(`about to execute:\n${js}`) <add> convertRootPath (shortRootPath) { <add> if (shortRootPath.startsWith('atom://') || shortRootPath.startsWith('remote://')) { return shortRootPath } <ide> <del> webContents.executeJavaScript(js) <del> }) <add> const fullRootPath = this.projectRootPool.get(shortRootPath) <add> if (!fullRootPath) { <add> throw new Error(`Unexpected short project root path: ${shortRootPath}`) <add> } <add> return fullRootPath <ide> } <ide> <del> function getTreeViewRootDirectories (atomWindow) { <del> return evalInWebContents( <del> atomWindow.browserWindow.webContents, <del> sendBackToMainProcess => { <del> atom.workspace.getLeftDock().observeActivePaneItem(treeView => { <del> if (treeView) { <del> sendBackToMainProcess( <del> Array.from( <del> treeView.element.querySelectorAll( <del> '.project-root > .header .name' <del> ) <del> ).map(element => element.dataset.path) <del> ) <del> } else { <del> sendBackToMainProcess([]) <del> } <del> }) <del> } <del> ) <add> convertEditorPath (shortEditorPath) { <add> const [truncatedPath, ...suffix] = shortEditorPath.split(/(?=:)/) <add> const fullEditorPath = this.filePathPool.get(truncatedPath) <add> if (!fullEditorPath) { <add> throw new Error(`Unexpected short editor path: ${shortEditorPath}`) <add> } <add> return fullEditorPath + suffix.join('') <ide> } <ide> <del> function clearElectronSession () { <del> return new Promise(resolve => { <del> electron.session.defaultSession.clearStorageData(() => { <del> // Resolve promise on next tick, otherwise the process stalls. This <del> // might be a bug in Electron, but it's probably fixed on the newer <del> // versions. <del> process.nextTick(resolve) <del> }) <add> convertPaths (paths) { <add> return paths.map(shortPath => { <add> if (shortPath.startsWith('atom://') || shortPath.startsWith('remote://')) { return shortPath } <add> <add> const fullRoot = this.projectRootPool.get(shortPath) <add> if (fullRoot) { return fullRoot } <add> <add> const [truncatedPath, ...suffix] = shortPath.split(/(?=:)/) <add> const fullEditor = this.filePathPool.get(truncatedPath) <add> if (fullEditor) { return fullEditor + suffix.join('') } <add> <add> throw new Error(`Unexpected short path: ${shortPath}`) <ide> }) <ide> } <del>}) <add> <add> parseWindowSpecs (source) { <add> const specs = [] <add> <add> const rx = /\s*\[(?:_|(\S+)) (?:_|(\S+))\]/g <add> let match = rx.exec(source) <add> <add> while (match) { <add> const roots = match[1] ? match[1].split(',').map(shortPath => this.convertRootPath(shortPath)) : [] <add> const editors = match[2] ? match[2].split(',').map(shortPath => this.convertEditorPath(shortPath)) : [] <add> specs.push({ roots, editors }) <add> <add> match = rx.exec(source) <add> } <add> <add> return specs <add> } <add>}
2
Text
Text
fix some typos
4d2af4430080e9c7ed5badc465be0e8f04b4b1a4
<ide><path>docs/reference/commandline/ps.md <ide> CONTAINER ID IMAGE COMMAND CREATED <ide> ``` <ide> <ide> The following matches containers based on the layer `d0e008c6cf02` or an image <del>that have this layer in it's layer stack. <add>that have this layer in its layer stack. <ide> <ide> ```bash <ide> $ docker ps --filter ancestor=d0e008c6cf02
1
Java
Java
resolve ${...} placeholders in @propertysource
234bca64624d0fadd0333e1ec3fc2c680308f081
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java <ide> protected void doProcessConfigurationClass(ConfigurationClass configClass, Annot <ide> String[] locations = (String[]) propertySourceAttributes.get("value"); <ide> ClassLoader classLoader = this.resourceLoader.getClassLoader(); <ide> for (String location : locations) { <add> location = this.environment.resolveRequiredPlaceholders(location); <ide> ResourcePropertySource ps = StringUtils.hasText(name) ? <ide> new ResourcePropertySource(name, location, classLoader) : <ide> new ResourcePropertySource(location, classLoader); <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/PropertySource.java <ide> * configuration class and then used when populating the {@code TestBean} object. Given <ide> * the configuration above, a call to {@code testBean.getName()} will return "myTestBean". <ide> * <add> * <h3>Resolving placeholders within @PropertySource resource locations</h3> <add> * Any ${...} placeholders present in a {@code @PropertySource} {@linkplain #value() <add> * resource location} will be resolved against the set of property sources already <add> * registered against the environment. For example: <add> * <pre class="code"> <add> * &#064;Configuration <add> * &#064;PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties") <add> * public class AppConfig { <add> * &#064;Autowired <add> * Environment env; <add> * <add> * &#064;Bean <add> * public TestBean testBean() { <add> * TestBean testBean = new TestBean(); <add> * testBean.setName(env.getProperty("testbean.name")); <add> * return testBean; <add> * } <add> * }</pre> <add> * <add> * Assuming that "my.placeholder" is present in one of the property sources already <add> * registered, e.g. system properties or environment variables, the placeholder will <add> * be resolved to the corresponding value. If not, then "default/path" will be used as a <add> * default. Expressing a default value (delimited by colon ":") is optional. If no <add> * default is specified and a property cannot be resolved, an {@code <add> * IllegalArgumentException} will be thrown. <add> * <ide> * <h3>A note on property overriding with @PropertySource</h3> <ide> * In cases where a given property key exists in more than one {@code .properties} <ide> * file, the last {@code @PropertySource} annotation processed will 'win' and override. <ide> /** <ide> * Indicate the resource location(s) of the properties file to be loaded. <ide> * For example, {@code "classpath:/com/myco/app.properties"} or <del> * {@code "file:/path/to/file"}. Note that resource location wildcards <del> * are not permitted, and that each location must evaluate to exactly one <del> * {@code .properties} resource. Each location will be added to the <del> * enclosing {@code Environment} as its own property source, and in the order <del> * declared. <add> * {@code "file:/path/to/file"}. <add> * <p>Resource location wildcards (e.g. *&#42;/*.properties) are not permitted; each <add> * location must evaluate to exactly one {@code .properties} resource. <add> * <p>${...} placeholders will be resolved against any/all property sources already <add> * registered with the {@code Environment}. See {@linkplain PropertySource above} for <add> * examples. <add> * <p>Each location will be added to the enclosing {@code Environment} as its own <add> * property source, and in the order declared. <ide> */ <ide> String[] value(); <ide> <ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java <ide> public void orderingIsLifo() { <ide> } <ide> } <ide> <add> @Test(expected=IllegalArgumentException.class) <add> public void withUnresolvablePlaceholder() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <add> ctx.register(ConfigWithUnresolvablePlaceholder.class); <add> ctx.refresh(); <add> } <add> <add> @Test <add> public void withUnresolvablePlaceholderAndDefault() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <add> ctx.register(ConfigWithUnresolvablePlaceholderAndDefault.class); <add> ctx.refresh(); <add> assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); <add> } <add> <add> @Test <add> public void withResolvablePlaceholder() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <add> ctx.register(ConfigWithResolvablePlaceholder.class); <add> System.setProperty("path.to.properties", "org/springframework/context/annotation"); <add> ctx.refresh(); <add> assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); <add> System.clearProperty("path.to.properties"); <add> } <add> <add> <add> @Configuration <add> @PropertySource(value="classpath:${unresolvable}/p1.properties") <add> static class ConfigWithUnresolvablePlaceholder { <add> } <add> <add> <add> @Configuration <add> @PropertySource(value="classpath:${unresolvable:org/springframework/context/annotation}/p1.properties") <add> static class ConfigWithUnresolvablePlaceholderAndDefault { <add> @Inject Environment env; <add> <add> @Bean <add> public TestBean testBean() { <add> return new TestBean(env.getProperty("testbean.name")); <add> } <add> } <add> <add> <add> @Configuration <add> @PropertySource(value="classpath:${path.to.properties}/p1.properties") <add> static class ConfigWithResolvablePlaceholder { <add> @Inject Environment env; <add> <add> @Bean <add> public TestBean testBean() { <add> return new TestBean(env.getProperty("testbean.name")); <add> } <add> } <add> <add> <ide> <ide> @Configuration <ide> @PropertySource(name="p1", value="classpath:org/springframework/context/annotation/p1.properties")
3
PHP
PHP
remove unneeded parent boot calls
d53c56e4e0bdc2b9a3c14511bdcbe48c4914f084
<ide><path>app/Providers/EventServiceProvider.php <ide> class EventServiceProvider extends ServiceProvider <ide> */ <ide> public function boot() <ide> { <del> parent::boot(); <del> <ide> // <ide> } <ide> } <ide><path>app/Providers/RouteServiceProvider.php <ide> class RouteServiceProvider extends ServiceProvider <ide> public function boot() <ide> { <ide> // <del> <del> parent::boot(); <ide> } <ide> <ide> /**
2
Javascript
Javascript
fix layout service
0c534e1eb8140e09f8d55bba7431fd4116dc9dd6
<ide><path>src/core/core.layoutService.js <ide> bottom: 0, <ide> }; <ide> <del> box.update(box.options.fullWidth ? chartWidth : maxChartAreaWidth, minBoxSize.minSize.height, scaleMargin); <add> // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends <add> // on the margin. Sometimes they need to increase in size slightly <add> box.update(box.options.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin); <ide> } else { <ide> box.update(minBoxSize.minSize.width, maxChartAreaHeight); <ide> }
1
Javascript
Javascript
remove unnecessary else branch
b98027ee5f4e906c84e8d92e8d76baeefa60b8cf
<ide><path>lib/zlib.js <ide> function zlibBufferSync(engine, buffer) { <ide> buffer = processChunkSync(engine, buffer, engine._finishFlushFlag); <ide> if (engine._info) <ide> return { buffer, engine }; <del> else <del> return buffer; <add> return buffer; <ide> } <ide> <ide> function zlibOnError(message, errno) {
1
Javascript
Javascript
fix typo in spy name
f69ee170ed1eb2ba3fdde5d91760d2b139b41a4c
<ide><path>test/ng/httpBackendSpec.js <ide> describe('$httpBackend', function() { <ide> return {}; <ide> }), <ide> body: { <del> appendChild: jasmine.createSpy('body.appendChid').andCallFake(function(script) { <add> appendChild: jasmine.createSpy('body.appendChild').andCallFake(function(script) { <ide> fakeDocument.$$scripts.push(script); <ide> }), <ide> removeChild: jasmine.createSpy('body.removeChild').andCallFake(function(script) {
1
Text
Text
improve matcher example (resolves )
38e4422c0db522e23c86728824ae09966d4ad14c
<ide><path>website/docs/usage/rule-based-matching.md <ide> match on the uppercase versions, in case someone has written it as "Google i/o". <ide> ### {executable="true"} <ide> import spacy <ide> from spacy.matcher import Matcher <add>from spacy.tokens import Span <ide> <ide> nlp = spacy.load("en_core_web_sm") <ide> matcher = Matcher(nlp.vocab) <ide> <del># Get the ID of the 'EVENT' entity type. This is required to set an entity. <del>EVENT = nlp.vocab.strings["EVENT"] <del> <ide> def add_event_ent(matcher, doc, i, matches): <ide> # Get the current match and create tuple of entity label, start and end. <ide> # Append entity to the doc's entity. (Don't overwrite doc.ents!) <ide> match_id, start, end = matches[i] <del> entity = (EVENT, start, end) <add> entity = Span(doc, start, end, label="EVENT") <ide> doc.ents += (entity,) <del> print(doc[start:end].text, entity) <add> print(entity.text) <ide> <del>matcher.add("GoogleIO", add_event_ent, <del> [{"ORTH": "Google"}, {"ORTH": "I"}, {"ORTH": "/"}, {"ORTH": "O"}], <del> [{"ORTH": "Google"}, {"ORTH": "I"}, {"ORTH": "/"}, {"ORTH": "O"}, {"IS_DIGIT": True}],) <del>doc = nlp(u"This is a text about Google I/O 2015.") <add>pattern = [{"ORTH": "Google"}, {"ORTH": "I"}, {"ORTH": "/"}, {"ORTH": "O"}] <add>matcher.add("GoogleIO", add_event_ent, pattern) <add>doc = nlp(u"This is a text about Google I/O.") <ide> matches = matcher(doc) <ide> ``` <ide> <add>A very similar logic has been implemented in the built-in <add>[`EntityRuler`](/api/entityruler) by the way. It also takes care of handling <add>overlapping matches, which you would otherwise have to take care of yourself. <add> <ide> > #### Tip: Visualizing matches <ide> > <ide> > When working with entities, you can use [displaCy](/api/top-level#displacy) to
1
Go
Go
extract volume interaction to a volumes service
e4b6adc88e967971de634596654d9bc33e7bd7e0
<ide><path>api/server/router/volume/backend.go <ide> package volume // import "github.com/docker/docker/api/server/router/volume" <ide> import ( <ide> "context" <ide> <add> "github.com/docker/docker/volume/service/opts" <ide> // TODO return types need to be refactored into pkg <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> import ( <ide> // Backend is the methods that need to be implemented to provide <ide> // volume specific functionality <ide> type Backend interface { <del> Volumes(filter string) ([]*types.Volume, []string, error) <del> VolumeInspect(name string) (*types.Volume, error) <del> VolumeCreate(name, driverName string, opts, labels map[string]string) (*types.Volume, error) <del> VolumeRm(name string, force bool) error <del> VolumesPrune(ctx context.Context, pruneFilters filters.Args) (*types.VolumesPruneReport, error) <add> List(ctx context.Context, filter filters.Args) ([]*types.Volume, []string, error) <add> Get(ctx context.Context, name string, opts ...opts.GetOption) (*types.Volume, error) <add> Create(ctx context.Context, name, driverName string, opts ...opts.CreateOption) (*types.Volume, error) <add> Remove(ctx context.Context, name string, opts ...opts.RemoveOption) error <add> Prune(ctx context.Context, pruneFilters filters.Args) (*types.VolumesPruneReport, error) <ide> } <ide><path>api/server/router/volume/volume_routes.go <ide> package volume // import "github.com/docker/docker/api/server/router/volume" <ide> import ( <ide> "context" <ide> "encoding/json" <del> "errors" <ide> "io" <ide> "net/http" <ide> <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/types/filters" <ide> volumetypes "github.com/docker/docker/api/types/volume" <ide> "github.com/docker/docker/errdefs" <add> "github.com/docker/docker/volume/service/opts" <add> "github.com/pkg/errors" <ide> ) <ide> <ide> func (v *volumeRouter) getVolumesList(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> <del> volumes, warnings, err := v.backend.Volumes(r.Form.Get("filters")) <add> filters, err := filters.FromJSON(r.Form.Get("filters")) <add> if err != nil { <add> return errdefs.InvalidParameter(errors.Wrap(err, "error reading volume filters")) <add> } <add> volumes, warnings, err := v.backend.List(ctx, filters) <ide> if err != nil { <ide> return err <ide> } <ide> func (v *volumeRouter) getVolumeByName(ctx context.Context, w http.ResponseWrite <ide> return err <ide> } <ide> <del> volume, err := v.backend.VolumeInspect(vars["name"]) <add> volume, err := v.backend.Get(ctx, vars["name"], opts.WithGetResolveStatus) <ide> if err != nil { <ide> return err <ide> } <ide> func (v *volumeRouter) postVolumesCreate(ctx context.Context, w http.ResponseWri <ide> return err <ide> } <ide> <del> volume, err := v.backend.VolumeCreate(req.Name, req.Driver, req.DriverOpts, req.Labels) <add> volume, err := v.backend.Create(ctx, req.Name, req.Driver, opts.WithCreateOptions(req.DriverOpts), opts.WithCreateLabels(req.Labels)) <ide> if err != nil { <ide> return err <ide> } <ide> func (v *volumeRouter) deleteVolumes(ctx context.Context, w http.ResponseWriter, <ide> return err <ide> } <ide> force := httputils.BoolValue(r, "force") <del> if err := v.backend.VolumeRm(vars["name"], force); err != nil { <add> if err := v.backend.Remove(ctx, vars["name"], opts.WithPurgeOnError(force)); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusNoContent) <ide> func (v *volumeRouter) postVolumesPrune(ctx context.Context, w http.ResponseWrit <ide> return err <ide> } <ide> <del> pruneReport, err := v.backend.VolumesPrune(ctx, pruneFilters) <add> pruneReport, err := v.backend.Prune(ctx, pruneFilters) <ide> if err != nil { <ide> return err <ide> } <ide><path>cmd/dockerd/daemon.go <ide> func initRouter(opts routerOptions) { <ide> container.NewRouter(opts.daemon, decoder), <ide> image.NewRouter(opts.daemon.ImageService()), <ide> systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildCache), <del> volume.NewRouter(opts.daemon), <add> volume.NewRouter(opts.daemon.VolumesService()), <ide> build.NewRouter(opts.buildBackend, opts.daemon), <ide> sessionrouter.NewRouter(opts.sessionManager), <ide> swarmrouter.NewRouter(opts.cluster), <ide> func createAndStartCluster(cli *DaemonCli, d *daemon.Daemon) (*cluster.Cluster, <ide> Root: cli.Config.Root, <ide> Name: name, <ide> Backend: d, <add> VolumeBackend: d.VolumesService(), <ide> ImageBackend: d.ImageService(), <ide> PluginBackend: d.PluginManager(), <ide> NetworkSubnetsProvider: d, <ide><path>container/container_unix.go <ide> func (container *Container) CopyImagePathContent(v volume.Volume, destination st <ide> return err <ide> } <ide> <del> if _, err = ioutil.ReadDir(rootfs); err != nil { <add> if _, err := os.Stat(rootfs); err != nil { <ide> if os.IsNotExist(err) { <ide> return nil <ide> } <ide><path>daemon/cluster/cluster.go <ide> type Config struct { <ide> Backend executorpkg.Backend <ide> ImageBackend executorpkg.ImageBackend <ide> PluginBackend plugin.Backend <add> VolumeBackend executorpkg.VolumeBackend <ide> NetworkSubnetsProvider NetworkSubnetsProvider <ide> <ide> // DefaultAdvertiseAddr is the default host/IP or network interface to use <ide><path>daemon/cluster/executor/backend.go <ide> import ( <ide> clustertypes "github.com/docker/docker/daemon/cluster/provider" <ide> networkSettings "github.com/docker/docker/daemon/network" <ide> "github.com/docker/docker/plugin" <add> volumeopts "github.com/docker/docker/volume/service/opts" <ide> "github.com/docker/libnetwork" <ide> "github.com/docker/libnetwork/cluster" <ide> networktypes "github.com/docker/libnetwork/types" <ide> type Backend interface { <ide> SetContainerSecretReferences(name string, refs []*swarmtypes.SecretReference) error <ide> SetContainerConfigReferences(name string, refs []*swarmtypes.ConfigReference) error <ide> SystemInfo() (*types.Info, error) <del> VolumeCreate(name, driverName string, opts, labels map[string]string) (*types.Volume, error) <ide> Containers(config *types.ContainerListOptions) ([]*types.Container, error) <ide> SetNetworkBootstrapKeys([]*networktypes.EncryptionKey) error <ide> DaemonJoinsCluster(provider cluster.Provider) <ide> type Backend interface { <ide> GetAttachmentStore() *networkSettings.AttachmentStore <ide> } <ide> <add>// VolumeBackend is used by an executor to perform volume operations <add>type VolumeBackend interface { <add> Create(ctx context.Context, name, driverName string, opts ...volumeopts.CreateOption) (*types.Volume, error) <add>} <add> <ide> // ImageBackend is used by an executor to perform image operations <ide> type ImageBackend interface { <ide> PullImage(ctx context.Context, image, tag, platform string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error <ide><path>daemon/cluster/executor/container/adapter.go <ide> import ( <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/daemon/cluster/convert" <ide> executorpkg "github.com/docker/docker/daemon/cluster/executor" <add> volumeopts "github.com/docker/docker/volume/service/opts" <ide> "github.com/docker/libnetwork" <ide> "github.com/docker/swarmkit/agent/exec" <ide> "github.com/docker/swarmkit/api" <ide> import ( <ide> // are mostly naked calls to the client API, seeded with information from <ide> // containerConfig. <ide> type containerAdapter struct { <del> backend executorpkg.Backend <del> imageBackend executorpkg.ImageBackend <del> container *containerConfig <del> dependencies exec.DependencyGetter <add> backend executorpkg.Backend <add> imageBackend executorpkg.ImageBackend <add> volumeBackend executorpkg.VolumeBackend <add> container *containerConfig <add> dependencies exec.DependencyGetter <ide> } <ide> <del>func newContainerAdapter(b executorpkg.Backend, i executorpkg.ImageBackend, task *api.Task, node *api.NodeDescription, dependencies exec.DependencyGetter) (*containerAdapter, error) { <add>func newContainerAdapter(b executorpkg.Backend, i executorpkg.ImageBackend, v executorpkg.VolumeBackend, task *api.Task, node *api.NodeDescription, dependencies exec.DependencyGetter) (*containerAdapter, error) { <ide> ctnr, err := newContainerConfig(task, node) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> return &containerAdapter{ <del> container: ctnr, <del> backend: b, <del> imageBackend: i, <del> dependencies: dependencies, <add> container: ctnr, <add> backend: b, <add> imageBackend: i, <add> volumeBackend: v, <add> dependencies: dependencies, <ide> }, nil <ide> } <ide> <ide> func (c *containerAdapter) createVolumes(ctx context.Context) error { <ide> req := c.container.volumeCreateRequest(&mount) <ide> <ide> // Check if this volume exists on the engine <del> if _, err := c.backend.VolumeCreate(req.Name, req.Driver, req.DriverOpts, req.Labels); err != nil { <add> if _, err := c.volumeBackend.Create(ctx, req.Name, req.Driver, <add> volumeopts.WithCreateOptions(req.DriverOpts), <add> volumeopts.WithCreateLabels(req.Labels), <add> ); err != nil { <ide> // TODO(amitshukla): Today, volume create through the engine api does not return an error <ide> // when the named volume with the same parameters already exists. <ide> // It returns an error if the driver name is different - that is a valid error <ide><path>daemon/cluster/executor/container/attachment.go <ide> type networkAttacherController struct { <ide> closed chan struct{} <ide> } <ide> <del>func newNetworkAttacherController(b executorpkg.Backend, i executorpkg.ImageBackend, task *api.Task, node *api.NodeDescription, dependencies exec.DependencyGetter) (*networkAttacherController, error) { <del> adapter, err := newContainerAdapter(b, i, task, node, dependencies) <add>func newNetworkAttacherController(b executorpkg.Backend, i executorpkg.ImageBackend, v executorpkg.VolumeBackend, task *api.Task, node *api.NodeDescription, dependencies exec.DependencyGetter) (*networkAttacherController, error) { <add> adapter, err := newContainerAdapter(b, i, v, task, node, dependencies) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/cluster/executor/container/controller.go <ide> type controller struct { <ide> var _ exec.Controller = &controller{} <ide> <ide> // NewController returns a docker exec runner for the provided task. <del>func newController(b executorpkg.Backend, i executorpkg.ImageBackend, task *api.Task, node *api.NodeDescription, dependencies exec.DependencyGetter) (*controller, error) { <del> adapter, err := newContainerAdapter(b, i, task, node, dependencies) <add>func newController(b executorpkg.Backend, i executorpkg.ImageBackend, v executorpkg.VolumeBackend, task *api.Task, node *api.NodeDescription, dependencies exec.DependencyGetter) (*controller, error) { <add> adapter, err := newContainerAdapter(b, i, v, task, node, dependencies) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/cluster/executor/container/executor.go <ide> type executor struct { <ide> backend executorpkg.Backend <ide> imageBackend executorpkg.ImageBackend <ide> pluginBackend plugin.Backend <add> volumeBackend executorpkg.VolumeBackend <ide> dependencies exec.DependencyManager <ide> mutex sync.Mutex // This mutex protects the following node field <ide> node *api.NodeDescription <ide> } <ide> <ide> // NewExecutor returns an executor from the docker client. <del>func NewExecutor(b executorpkg.Backend, p plugin.Backend, i executorpkg.ImageBackend) exec.Executor { <add>func NewExecutor(b executorpkg.Backend, p plugin.Backend, i executorpkg.ImageBackend, v executorpkg.VolumeBackend) exec.Executor { <ide> return &executor{ <ide> backend: b, <ide> pluginBackend: p, <ide> imageBackend: i, <add> volumeBackend: v, <ide> dependencies: agent.NewDependencyManager(), <ide> } <ide> } <ide> func (e *executor) Controller(t *api.Task) (exec.Controller, error) { <ide> e.mutex.Unlock() <ide> <ide> if t.Spec.GetAttachment() != nil { <del> return newNetworkAttacherController(e.backend, e.imageBackend, t, nodeDescription, dependencyGetter) <add> return newNetworkAttacherController(e.backend, e.imageBackend, e.volumeBackend, t, nodeDescription, dependencyGetter) <ide> } <ide> <ide> var ctlr exec.Controller <ide> func (e *executor) Controller(t *api.Task) (exec.Controller, error) { <ide> return ctlr, fmt.Errorf("unsupported runtime type: %q", runtimeKind) <ide> } <ide> case *api.TaskSpec_Container: <del> c, err := newController(e.backend, e.imageBackend, t, nodeDescription, dependencyGetter) <add> c, err := newController(e.backend, e.imageBackend, e.volumeBackend, t, nodeDescription, dependencyGetter) <ide> if err != nil { <ide> return ctlr, err <ide> } <ide><path>daemon/cluster/executor/container/health_test.go <ide> func TestHealthStates(t *testing.T) { <ide> EventsService: e, <ide> } <ide> <del> controller, err := newController(daemon, nil, task, nil, nil) <add> controller, err := newController(daemon, nil, nil, task, nil, nil) <ide> if err != nil { <ide> t.Fatalf("create controller fail %v", err) <ide> } <ide><path>daemon/cluster/executor/container/validate_test.go <ide> import ( <ide> ) <ide> <ide> func newTestControllerWithMount(m api.Mount) (*controller, error) { <del> return newController(&daemon.Daemon{}, nil, &api.Task{ <add> return newController(&daemon.Daemon{}, nil, nil, &api.Task{ <ide> ID: stringid.GenerateRandomID(), <ide> ServiceID: stringid.GenerateRandomID(), <ide> Spec: api.TaskSpec{ <ide><path>daemon/cluster/noderunner.go <ide> func (n *nodeRunner) start(conf nodeStartConfig) error { <ide> Executor: container.NewExecutor( <ide> n.cluster.config.Backend, <ide> n.cluster.config.PluginBackend, <del> n.cluster.config.ImageBackend), <add> n.cluster.config.ImageBackend, <add> n.cluster.config.VolumeBackend, <add> ), <ide> HeartbeatTick: n.cluster.config.RaftHeartbeatTick, <ide> // Recommended value in etcd/raft is 10 x (HeartbeatTick). <ide> // Lower values were seen to have caused instability because of <ide><path>daemon/create.go <ide> import ( <ide> "strings" <ide> "time" <ide> <del> "github.com/pkg/errors" <del> <ide> "github.com/docker/docker/api/types" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> networktypes "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/idtools" <del> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/runconfig" <ide> "github.com/opencontainers/selinux/go-selinux/label" <add> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> func (daemon *Daemon) generateSecurityOpt(hostConfig *containertypes.HostConfig) <ide> return nil, nil <ide> } <ide> <del>// VolumeCreate creates a volume with the specified name, driver, and opts <del>// This is called directly from the Engine API <del>func (daemon *Daemon) VolumeCreate(name, driverName string, opts, labels map[string]string) (*types.Volume, error) { <del> if name == "" { <del> name = stringid.GenerateNonCryptoID() <del> } <del> <del> v, err := daemon.volumes.Create(name, driverName, opts, labels) <del> if err != nil { <del> return nil, err <del> } <del> <del> daemon.LogVolumeEvent(v.Name(), "create", map[string]string{"driver": v.DriverName()}) <del> apiV := volumeToAPIType(v) <del> apiV.Mountpoint = v.Path() <del> return apiV, nil <del>} <del> <ide> func (daemon *Daemon) mergeAndVerifyConfig(config *containertypes.Config, img *image.Image) error { <ide> if img != nil && img.Config != nil { <ide> if err := merge(config, img.Config); err != nil { <ide><path>daemon/create_unix.go <ide> package daemon // import "github.com/docker/docker/daemon" <ide> <ide> import ( <add> "context" <ide> "fmt" <ide> "os" <ide> "path/filepath" <ide> import ( <ide> mounttypes "github.com/docker/docker/api/types/mount" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/pkg/stringid" <add> volumeopts "github.com/docker/docker/volume/service/opts" <ide> "github.com/opencontainers/selinux/go-selinux/label" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (daemon *Daemon) createContainerOSSpecificSettings(container *container.Con <ide> return fmt.Errorf("cannot mount volume over existing file, file exists %s", path) <ide> } <ide> <del> v, err := daemon.volumes.CreateWithRef(name, hostConfig.VolumeDriver, container.ID, nil, nil) <add> v, err := daemon.volumes.Create(context.TODO(), name, hostConfig.VolumeDriver, volumeopts.WithCreateReference(container.ID)) <ide> if err != nil { <ide> return err <ide> } <ide> <del> if err := label.Relabel(v.Path(), container.MountLabel, true); err != nil { <add> if err := label.Relabel(v.Mountpoint, container.MountLabel, true); err != nil { <ide> return err <ide> } <ide> <del> container.AddMountPointWithVolume(destination, v, true) <add> container.AddMountPointWithVolume(destination, &volumeWrapper{v: v, s: daemon.volumes}, true) <ide> } <ide> return daemon.populateVolumes(container) <ide> } <ide><path>daemon/create_windows.go <ide> package daemon // import "github.com/docker/docker/daemon" <ide> <ide> import ( <add> "context" <ide> "fmt" <ide> "runtime" <ide> <ide> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/pkg/stringid" <ide> volumemounts "github.com/docker/docker/volume/mounts" <add> volumeopts "github.com/docker/docker/volume/service/opts" <ide> ) <ide> <ide> // createContainerOSSpecificSettings performs host-OS specific container create functionality <ide> func (daemon *Daemon) createContainerOSSpecificSettings(container *container.Con <ide> <ide> // Create the volume in the volume driver. If it doesn't exist, <ide> // a new one will be created. <del> v, err := daemon.volumes.CreateWithRef(mp.Name, volumeDriver, container.ID, nil, nil) <add> v, err := daemon.volumes.Create(context.TODO(), mp.Name, volumeDriver, volumeopts.WithCreateReference(container.ID)) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) createContainerOSSpecificSettings(container *container.Con <ide> // } <ide> <ide> // Add it to container.MountPoints <del> container.AddMountPointWithVolume(mp.Destination, v, mp.RW) <add> container.AddMountPointWithVolume(mp.Destination, &volumeWrapper{v: v, s: daemon.volumes}, mp.RW) <ide> } <ide> return nil <ide> } <ide><path>daemon/daemon.go <ide> import ( <ide> refstore "github.com/docker/docker/reference" <ide> "github.com/docker/docker/registry" <ide> "github.com/docker/docker/runconfig" <del> volumedrivers "github.com/docker/docker/volume/drivers" <del> "github.com/docker/docker/volume/local" <del> "github.com/docker/docker/volume/store" <add> volumesservice "github.com/docker/docker/volume/service" <ide> "github.com/docker/libnetwork" <ide> "github.com/docker/libnetwork/cluster" <ide> nwconfig "github.com/docker/libnetwork/config" <ide> type Daemon struct { <ide> RegistryService registry.Service <ide> EventsService *events.Events <ide> netController libnetwork.NetworkController <del> volumes *store.VolumeStore <add> volumes *volumesservice.VolumesService <ide> discoveryWatcher discovery.Reloader <ide> root string <ide> seccompEnabled bool <ide> func NewDaemon(config *config.Config, registryService registry.Service, containe <ide> return nil, err <ide> } <ide> <del> // Configure the volumes driver <del> volStore, err := d.configureVolumes(rootIDs) <add> d.volumes, err = volumesservice.NewVolumeService(config.Root, d.PluginStore, rootIDs, d) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func NewDaemon(config *config.Config, registryService registry.Service, containe <ide> d.statsCollector = d.newStatsCollector(1 * time.Second) <ide> <ide> d.EventsService = events.New() <del> d.volumes = volStore <ide> d.root = config.Root <ide> d.idMappings = idMappings <ide> d.seccompEnabled = sysInfo.Seccomp <ide> func setDefaultMtu(conf *config.Config) { <ide> conf.Mtu = config.DefaultNetworkMtu <ide> } <ide> <del>func (daemon *Daemon) configureVolumes(rootIDs idtools.IDPair) (*store.VolumeStore, error) { <del> volumeDriver, err := local.New(daemon.configStore.Root, rootIDs) <del> if err != nil { <del> return nil, err <del> } <del> drivers := volumedrivers.NewStore(daemon.PluginStore) <del> if !drivers.Register(volumeDriver, volumeDriver.Name()) { <del> return nil, errors.New("local volume driver could not be registered") <del> } <del> return store.New(daemon.configStore.Root, drivers) <del>} <del> <ide> // IsShuttingDown tells whether the daemon is shutting down or not <ide> func (daemon *Daemon) IsShuttingDown() bool { <ide> return daemon.shutdown <ide><path>daemon/daemon_test.go <ide> import ( <ide> _ "github.com/docker/docker/pkg/discovery/memory" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/truncindex" <del> volumedrivers "github.com/docker/docker/volume/drivers" <del> "github.com/docker/docker/volume/local" <del> "github.com/docker/docker/volume/store" <add> volumesservice "github.com/docker/docker/volume/service" <ide> "github.com/docker/go-connections/nat" <ide> "github.com/docker/libnetwork" <ide> "github.com/gotestyourself/gotestyourself/assert" <ide> func initDaemonWithVolumeStore(tmp string) (*Daemon, error) { <ide> repository: tmp, <ide> root: tmp, <ide> } <del> drivers := volumedrivers.NewStore(nil) <del> daemon.volumes, err = store.New(tmp, drivers) <add> daemon.volumes, err = volumesservice.NewVolumeService(tmp, nil, idtools.IDPair{UID: 0, GID: 0}, daemon) <ide> if err != nil { <ide> return nil, err <ide> } <del> <del> volumesDriver, err := local.New(tmp, idtools.IDPair{UID: 0, GID: 0}) <del> if err != nil { <del> return nil, err <del> } <del> drivers.Register(volumesDriver, volumesDriver.Name()) <del> <ide> return daemon, nil <ide> } <ide> <ide><path>daemon/delete.go <ide> import ( <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/pkg/system" <del> "github.com/docker/docker/volume" <del> volumestore "github.com/docker/docker/volume/store" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo <ide> daemon.LogContainerEvent(container, "destroy") <ide> return nil <ide> } <del> <del>// VolumeRm removes the volume with the given name. <del>// If the volume is referenced by a container it is not removed <del>// This is called directly from the Engine API <del>func (daemon *Daemon) VolumeRm(name string, force bool) error { <del> v, err := daemon.volumes.Get(name) <del> if err != nil { <del> if force && volumestore.IsNotExist(err) { <del> return nil <del> } <del> return err <del> } <del> <del> err = daemon.volumeRm(v) <del> if err != nil && volumestore.IsInUse(err) { <del> return errdefs.Conflict(err) <del> } <del> <del> if err == nil || force { <del> daemon.volumes.Purge(name) <del> return nil <del> } <del> return err <del>} <del> <del>func (daemon *Daemon) volumeRm(v volume.Volume) error { <del> if err := daemon.volumes.Remove(v); err != nil { <del> return errors.Wrap(err, "unable to remove volume") <del> } <del> daemon.LogVolumeEvent(v.Name(), "destroy", map[string]string{"driver": v.DriverName()}) <del> return nil <del>} <ide><path>daemon/disk_usage.go <ide> import ( <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <del> "github.com/docker/docker/pkg/directory" <del> "github.com/docker/docker/volume" <del> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> // SystemDiskUsage returns information about the daemon data disk usage <ide> func (daemon *Daemon) SystemDiskUsage(ctx context.Context) (*types.DiskUsage, er <ide> return nil, fmt.Errorf("failed to retrieve image list: %v", err) <ide> } <ide> <del> volumes, err := daemon.volumes.FilterByDriver(volume.DefaultDriverName) <add> localVolumes, err := daemon.volumes.LocalVolumesSize(ctx) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <del> var allVolumes []*types.Volume <del> for _, v := range volumes { <del> select { <del> case <-ctx.Done(): <del> return nil, ctx.Err() <del> default: <del> } <del> if d, ok := v.(volume.DetailedVolume); ok { <del> if len(d.Options()) > 0 { <del> // skip local volumes with mount options since these could have external <del> // mounted filesystems that will be slow to enumerate. <del> continue <del> } <del> } <del> <del> name := v.Name() <del> refs := daemon.volumes.Refs(v) <del> <del> tv := volumeToAPIType(v) <del> sz, err := directory.Size(ctx, v.Path()) <del> if err != nil { <del> logrus.Warnf("failed to determine size of volume %v", name) <del> sz = -1 <del> } <del> tv.UsageData = &types.VolumeUsageData{Size: sz, RefCount: int64(len(refs))} <del> allVolumes = append(allVolumes, tv) <del> } <del> <ide> allLayersSize, err := daemon.imageService.LayerDiskUsage(ctx) <ide> if err != nil { <ide> return nil, err <ide> func (daemon *Daemon) SystemDiskUsage(ctx context.Context) (*types.DiskUsage, er <ide> return &types.DiskUsage{ <ide> LayersSize: allLayersSize, <ide> Containers: allContainers, <del> Volumes: allVolumes, <add> Volumes: localVolumes, <ide> Images: allImages, <ide> }, nil <ide> } <ide><path>daemon/errors.go <ide> func containerNotFound(id string) error { <ide> return objNotFoundError{"container", id} <ide> } <ide> <del>func volumeNotFound(id string) error { <del> return objNotFoundError{"volume", id} <del>} <del> <ide> type objNotFoundError struct { <ide> object string <ide> id string <ide><path>daemon/images/image_prune.go <ide> import ( <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <ide> "github.com/opencontainers/go-digest" <add> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> var imagesAcceptedFilters = map[string]bool{ <ide> <ide> // errPruneRunning is returned when a prune request is received while <ide> // one is in progress <del>var errPruneRunning = fmt.Errorf("a prune operation is already running") <add>var errPruneRunning = errdefs.Conflict(errors.New("a prune operation is already running")) <ide> <ide> // ImagesPrune removes unused images <ide> func (i *ImageService) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (*types.ImagesPruneReport, error) { <ide><path>daemon/inspect.go <ide> import ( <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/daemon/network" <ide> "github.com/docker/docker/errdefs" <del> volumestore "github.com/docker/docker/volume/store" <ide> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> func (daemon *Daemon) ContainerExecInspect(id string) (*backend.ExecInspect, err <ide> }, nil <ide> } <ide> <del>// VolumeInspect looks up a volume by name. An error is returned if <del>// the volume cannot be found. <del>func (daemon *Daemon) VolumeInspect(name string) (*types.Volume, error) { <del> v, err := daemon.volumes.Get(name) <del> if err != nil { <del> if volumestore.IsNotExist(err) { <del> return nil, volumeNotFound(name) <del> } <del> return nil, errdefs.System(err) <del> } <del> apiV := volumeToAPIType(v) <del> apiV.Mountpoint = v.Path() <del> apiV.Status = v.Status() <del> return apiV, nil <del>} <del> <ide> func (daemon *Daemon) getBackwardsCompatibleNetworkSettings(settings *network.Settings) *v1p20.NetworkSettings { <ide> result := &v1p20.NetworkSettings{ <ide> NetworkSettingsBase: types.NetworkSettingsBase{ <ide><path>daemon/list.go <ide> import ( <ide> "github.com/docker/docker/daemon/images" <ide> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/image" <del> "github.com/docker/docker/volume" <ide> "github.com/docker/go-connections/nat" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <del>var acceptedVolumeFilterTags = map[string]bool{ <del> "dangling": true, <del> "name": true, <del> "driver": true, <del> "label": true, <del>} <del> <ide> var acceptedPsFilterTags = map[string]bool{ <ide> "ancestor": true, <ide> "before": true, <ide> func (daemon *Daemon) refreshImage(s *container.Snapshot, ctx *listContext) (*ty <ide> return &c, nil <ide> } <ide> <del>// Volumes lists known volumes, using the filter to restrict the range <del>// of volumes returned. <del>func (daemon *Daemon) Volumes(filter string) ([]*types.Volume, []string, error) { <del> var ( <del> volumesOut []*types.Volume <del> ) <del> volFilters, err := filters.FromJSON(filter) <del> if err != nil { <del> return nil, nil, err <del> } <del> <del> if err := volFilters.Validate(acceptedVolumeFilterTags); err != nil { <del> return nil, nil, err <del> } <del> <del> volumes, warnings, err := daemon.volumes.List() <del> if err != nil { <del> return nil, nil, err <del> } <del> <del> filterVolumes, err := daemon.filterVolumes(volumes, volFilters) <del> if err != nil { <del> return nil, nil, err <del> } <del> for _, v := range filterVolumes { <del> apiV := volumeToAPIType(v) <del> if vv, ok := v.(interface { <del> CachedPath() string <del> }); ok { <del> apiV.Mountpoint = vv.CachedPath() <del> } else { <del> apiV.Mountpoint = v.Path() <del> } <del> volumesOut = append(volumesOut, apiV) <del> } <del> return volumesOut, warnings, nil <del>} <del> <del>// filterVolumes filters volume list according to user specified filter <del>// and returns user chosen volumes <del>func (daemon *Daemon) filterVolumes(vols []volume.Volume, filter filters.Args) ([]volume.Volume, error) { <del> // if filter is empty, return original volume list <del> if filter.Len() == 0 { <del> return vols, nil <del> } <del> <del> var retVols []volume.Volume <del> for _, vol := range vols { <del> if filter.Contains("name") { <del> if !filter.Match("name", vol.Name()) { <del> continue <del> } <del> } <del> if filter.Contains("driver") { <del> if !filter.ExactMatch("driver", vol.DriverName()) { <del> continue <del> } <del> } <del> if filter.Contains("label") { <del> v, ok := vol.(volume.DetailedVolume) <del> if !ok { <del> continue <del> } <del> if !filter.MatchKVList("label", v.Labels()) { <del> continue <del> } <del> } <del> retVols = append(retVols, vol) <del> } <del> danglingOnly := false <del> if filter.Contains("dangling") { <del> if filter.ExactMatch("dangling", "true") || filter.ExactMatch("dangling", "1") { <del> danglingOnly = true <del> } else if !filter.ExactMatch("dangling", "false") && !filter.ExactMatch("dangling", "0") { <del> return nil, invalidFilter{"dangling", filter.Get("dangling")} <del> } <del> retVols = daemon.volumes.FilterByUsed(retVols, !danglingOnly) <del> } <del> return retVols, nil <del>} <del> <ide> func populateImageFilterByParents(ancestorMap map[image.ID]bool, imageID image.ID, getChildren func(image.ID) []image.ID) { <ide> if !ancestorMap[imageID] { <ide> for _, id := range getChildren(imageID) { <ide><path>daemon/mounts.go <ide> package daemon // import "github.com/docker/docker/daemon" <ide> <ide> import ( <add> "context" <ide> "fmt" <ide> "strings" <ide> <ide> mounttypes "github.com/docker/docker/api/types/mount" <ide> "github.com/docker/docker/container" <del> volumestore "github.com/docker/docker/volume/store" <add> volumesservice "github.com/docker/docker/volume/service" <ide> ) <ide> <ide> func (daemon *Daemon) prepareMountPoints(container *container.Container) error { <ide> func (daemon *Daemon) prepareMountPoints(container *container.Container) error { <ide> <ide> func (daemon *Daemon) removeMountPoints(container *container.Container, rm bool) error { <ide> var rmErrors []string <add> ctx := context.TODO() <ide> for _, m := range container.MountPoints { <ide> if m.Type != mounttypes.TypeVolume || m.Volume == nil { <ide> continue <ide> } <del> daemon.volumes.Dereference(m.Volume, container.ID) <add> daemon.volumes.Release(ctx, m.Volume.Name(), container.ID) <ide> if !rm { <ide> continue <ide> } <ide> func (daemon *Daemon) removeMountPoints(container *container.Container, rm bool) <ide> continue <ide> } <ide> <del> err := daemon.volumes.Remove(m.Volume) <add> err := daemon.volumes.Remove(ctx, m.Volume.Name()) <ide> // Ignore volume in use errors because having this <ide> // volume being referenced by other container is <ide> // not an error, but an implementation detail. <ide> // This prevents docker from logging "ERROR: Volume in use" <ide> // where there is another container using the volume. <del> if err != nil && !volumestore.IsInUse(err) { <add> if err != nil && !volumesservice.IsInUse(err) { <ide> rmErrors = append(rmErrors, err.Error()) <ide> } <ide> } <ide><path>daemon/prune.go <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> timetypes "github.com/docker/docker/api/types/time" <del> "github.com/docker/docker/pkg/directory" <add> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/runconfig" <del> "github.com/docker/docker/volume" <ide> "github.com/docker/libnetwork" <add> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> var ( <ide> // errPruneRunning is returned when a prune request is received while <ide> // one is in progress <del> errPruneRunning = fmt.Errorf("a prune operation is already running") <add> errPruneRunning = errdefs.Conflict(errors.New("a prune operation is already running")) <ide> <ide> containersAcceptedFilters = map[string]bool{ <ide> "label": true, <ide> "label!": true, <ide> "until": true, <ide> } <del> volumesAcceptedFilters = map[string]bool{ <del> "label": true, <del> "label!": true, <del> } <ide> <ide> networksAcceptedFilters = map[string]bool{ <ide> "label": true, <ide> func (daemon *Daemon) ContainersPrune(ctx context.Context, pruneFilters filters. <ide> return rep, nil <ide> } <ide> <del>// VolumesPrune removes unused local volumes <del>func (daemon *Daemon) VolumesPrune(ctx context.Context, pruneFilters filters.Args) (*types.VolumesPruneReport, error) { <del> if !atomic.CompareAndSwapInt32(&daemon.pruneRunning, 0, 1) { <del> return nil, errPruneRunning <del> } <del> defer atomic.StoreInt32(&daemon.pruneRunning, 0) <del> <del> // make sure that only accepted filters have been received <del> err := pruneFilters.Validate(volumesAcceptedFilters) <del> if err != nil { <del> return nil, err <del> } <del> <del> rep := &types.VolumesPruneReport{} <del> <del> volumes, err := daemon.volumes.FilterByDriver(volume.DefaultDriverName) <del> if err != nil { <del> return nil, err <del> } <del> <del> for _, v := range volumes { <del> select { <del> case <-ctx.Done(): <del> logrus.Debugf("VolumesPrune operation cancelled: %#v", *rep) <del> err := ctx.Err() <del> if err == context.Canceled { <del> return rep, nil <del> } <del> return rep, err <del> default: <del> } <del> <del> name := v.Name() <del> refs := daemon.volumes.Refs(v) <del> <del> if len(refs) == 0 { <del> detailedVolume, ok := v.(volume.DetailedVolume) <del> if ok { <del> if !matchLabels(pruneFilters, detailedVolume.Labels()) { <del> continue <del> } <del> } <del> <del> vSize, err := directory.Size(ctx, v.Path()) <del> if err != nil { <del> logrus.Warnf("could not determine size of volume %s: %v", name, err) <del> } <del> err = daemon.volumeRm(v) <del> if err != nil { <del> logrus.Warnf("could not remove volume %s: %v", name, err) <del> continue <del> } <del> rep.SpaceReclaimed += uint64(vSize) <del> rep.VolumesDeleted = append(rep.VolumesDeleted, name) <del> } <del> <del> } <del> <del> return rep, nil <del>} <del> <ide> // localNetworksPrune removes unused local networks <ide> func (daemon *Daemon) localNetworksPrune(ctx context.Context, pruneFilters filters.Args) *types.NetworksPruneReport { <ide> rep := &types.NetworksPruneReport{} <ide><path>daemon/volumes.go <ide> package daemon // import "github.com/docker/docker/daemon" <ide> <ide> import ( <add> "context" <ide> "os" <ide> "path/filepath" <ide> "reflect" <ide> import ( <ide> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/volume" <ide> volumemounts "github.com/docker/docker/volume/mounts" <add> "github.com/docker/docker/volume/service" <add> volumeopts "github.com/docker/docker/volume/service/opts" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> var ( <ide> <ide> type mounts []container.Mount <ide> <del>// volumeToAPIType converts a volume.Volume to the type used by the Engine API <del>func volumeToAPIType(v volume.Volume) *types.Volume { <del> createdAt, _ := v.CreatedAt() <del> tv := &types.Volume{ <del> Name: v.Name(), <del> Driver: v.DriverName(), <del> CreatedAt: createdAt.Format(time.RFC3339), <del> } <del> if v, ok := v.(volume.DetailedVolume); ok { <del> tv.Labels = v.Labels() <del> tv.Options = v.Options() <del> tv.Scope = v.Scope() <del> } <del> <del> return tv <del>} <del> <ide> // Len returns the number of mounts. Used in sorting. <ide> func (m mounts) Len() int { <ide> return len(m) <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> mountPoints := map[string]*volumemounts.MountPoint{} <ide> parser := volumemounts.NewParser(container.OS) <ide> <add> ctx := context.TODO() <ide> defer func() { <ide> // clean up the container mountpoints once return with error <ide> if retErr != nil { <ide> for _, m := range mountPoints { <ide> if m.Volume == nil { <ide> continue <ide> } <del> daemon.volumes.Dereference(m.Volume, container.ID) <add> daemon.volumes.Release(ctx, m.Volume.Name(), container.ID) <ide> } <ide> } <ide> }() <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> if v, ok := mountPoints[destination]; ok { <ide> logrus.Debugf("Duplicate mount point '%s'", destination) <ide> if v.Volume != nil { <del> daemon.volumes.Dereference(v.Volume, container.ID) <add> daemon.volumes.Release(ctx, v.Volume.Name(), container.ID) <ide> } <ide> } <ide> } <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> } <ide> <ide> if len(cp.Source) == 0 { <del> v, err := daemon.volumes.GetWithRef(cp.Name, cp.Driver, container.ID) <add> v, err := daemon.volumes.Get(ctx, cp.Name, volumeopts.WithGetDriver(cp.Driver), volumeopts.WithGetReference(container.ID)) <ide> if err != nil { <ide> return err <ide> } <del> cp.Volume = v <add> cp.Volume = &volumeWrapper{v: v, s: daemon.volumes} <ide> } <ide> dereferenceIfExists(cp.Destination) <ide> mountPoints[cp.Destination] = cp <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> <ide> if bind.Type == mounttypes.TypeVolume { <ide> // create the volume <del> v, err := daemon.volumes.CreateWithRef(bind.Name, bind.Driver, container.ID, nil, nil) <add> v, err := daemon.volumes.Create(ctx, bind.Name, bind.Driver, volumeopts.WithCreateReference(container.ID)) <ide> if err != nil { <ide> return err <ide> } <del> bind.Volume = v <del> bind.Source = v.Path() <add> bind.Volume = &volumeWrapper{v: v, s: daemon.volumes} <add> bind.Source = v.Mountpoint <ide> // bind.Name is an already existing volume, we need to use that here <del> bind.Driver = v.DriverName() <add> bind.Driver = v.Driver <ide> if bind.Driver == volume.DefaultDriverName { <ide> setBindModeIfNull(bind) <ide> } <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> } <ide> <ide> if mp.Type == mounttypes.TypeVolume { <del> var v volume.Volume <add> var v *types.Volume <ide> if cfg.VolumeOptions != nil { <ide> var driverOpts map[string]string <ide> if cfg.VolumeOptions.DriverConfig != nil { <ide> driverOpts = cfg.VolumeOptions.DriverConfig.Options <ide> } <del> v, err = daemon.volumes.CreateWithRef(mp.Name, mp.Driver, container.ID, driverOpts, cfg.VolumeOptions.Labels) <add> v, err = daemon.volumes.Create(ctx, <add> mp.Name, <add> mp.Driver, <add> volumeopts.WithCreateReference(container.ID), <add> volumeopts.WithCreateOptions(driverOpts), <add> volumeopts.WithCreateLabels(cfg.VolumeOptions.Labels), <add> ) <ide> } else { <del> v, err = daemon.volumes.CreateWithRef(mp.Name, mp.Driver, container.ID, nil, nil) <add> v, err = daemon.volumes.Create(ctx, mp.Name, mp.Driver, volumeopts.WithCreateReference(container.ID)) <ide> } <ide> if err != nil { <ide> return err <ide> } <ide> <del> mp.Volume = v <del> mp.Name = v.Name() <del> mp.Driver = v.DriverName() <add> mp.Volume = &volumeWrapper{v: v, s: daemon.volumes} <add> mp.Name = v.Name <add> mp.Driver = v.Driver <ide> <del> // only use the cached path here since getting the path is not necessary right now and calling `Path()` may be slow <del> if cv, ok := v.(interface { <del> CachedPath() string <del> }); ok { <del> mp.Source = cv.CachedPath() <del> } <ide> if mp.Driver == volume.DefaultDriverName { <ide> setBindModeIfNull(mp) <ide> } <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> for _, m := range mountPoints { <ide> if parser.IsBackwardCompatible(m) { <ide> if mp, exists := container.MountPoints[m.Destination]; exists && mp.Volume != nil { <del> daemon.volumes.Dereference(mp.Volume, container.ID) <add> daemon.volumes.Release(ctx, mp.Volume.Name(), container.ID) <ide> } <ide> } <ide> } <ide> func (daemon *Daemon) registerMountPoints(container *container.Container, hostCo <ide> // This happens after a daemon restart. <ide> func (daemon *Daemon) lazyInitializeVolume(containerID string, m *volumemounts.MountPoint) error { <ide> if len(m.Driver) > 0 && m.Volume == nil { <del> v, err := daemon.volumes.GetWithRef(m.Name, m.Driver, containerID) <add> v, err := daemon.volumes.Get(context.TODO(), m.Name, volumeopts.WithGetDriver(m.Driver), volumeopts.WithGetReference(containerID)) <ide> if err != nil { <ide> return err <ide> } <del> m.Volume = v <add> m.Volume = &volumeWrapper{v: v, s: daemon.volumes} <ide> } <ide> return nil <ide> } <ide> func (daemon *Daemon) backportMountSpec(container *container.Container) { <ide> cm.Spec.ReadOnly = !cm.RW <ide> } <ide> } <add> <add>// VolumesService is used to perform volume operations <add>func (daemon *Daemon) VolumesService() *service.VolumesService { <add> return daemon.volumes <add>} <add> <add>type volumeMounter interface { <add> Mount(ctx context.Context, v *types.Volume, ref string) (string, error) <add> Unmount(ctx context.Context, v *types.Volume, ref string) error <add>} <add> <add>type volumeWrapper struct { <add> v *types.Volume <add> s volumeMounter <add>} <add> <add>func (v *volumeWrapper) Name() string { <add> return v.v.Name <add>} <add> <add>func (v *volumeWrapper) DriverName() string { <add> return v.v.Driver <add>} <add> <add>func (v *volumeWrapper) Path() string { <add> return v.v.Mountpoint <add>} <add> <add>func (v *volumeWrapper) Mount(ref string) (string, error) { <add> return v.s.Mount(context.TODO(), v.v, ref) <add>} <add> <add>func (v *volumeWrapper) Unmount(ref string) error { <add> return v.s.Unmount(context.TODO(), v.v, ref) <add>} <add> <add>func (v *volumeWrapper) CreatedAt() (time.Time, error) { <add> return time.Time{}, errors.New("not implemented") <add>} <add> <add>func (v *volumeWrapper) Status() map[string]interface{} { <add> return v.v.Status <add>} <ide><path>integration-cli/docker_cli_events_unix_test.go <ide> func (s *DockerSuite) TestVolumeEvents(c *check.C) { <ide> c.Assert(len(events), checker.GreaterThan, 4) <ide> <ide> volumeEvents := eventActionsByIDAndType(c, events, "test-event-volume-local", "volume") <del> c.Assert(volumeEvents, checker.HasLen, 4) <add> c.Assert(volumeEvents, checker.HasLen, 5) <ide> c.Assert(volumeEvents[0], checker.Equals, "create") <del> c.Assert(volumeEvents[1], checker.Equals, "mount") <del> c.Assert(volumeEvents[2], checker.Equals, "unmount") <del> c.Assert(volumeEvents[3], checker.Equals, "destroy") <add> c.Assert(volumeEvents[1], checker.Equals, "create") <add> c.Assert(volumeEvents[2], checker.Equals, "mount") <add> c.Assert(volumeEvents[3], checker.Equals, "unmount") <add> c.Assert(volumeEvents[4], checker.Equals, "destroy") <ide> } <ide> <ide> func (s *DockerSuite) TestNetworkEvents(c *check.C) { <ide><path>integration-cli/docker_cli_external_volume_driver_unix_test.go <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverGetEmptyResponse(c * <ide> } <ide> <ide> // Ensure only cached paths are used in volume list to prevent N+1 calls to `VolumeDriver.Path` <add>// <add>// TODO(@cpuguy83): This test is testing internal implementation. In all the cases here, there may not even be a path <add>// available because the volume is not even mounted. Consider removing this test. <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverPathCalls(c *check.C) { <ide> s.d.Start(c) <ide> c.Assert(s.ec.paths, checker.Equals, 0) <ide> <ide> out, err := s.d.Cmd("volume", "create", "test", "--driver=test-external-volume-driver") <ide> c.Assert(err, checker.IsNil, check.Commentf(out)) <del> c.Assert(s.ec.paths, checker.Equals, 1) <add> c.Assert(s.ec.paths, checker.Equals, 0) <ide> <ide> out, err = s.d.Cmd("volume", "ls") <ide> c.Assert(err, checker.IsNil, check.Commentf(out)) <del> c.Assert(s.ec.paths, checker.Equals, 1) <del> <del> out, err = s.d.Cmd("volume", "inspect", "--format='{{.Mountpoint}}'", "test") <del> c.Assert(err, checker.IsNil, check.Commentf(out)) <del> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <del> c.Assert(s.ec.paths, checker.Equals, 1) <add> c.Assert(s.ec.paths, checker.Equals, 0) <ide> } <ide> <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverMountID(c *check.C) { <ide><path>pkg/directory/directory_unix.go <del>// +build linux freebsd <add>// +build linux freebsd darwin <ide> <ide> package directory // import "github.com/docker/docker/pkg/directory" <ide> <ide><path>volume/drivers/adapter.go <ide> func (a *volumeDriverAdapter) getCapabilities() volume.Capability { <ide> if err != nil { <ide> // `GetCapabilities` is a not a required endpoint. <ide> // On error assume it's a local-only driver <del> logrus.Warnf("Volume driver %s returned an error while trying to query its capabilities, using default capabilities: %v", a.name, err) <add> logrus.WithError(err).WithField("driver", a.name).Debug("Volume driver returned an error while trying to query its capabilities, using default capabilities") <ide> return volume.Capability{Scope: volume.LocalScope} <ide> } <ide> <ide> func (a *volumeDriverAdapter) getCapabilities() volume.Capability { <ide> <ide> cap.Scope = strings.ToLower(cap.Scope) <ide> if cap.Scope != volume.LocalScope && cap.Scope != volume.GlobalScope { <del> logrus.Warnf("Volume driver %q returned an invalid scope: %q", a.Name(), cap.Scope) <add> logrus.WithField("driver", a.Name()).WithField("scope", a.Scope).Warn("Volume driver returned an invalid scope") <ide> cap.Scope = volume.LocalScope <ide> } <ide> <ide><path>volume/drivers/extpoint.go <ide> func (s *Store) ReleaseDriver(name string) (volume.Driver, error) { <ide> func (s *Store) GetDriverList() []string { <ide> var driverList []string <ide> s.mu.Lock() <add> defer s.mu.Unlock() <ide> for driverName := range s.extensions { <ide> driverList = append(driverList, driverName) <ide> } <del> s.mu.Unlock() <ide> sort.Strings(driverList) <ide> return driverList <ide> } <ide><path>volume/service/by.go <add>package service // import "github.com/docker/docker/volume/service" <add> <add>import ( <add> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/volume" <add>) <add> <add>// By is an interface which is used to implement filtering on volumes. <add>type By interface { <add> isBy() <add>} <add> <add>// ByDriver is `By` that filters based on the driver names that are passed in <add>func ByDriver(drivers ...string) By { <add> return byDriver(drivers) <add>} <add> <add>type byDriver []string <add> <add>func (byDriver) isBy() {} <add> <add>// ByReferenced is a `By` that filters based on if the volume has references <add>type ByReferenced bool <add> <add>func (ByReferenced) isBy() {} <add> <add>// And creates a `By` combining all the passed in bys using AND logic. <add>func And(bys ...By) By { <add> and := make(andCombinator, 0, len(bys)) <add> for _, by := range bys { <add> and = append(and, by) <add> } <add> return and <add>} <add> <add>type andCombinator []By <add> <add>func (andCombinator) isBy() {} <add> <add>// Or creates a `By` combining all the passed in bys using OR logic. <add>func Or(bys ...By) By { <add> or := make(orCombinator, 0, len(bys)) <add> for _, by := range bys { <add> or = append(or, by) <add> } <add> return or <add>} <add> <add>type orCombinator []By <add> <add>func (orCombinator) isBy() {} <add> <add>// CustomFilter is a `By` that is used by callers to provide custom filtering <add>// logic. <add>type CustomFilter filterFunc <add> <add>func (CustomFilter) isBy() {} <add> <add>// FromList returns a By which sets the initial list of volumes to use <add>func FromList(ls *[]volume.Volume, by By) By { <add> return &fromList{by: by, ls: ls} <add>} <add> <add>type fromList struct { <add> by By <add> ls *[]volume.Volume <add>} <add> <add>func (fromList) isBy() {} <add> <add>func byLabelFilter(filter filters.Args) By { <add> return CustomFilter(func(v volume.Volume) bool { <add> dv, ok := v.(volume.DetailedVolume) <add> if !ok { <add> return false <add> } <add> <add> labels := dv.Labels() <add> if !filter.MatchKVList("label", labels) { <add> return false <add> } <add> if filter.Contains("label!") { <add> if filter.MatchKVList("label!", labels) { <add> return false <add> } <add> } <add> return true <add> }) <add>} <ide><path>volume/service/convert.go <add>package service <add> <add>import ( <add> "context" <add> "time" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/pkg/directory" <add> "github.com/docker/docker/volume" <add> "github.com/sirupsen/logrus" <add>) <add> <add>// convertOpts are used to pass options to `volumeToAPI` <add>type convertOpt interface { <add> isConvertOpt() <add>} <add> <add>type useCachedPath bool <add> <add>func (useCachedPath) isConvertOpt() {} <add> <add>type calcSize bool <add> <add>func (calcSize) isConvertOpt() {} <add> <add>type pathCacher interface { <add> CachedPath() string <add>} <add> <add>func (s *VolumesService) volumesToAPI(ctx context.Context, volumes []volume.Volume, opts ...convertOpt) []*types.Volume { <add> var ( <add> out = make([]*types.Volume, 0, len(volumes)) <add> getSize bool <add> cachedPath bool <add> ) <add> <add> for _, o := range opts { <add> switch t := o.(type) { <add> case calcSize: <add> getSize = bool(t) <add> case useCachedPath: <add> cachedPath = bool(t) <add> } <add> } <add> for _, v := range volumes { <add> select { <add> case <-ctx.Done(): <add> return nil <add> default: <add> } <add> apiV := volumeToAPIType(v) <add> <add> if cachedPath { <add> if vv, ok := v.(pathCacher); ok { <add> apiV.Mountpoint = vv.CachedPath() <add> } <add> } else { <add> apiV.Mountpoint = v.Path() <add> } <add> <add> if getSize { <add> p := v.Path() <add> if apiV.Mountpoint == "" { <add> apiV.Mountpoint = p <add> } <add> sz, err := directory.Size(ctx, p) <add> if err != nil { <add> logrus.WithError(err).WithField("volume", v.Name()).Warnf("Failed to determine size of volume") <add> sz = -1 <add> } <add> apiV.UsageData = &types.VolumeUsageData{Size: sz, RefCount: int64(s.vs.CountReferences(v))} <add> } <add> <add> out = append(out, &apiV) <add> } <add> return out <add>} <add> <add>func volumeToAPIType(v volume.Volume) types.Volume { <add> createdAt, _ := v.CreatedAt() <add> tv := types.Volume{ <add> Name: v.Name(), <add> Driver: v.DriverName(), <add> CreatedAt: createdAt.Format(time.RFC3339), <add> } <add> if v, ok := v.(volume.DetailedVolume); ok { <add> tv.Labels = v.Labels() <add> tv.Options = v.Options() <add> tv.Scope = v.Scope() <add> } <add> if cp, ok := v.(pathCacher); ok { <add> tv.Mountpoint = cp.CachedPath() <add> } <add> return tv <add>} <add> <add>func filtersToBy(filter filters.Args, acceptedFilters map[string]bool) (By, error) { <add> if err := filter.Validate(acceptedFilters); err != nil { <add> return nil, err <add> } <add> var bys []By <add> if drivers := filter.Get("driver"); len(drivers) > 0 { <add> bys = append(bys, ByDriver(drivers...)) <add> } <add> if filter.Contains("name") { <add> bys = append(bys, CustomFilter(func(v volume.Volume) bool { <add> return filter.Match("name", v.Name()) <add> })) <add> } <add> bys = append(bys, byLabelFilter(filter)) <add> <add> if filter.Contains("dangling") { <add> var dangling bool <add> if filter.ExactMatch("dangling", "true") || filter.ExactMatch("dangling", "1") { <add> dangling = true <add> } else if !filter.ExactMatch("dangling", "false") && !filter.ExactMatch("dangling", "0") { <add> return nil, invalidFilter{"dangling", filter.Get("dangling")} <add> } <add> bys = append(bys, ByReferenced(!dangling)) <add> } <add> <add> var by By <add> switch len(bys) { <add> case 0: <add> case 1: <add> by = bys[0] <add> default: <add> by = And(bys...) <add> } <add> return by, nil <add>} <add><path>volume/service/db.go <del><path>volume/store/db.go <del>package store // import "github.com/docker/docker/volume/store" <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> import ( <ide> "encoding/json" <add><path>volume/service/db_test.go <del><path>volume/store/db_test.go <del>package store <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> import ( <ide> "io/ioutil" <ide><path>volume/service/default_driver.go <add>// +build linux windows <add> <add>package service // import "github.com/docker/docker/volume/service" <add>import ( <add> "github.com/docker/docker/pkg/idtools" <add> "github.com/docker/docker/volume" <add> "github.com/docker/docker/volume/drivers" <add> "github.com/docker/docker/volume/local" <add> "github.com/pkg/errors" <add>) <add> <add>func setupDefaultDriver(store *drivers.Store, root string, rootIDs idtools.IDPair) error { <add> d, err := local.New(root, rootIDs) <add> if err != nil { <add> return errors.Wrap(err, "error setting up default driver") <add> } <add> if !store.Register(d, volume.DefaultDriverName) { <add> return errors.New("local volume driver could not be registered") <add> } <add> return nil <add>} <ide><path>volume/service/default_driver_stubs.go <add>// +build !linux,!windows <add> <add>package service // import "github.com/docker/docker/volume/service" <add> <add>import ( <add> "github.com/docker/docker/pkg/idtools" <add> "github.com/docker/docker/volume/drivers" <add>) <add> <add>func setupDefaultDriver(_ *drivers.Store, _ string, _ idtools.IDPair) error { return nil } <add><path>volume/service/errors.go <del><path>volume/store/errors.go <del>package store // import "github.com/docker/docker/volume/store" <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> import ( <add> "fmt" <ide> "strings" <ide> ) <ide> <ide> func isErr(err error, expected error) bool { <ide> } <ide> return err == expected <ide> } <add> <add>type invalidFilter struct { <add> filter string <add> value interface{} <add>} <add> <add>func (e invalidFilter) Error() string { <add> msg := "Invalid filter '" + e.filter <add> if e.value != nil { <add> msg += fmt.Sprintf("=%s", e.value) <add> } <add> return msg + "'" <add>} <add> <add>func (e invalidFilter) InvalidParameter() {} <ide><path>volume/service/opts/opts.go <add>package opts <add> <add>// CreateOption is used to pass options in when creating a volume <add>type CreateOption func(*CreateConfig) <add> <add>// CreateConfig is the set of config options that can be set when creating <add>// a volume <add>type CreateConfig struct { <add> Options map[string]string <add> Labels map[string]string <add> Reference string <add>} <add> <add>// WithCreateLabels creates a CreateOption which sets the labels to the <add>// passed in value <add>func WithCreateLabels(labels map[string]string) CreateOption { <add> return func(cfg *CreateConfig) { <add> cfg.Labels = labels <add> } <add>} <add> <add>// WithCreateOptions creates a CreateOption which sets the options passed <add>// to the volume driver when creating a volume to the options passed in. <add>func WithCreateOptions(opts map[string]string) CreateOption { <add> return func(cfg *CreateConfig) { <add> cfg.Options = opts <add> } <add>} <add> <add>// WithCreateReference creats a CreateOption which sets a reference to use <add>// when creating a volume. This ensures that the volume is created with a reference <add>// already attached to it to prevent race conditions with Create and volume cleanup. <add>func WithCreateReference(ref string) CreateOption { <add> return func(cfg *CreateConfig) { <add> cfg.Reference = ref <add> } <add>} <add> <add>// GetConfig is used with `GetOption` to set options for the volumes service's <add>// `Get` implementation. <add>type GetConfig struct { <add> Driver string <add> Reference string <add> ResolveStatus bool <add>} <add> <add>// GetOption is passed to the service `Get` add extra details on the get request <add>type GetOption func(*GetConfig) <add> <add>// WithGetDriver provides the driver to get the volume from <add>// If no driver is provided to `Get`, first the available metadata is checked <add>// to see which driver it belongs to, if that is not available all drivers are <add>// probed to find the volume. <add>func WithGetDriver(name string) GetOption { <add> return func(o *GetConfig) { <add> o.Driver = name <add> } <add>} <add> <add>// WithGetReference indicates to `Get` to increment the reference count for the <add>// retreived volume with the provided reference ID. <add>func WithGetReference(ref string) GetOption { <add> return func(o *GetConfig) { <add> o.Reference = ref <add> } <add>} <add> <add>// WithGetResolveStatus indicates to `Get` to also fetch the volume status. <add>// This can cause significant overhead in the volume lookup. <add>func WithGetResolveStatus(cfg *GetConfig) { <add> cfg.ResolveStatus = true <add>} <add> <add>// RemoveConfig is used by `RemoveOption` to store config options for remove <add>type RemoveConfig struct { <add> PurgeOnError bool <add>} <add> <add>// RemoveOption is used to pass options to the volumes service `Remove` implementation <add>type RemoveOption func(*RemoveConfig) <add> <add>// WithPurgeOnError is an option passed to `Remove` which will purge all cached <add>// data about a volume even if there was an error while attempting to remove the <add>// volume. <add>func WithPurgeOnError(b bool) RemoveOption { <add> return func(o *RemoveConfig) { <add> o.PurgeOnError = b <add> } <add>} <add><path>volume/service/restore.go <del><path>volume/store/restore.go <del>package store // import "github.com/docker/docker/volume/store" <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> import ( <add> "context" <ide> "sync" <ide> <ide> "github.com/boltdb/bolt" <ide> func (s *VolumeStore) restore() { <ide> ls = listMeta(tx) <ide> return nil <ide> }) <add> ctx := context.Background() <ide> <ide> chRemove := make(chan *volumeMetadata, len(ls)) <ide> var wg sync.WaitGroup <ide> func (s *VolumeStore) restore() { <ide> var v volume.Volume <ide> var err error <ide> if meta.Driver != "" { <del> v, err = lookupVolume(s.drivers, meta.Driver, meta.Name) <add> v, err = lookupVolume(ctx, s.drivers, meta.Driver, meta.Name) <ide> if err != nil && err != errNoSuchVolume { <ide> logrus.WithError(err).WithField("driver", meta.Driver).WithField("volume", meta.Name).Warn("Error restoring volume") <ide> return <ide> func (s *VolumeStore) restore() { <ide> return <ide> } <ide> } else { <del> v, err = s.getVolume(meta.Name) <add> v, err = s.getVolume(ctx, meta.Name, meta.Driver) <ide> if err != nil { <ide> if err == errNoSuchVolume { <ide> chRemove <- &meta <ide> func (s *VolumeStore) restore() { <ide> s.options[v.Name()] = meta.Options <ide> s.labels[v.Name()] = meta.Labels <ide> s.names[v.Name()] = v <add> s.refs[v.Name()] = make(map[string]struct{}) <ide> s.globalLock.Unlock() <ide> }(meta) <ide> } <add><path>volume/service/restore_test.go <del><path>volume/store/restore_test.go <del>package store <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> import ( <add> "context" <ide> "io/ioutil" <ide> "os" <ide> "testing" <ide> <ide> "github.com/docker/docker/volume" <ide> volumedrivers "github.com/docker/docker/volume/drivers" <add> "github.com/docker/docker/volume/service/opts" <ide> volumetestutils "github.com/docker/docker/volume/testutils" <ide> "github.com/gotestyourself/gotestyourself/assert" <ide> ) <ide> func TestRestore(t *testing.T) { <ide> driverName := "test-restore" <ide> drivers.Register(volumetestutils.NewFakeDriver(driverName), driverName) <ide> <del> s, err := New(dir, drivers) <add> s, err := NewStore(dir, drivers) <ide> assert.NilError(t, err) <ide> defer s.Shutdown() <ide> <del> _, err = s.Create("test1", driverName, nil, nil) <add> ctx := context.Background() <add> _, err = s.Create(ctx, "test1", driverName) <ide> assert.NilError(t, err) <ide> <ide> testLabels := map[string]string{"a": "1"} <ide> testOpts := map[string]string{"foo": "bar"} <del> _, err = s.Create("test2", driverName, testOpts, testLabels) <add> _, err = s.Create(ctx, "test2", driverName, opts.WithCreateOptions(testOpts), opts.WithCreateLabels(testLabels)) <ide> assert.NilError(t, err) <ide> <ide> s.Shutdown() <ide> <del> s, err = New(dir, drivers) <add> s, err = NewStore(dir, drivers) <ide> assert.NilError(t, err) <ide> <del> v, err := s.Get("test1") <add> v, err := s.Get(ctx, "test1") <ide> assert.NilError(t, err) <ide> <ide> dv := v.(volume.DetailedVolume) <ide> var nilMap map[string]string <ide> assert.DeepEqual(t, nilMap, dv.Options()) <ide> assert.DeepEqual(t, nilMap, dv.Labels()) <ide> <del> v, err = s.Get("test2") <add> v, err = s.Get(ctx, "test2") <ide> assert.NilError(t, err) <ide> dv = v.(volume.DetailedVolume) <ide> assert.DeepEqual(t, testOpts, dv.Options()) <ide><path>volume/service/service.go <add>package service // import "github.com/docker/docker/volume/service" <add> <add>import ( <add> "context" <add> "sync/atomic" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/errdefs" <add> "github.com/docker/docker/pkg/directory" <add> "github.com/docker/docker/pkg/idtools" <add> "github.com/docker/docker/pkg/plugingetter" <add> "github.com/docker/docker/pkg/stringid" <add> "github.com/docker/docker/volume" <add> "github.com/docker/docker/volume/drivers" <add> "github.com/docker/docker/volume/service/opts" <add> "github.com/pkg/errors" <add> "github.com/sirupsen/logrus" <add>) <add> <add>type ds interface { <add> GetDriverList() []string <add>} <add> <add>type volumeEventLogger interface { <add> LogVolumeEvent(volumeID, action string, attributes map[string]string) <add>} <add> <add>// VolumesService manages access to volumes <add>type VolumesService struct { <add> vs *VolumeStore <add> ds ds <add> pruneRunning int32 <add> eventLogger volumeEventLogger <add>} <add> <add>// NewVolumeService creates a new volume service <add>func NewVolumeService(root string, pg plugingetter.PluginGetter, rootIDs idtools.IDPair, logger volumeEventLogger) (*VolumesService, error) { <add> ds := drivers.NewStore(pg) <add> if err := setupDefaultDriver(ds, root, rootIDs); err != nil { <add> return nil, err <add> } <add> <add> vs, err := NewStore(root, ds) <add> if err != nil { <add> return nil, err <add> } <add> return &VolumesService{vs: vs, ds: ds, eventLogger: logger}, nil <add>} <add> <add>// GetDriverList gets the list of registered volume drivers <add>func (s *VolumesService) GetDriverList() []string { <add> return s.ds.GetDriverList() <add>} <add> <add>// Create creates a volume <add>func (s *VolumesService) Create(ctx context.Context, name, driverName string, opts ...opts.CreateOption) (*types.Volume, error) { <add> if name == "" { <add> name = stringid.GenerateNonCryptoID() <add> } <add> v, err := s.vs.Create(ctx, name, driverName, opts...) <add> if err != nil { <add> return nil, err <add> } <add> <add> s.eventLogger.LogVolumeEvent(v.Name(), "create", map[string]string{"driver": v.DriverName()}) <add> apiV := volumeToAPIType(v) <add> return &apiV, nil <add>} <add> <add>// Get gets a volume <add>func (s *VolumesService) Get(ctx context.Context, name string, getOpts ...opts.GetOption) (*types.Volume, error) { <add> v, err := s.vs.Get(ctx, name, getOpts...) <add> if err != nil { <add> return nil, err <add> } <add> vol := volumeToAPIType(v) <add> <add> var cfg opts.GetConfig <add> for _, o := range getOpts { <add> o(&cfg) <add> } <add> <add> if cfg.ResolveStatus { <add> vol.Status = v.Status() <add> } <add> return &vol, nil <add>} <add> <add>// Mount mounts the volume <add>func (s *VolumesService) Mount(ctx context.Context, vol *types.Volume, ref string) (string, error) { <add> v, err := s.vs.Get(ctx, vol.Name, opts.WithGetDriver(vol.Driver)) <add> if err != nil { <add> if IsNotExist(err) { <add> err = errdefs.NotFound(err) <add> } <add> return "", err <add> } <add> return v.Mount(ref) <add>} <add> <add>// Unmount unmounts the volume. <add>// Note that depending on the implementation, the volume may still be mounted due to other resources using it. <add>func (s *VolumesService) Unmount(ctx context.Context, vol *types.Volume, ref string) error { <add> v, err := s.vs.Get(ctx, vol.Name, opts.WithGetDriver(vol.Driver)) <add> if err != nil { <add> if IsNotExist(err) { <add> err = errdefs.NotFound(err) <add> } <add> return err <add> } <add> return v.Unmount(ref) <add>} <add> <add>// Release releases a volume reference <add>func (s *VolumesService) Release(ctx context.Context, name string, ref string) error { <add> return s.vs.Release(ctx, name, ref) <add>} <add> <add>// Remove removes a volume <add>func (s *VolumesService) Remove(ctx context.Context, name string, rmOpts ...opts.RemoveOption) error { <add> var cfg opts.RemoveConfig <add> for _, o := range rmOpts { <add> o(&cfg) <add> } <add> <add> v, err := s.vs.Get(ctx, name) <add> if err != nil { <add> if IsNotExist(err) && cfg.PurgeOnError { <add> return nil <add> } <add> return err <add> } <add> <add> err = s.vs.Remove(ctx, v, rmOpts...) <add> if IsNotExist(err) { <add> err = nil <add> } else if IsInUse(err) { <add> err = errdefs.Conflict(err) <add> } else if IsNotExist(err) && cfg.PurgeOnError { <add> err = nil <add> } <add> <add> if err == nil { <add> s.eventLogger.LogVolumeEvent(v.Name(), "destroy", map[string]string{"driver": v.DriverName()}) <add> } <add> return err <add>} <add> <add>var acceptedPruneFilters = map[string]bool{ <add> "label": true, <add> "label!": true, <add>} <add> <add>var acceptedListFilters = map[string]bool{ <add> "dangling": true, <add> "name": true, <add> "driver": true, <add> "label": true, <add>} <add> <add>// LocalVolumesSize gets all local volumes and fetches their size on disk <add>// Note that this intentionally skips volumes which have mount options. Typically <add>// volumes with mount options are not really local even if they are using the <add>// local driver. <add>func (s *VolumesService) LocalVolumesSize(ctx context.Context) ([]*types.Volume, error) { <add> ls, _, err := s.vs.Find(ctx, And(ByDriver(volume.DefaultDriverName), CustomFilter(func(v volume.Volume) bool { <add> dv, ok := v.(volume.DetailedVolume) <add> return ok && len(dv.Options()) == 0 <add> }))) <add> if err != nil { <add> return nil, err <add> } <add> return s.volumesToAPI(ctx, ls, calcSize(true)), nil <add>} <add> <add>// Prune removes (local) volumes which match the past in filter arguments. <add>// Note that this intentionally skips volumes with mount options as there would <add>// be no space reclaimed in this case. <add>func (s *VolumesService) Prune(ctx context.Context, filter filters.Args) (*types.VolumesPruneReport, error) { <add> if !atomic.CompareAndSwapInt32(&s.pruneRunning, 0, 1) { <add> return nil, errdefs.Conflict(errors.New("a prune operation is already running")) <add> } <add> defer atomic.StoreInt32(&s.pruneRunning, 0) <add> <add> by, err := filtersToBy(filter, acceptedPruneFilters) <add> if err != nil { <add> return nil, err <add> } <add> ls, _, err := s.vs.Find(ctx, And(ByDriver(volume.DefaultDriverName), ByReferenced(false), by, CustomFilter(func(v volume.Volume) bool { <add> dv, ok := v.(volume.DetailedVolume) <add> return ok && len(dv.Options()) == 0 <add> }))) <add> if err != nil { <add> return nil, err <add> } <add> <add> rep := &types.VolumesPruneReport{VolumesDeleted: make([]string, 0, len(ls))} <add> for _, v := range ls { <add> select { <add> case <-ctx.Done(): <add> err := ctx.Err() <add> if err == context.Canceled { <add> err = nil <add> } <add> return rep, err <add> default: <add> } <add> <add> vSize, err := directory.Size(ctx, v.Path()) <add> if err != nil { <add> logrus.WithField("volume", v.Name()).WithError(err).Warn("could not determine size of volume") <add> } <add> if err := s.vs.Remove(ctx, v); err != nil { <add> logrus.WithError(err).WithField("volume", v.Name()).Warnf("Could not determine size of volume") <add> continue <add> } <add> rep.SpaceReclaimed += uint64(vSize) <add> rep.VolumesDeleted = append(rep.VolumesDeleted, v.Name()) <add> } <add> return rep, nil <add>} <add> <add>// List gets the list of volumes which match the past in filters <add>// If filters is nil or empty all volumes are returned. <add>func (s *VolumesService) List(ctx context.Context, filter filters.Args) (volumesOut []*types.Volume, warnings []string, err error) { <add> by, err := filtersToBy(filter, acceptedListFilters) <add> if err != nil { <add> return nil, nil, err <add> } <add> <add> volumes, warnings, err := s.vs.Find(ctx, by) <add> if err != nil { <add> return nil, nil, err <add> } <add> <add> return s.volumesToAPI(ctx, volumes, useCachedPath(true)), warnings, nil <add>} <add> <add>// Shutdown shuts down the image service and dependencies <add>func (s *VolumesService) Shutdown() error { <add> return s.vs.Shutdown() <add>} <ide><path>volume/service/service_linux_test.go <add>package service <add> <add>import ( <add> "context" <add> "io/ioutil" <add> "os" <add> "path/filepath" <add> "testing" <add> <add> "github.com/docker/docker/pkg/idtools" <add> "github.com/docker/docker/volume" <add> volumedrivers "github.com/docker/docker/volume/drivers" <add> "github.com/docker/docker/volume/local" <add> "github.com/docker/docker/volume/service/opts" <add> "github.com/docker/docker/volume/testutils" <add> "github.com/gotestyourself/gotestyourself/assert" <add> is "github.com/gotestyourself/gotestyourself/assert/cmp" <add>) <add> <add>func TestLocalVolumeSize(t *testing.T) { <add> t.Parallel() <add> <add> ds := volumedrivers.NewStore(nil) <add> dir, err := ioutil.TempDir("", t.Name()) <add> assert.Assert(t, err) <add> defer os.RemoveAll(dir) <add> <add> l, err := local.New(dir, idtools.IDPair{UID: os.Getuid(), GID: os.Getegid()}) <add> assert.Assert(t, err) <add> assert.Assert(t, ds.Register(l, volume.DefaultDriverName)) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("fake"), "fake")) <add> <add> service, cleanup := newTestService(t, ds) <add> defer cleanup() <add> <add> ctx := context.Background() <add> v1, err := service.Create(ctx, "test1", volume.DefaultDriverName, opts.WithCreateReference("foo")) <add> assert.Assert(t, err) <add> v2, err := service.Create(ctx, "test2", volume.DefaultDriverName) <add> assert.Assert(t, err) <add> _, err = service.Create(ctx, "test3", "fake") <add> assert.Assert(t, err) <add> <add> data := make([]byte, 1024) <add> err = ioutil.WriteFile(filepath.Join(v1.Mountpoint, "data"), data, 0644) <add> assert.Assert(t, err) <add> err = ioutil.WriteFile(filepath.Join(v2.Mountpoint, "data"), data[:1], 0644) <add> assert.Assert(t, err) <add> <add> ls, err := service.LocalVolumesSize(ctx) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(ls, 2)) <add> <add> for _, v := range ls { <add> switch v.Name { <add> case "test1": <add> assert.Assert(t, is.Equal(v.UsageData.Size, int64(len(data)))) <add> assert.Assert(t, is.Equal(v.UsageData.RefCount, int64(1))) <add> case "test2": <add> assert.Assert(t, is.Equal(v.UsageData.Size, int64(len(data[:1])))) <add> assert.Assert(t, is.Equal(v.UsageData.RefCount, int64(0))) <add> default: <add> t.Fatalf("got unexpected volume: %+v", v) <add> } <add> } <add> assert.Assert(t, is.Equal(ls[1].UsageData.Size, int64(len(data[:1])))) <add>} <ide><path>volume/service/service_test.go <add>package service <add> <add>import ( <add> "context" <add> "io/ioutil" <add> "os" <add> "testing" <add> <add> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/errdefs" <add> "github.com/docker/docker/volume" <add> volumedrivers "github.com/docker/docker/volume/drivers" <add> "github.com/docker/docker/volume/service/opts" <add> "github.com/docker/docker/volume/testutils" <add> "github.com/gotestyourself/gotestyourself/assert" <add> is "github.com/gotestyourself/gotestyourself/assert/cmp" <add>) <add> <add>func TestServiceCreate(t *testing.T) { <add> t.Parallel() <add> <add> ds := volumedrivers.NewStore(nil) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("d1"), "d1")) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("d2"), "d2")) <add> <add> ctx := context.Background() <add> service, cleanup := newTestService(t, ds) <add> defer cleanup() <add> <add> _, err := service.Create(ctx, "v1", "notexist") <add> assert.Assert(t, errdefs.IsNotFound(err), err) <add> <add> v, err := service.Create(ctx, "v1", "d1") <add> assert.Assert(t, err) <add> <add> vCopy, err := service.Create(ctx, "v1", "d1") <add> assert.Assert(t, err) <add> assert.Assert(t, is.DeepEqual(v, vCopy)) <add> <add> _, err = service.Create(ctx, "v1", "d2") <add> assert.Check(t, IsNameConflict(err), err) <add> assert.Check(t, errdefs.IsConflict(err), err) <add> <add> assert.Assert(t, service.Remove(ctx, "v1")) <add> _, err = service.Create(ctx, "v1", "d2") <add> assert.Assert(t, err) <add> _, err = service.Create(ctx, "v1", "d2") <add> assert.Assert(t, err) <add> <add>} <add> <add>func TestServiceList(t *testing.T) { <add> t.Parallel() <add> <add> ds := volumedrivers.NewStore(nil) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("d1"), "d1")) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("d2"), "d2")) <add> <add> service, cleanup := newTestService(t, ds) <add> defer cleanup() <add> <add> ctx := context.Background() <add> <add> _, err := service.Create(ctx, "v1", "d1") <add> assert.Assert(t, err) <add> _, err = service.Create(ctx, "v2", "d1") <add> assert.Assert(t, err) <add> _, err = service.Create(ctx, "v3", "d2") <add> assert.Assert(t, err) <add> <add> ls, _, err := service.List(ctx, filters.NewArgs(filters.Arg("driver", "d1"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 2)) <add> <add> ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("driver", "d2"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 1)) <add> <add> ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("driver", "notexist"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 0)) <add> <add> ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "true"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 3)) <add> ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "false"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 0)) <add> <add> _, err = service.Get(ctx, "v1", opts.WithGetReference("foo")) <add> assert.Assert(t, err) <add> ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "true"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 2)) <add> ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "false"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 1)) <add> <add> ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "false"), filters.Arg("driver", "d2"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 0)) <add> ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "true"), filters.Arg("driver", "d2"))) <add> assert.Assert(t, err) <add> assert.Check(t, is.Len(ls, 1)) <add>} <add> <add>func TestServiceRemove(t *testing.T) { <add> t.Parallel() <add> <add> ds := volumedrivers.NewStore(nil) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("d1"), "d1")) <add> <add> service, cleanup := newTestService(t, ds) <add> defer cleanup() <add> ctx := context.Background() <add> <add> _, err := service.Create(ctx, "test", "d1") <add> assert.Assert(t, err) <add> <add> assert.Assert(t, service.Remove(ctx, "test")) <add> assert.Assert(t, service.Remove(ctx, "test", opts.WithPurgeOnError(true))) <add>} <add> <add>func TestServiceGet(t *testing.T) { <add> t.Parallel() <add> <add> ds := volumedrivers.NewStore(nil) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("d1"), "d1")) <add> <add> service, cleanup := newTestService(t, ds) <add> defer cleanup() <add> ctx := context.Background() <add> <add> v, err := service.Get(ctx, "notexist") <add> assert.Assert(t, IsNotExist(err)) <add> assert.Check(t, v == nil) <add> <add> created, err := service.Create(ctx, "test", "d1") <add> assert.Assert(t, err) <add> assert.Assert(t, created != nil) <add> <add> v, err = service.Get(ctx, "test") <add> assert.Assert(t, err) <add> assert.Assert(t, is.DeepEqual(created, v)) <add> <add> v, err = service.Get(ctx, "test", opts.WithGetResolveStatus) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(v.Status, 1), v.Status) <add> <add> v, err = service.Get(ctx, "test", opts.WithGetDriver("notarealdriver")) <add> assert.Assert(t, errdefs.IsConflict(err), err) <add> v, err = service.Get(ctx, "test", opts.WithGetDriver("d1")) <add> assert.Assert(t, err == nil) <add> assert.Assert(t, is.DeepEqual(created, v)) <add> <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("d2"), "d2")) <add> v, err = service.Get(ctx, "test", opts.WithGetDriver("d2")) <add> assert.Assert(t, errdefs.IsConflict(err), err) <add>} <add> <add>func TestServicePrune(t *testing.T) { <add> t.Parallel() <add> <add> ds := volumedrivers.NewStore(nil) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver(volume.DefaultDriverName), volume.DefaultDriverName)) <add> assert.Assert(t, ds.Register(testutils.NewFakeDriver("other"), "other")) <add> <add> service, cleanup := newTestService(t, ds) <add> defer cleanup() <add> ctx := context.Background() <add> <add> _, err := service.Create(ctx, "test", volume.DefaultDriverName) <add> assert.Assert(t, err) <add> _, err = service.Create(ctx, "test2", "other") <add> assert.Assert(t, err) <add> <add> pr, err := service.Prune(ctx, filters.NewArgs(filters.Arg("label", "banana"))) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(pr.VolumesDeleted, 0)) <add> <add> pr, err = service.Prune(ctx, filters.NewArgs()) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) <add> assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test")) <add> <add> _, err = service.Get(ctx, "test") <add> assert.Assert(t, IsNotExist(err), err) <add> <add> v, err := service.Get(ctx, "test2") <add> assert.Assert(t, err) <add> assert.Assert(t, is.Equal(v.Driver, "other")) <add> <add> _, err = service.Create(ctx, "test", volume.DefaultDriverName) <add> assert.Assert(t, err) <add> <add> pr, err = service.Prune(ctx, filters.NewArgs(filters.Arg("label!", "banana"))) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) <add> assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test")) <add> v, err = service.Get(ctx, "test2") <add> assert.Assert(t, err) <add> assert.Assert(t, is.Equal(v.Driver, "other")) <add> <add> _, err = service.Create(ctx, "test", volume.DefaultDriverName, opts.WithCreateLabels(map[string]string{"banana": ""})) <add> assert.Assert(t, err) <add> pr, err = service.Prune(ctx, filters.NewArgs(filters.Arg("label!", "banana"))) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(pr.VolumesDeleted, 0)) <add> <add> _, err = service.Create(ctx, "test3", volume.DefaultDriverName, opts.WithCreateLabels(map[string]string{"banana": "split"})) <add> assert.Assert(t, err) <add> pr, err = service.Prune(ctx, filters.NewArgs(filters.Arg("label!", "banana=split"))) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) <add> assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test")) <add> <add> pr, err = service.Prune(ctx, filters.NewArgs(filters.Arg("label", "banana=split"))) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) <add> assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test3")) <add> <add> v, err = service.Create(ctx, "test", volume.DefaultDriverName, opts.WithCreateReference(t.Name())) <add> assert.Assert(t, err) <add> <add> pr, err = service.Prune(ctx, filters.NewArgs()) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(pr.VolumesDeleted, 0)) <add> assert.Assert(t, service.Release(ctx, v.Name, t.Name())) <add> <add> pr, err = service.Prune(ctx, filters.NewArgs()) <add> assert.Assert(t, err) <add> assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) <add> assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test")) <add>} <add> <add>func newTestService(t *testing.T, ds *volumedrivers.Store) (*VolumesService, func()) { <add> t.Helper() <add> <add> dir, err := ioutil.TempDir("", t.Name()) <add> assert.Assert(t, err) <add> <add> store, err := NewStore(dir, ds) <add> assert.Assert(t, err) <add> s := &VolumesService{vs: store, eventLogger: dummyEventLogger{}} <add> return s, func() { <add> assert.Check(t, s.Shutdown()) <add> assert.Check(t, os.RemoveAll(dir)) <add> } <add>} <add> <add>type dummyEventLogger struct{} <add> <add>func (dummyEventLogger) LogVolumeEvent(_, _ string, _ map[string]string) {} <add><path>volume/service/store.go <del><path>volume/store/store.go <del>package store // import "github.com/docker/docker/volume/store" <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> import ( <add> "context" <add> "fmt" <ide> "net" <ide> "os" <ide> "path/filepath" <ide> import ( <ide> "github.com/pkg/errors" <ide> <ide> "github.com/boltdb/bolt" <add> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/pkg/locker" <ide> "github.com/docker/docker/volume" <ide> "github.com/docker/docker/volume/drivers" <ide> volumemounts "github.com/docker/docker/volume/mounts" <add> "github.com/docker/docker/volume/service/opts" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> func (v volumeWrapper) CachedPath() string { <ide> return v.Volume.Path() <ide> } <ide> <del>// New initializes a VolumeStore to keep <del>// reference counting of volumes in the system. <del>func New(rootPath string, drivers *drivers.Store) (*VolumeStore, error) { <add>// NewStore creates a new volume store at the given path <add>func NewStore(rootPath string, drivers *drivers.Store) (*VolumeStore, error) { <ide> vs := &VolumeStore{ <ide> locks: &locker.Locker{}, <ide> names: make(map[string]volume.Volume), <ide> func New(rootPath string, drivers *drivers.Store) (*VolumeStore, error) { <ide> return nil, err <ide> } <ide> <del> dbPath := filepath.Join(volPath, "metadata.db") <del> <ide> var err error <del> vs.db, err = bolt.Open(dbPath, 0600, &bolt.Options{Timeout: 1 * time.Second}) <add> vs.db, err = bolt.Open(filepath.Join(volPath, "metadata.db"), 0600, &bolt.Options{Timeout: 1 * time.Second}) <ide> if err != nil { <ide> return nil, errors.Wrap(err, "error while opening volume store metadata database") <ide> } <ide> func (s *VolumeStore) getRefs(name string) []string { <ide> return refs <ide> } <ide> <del>// Purge allows the cleanup of internal data on docker in case <add>// purge allows the cleanup of internal data on docker in case <ide> // the internal data is out of sync with volumes driver plugins. <del>func (s *VolumeStore) Purge(name string) { <add>func (s *VolumeStore) purge(ctx context.Context, name string) error { <ide> s.globalLock.Lock() <add> defer s.globalLock.Unlock() <add> <add> select { <add> case <-ctx.Done(): <add> return ctx.Err() <add> default: <add> } <add> <ide> v, exists := s.names[name] <ide> if exists { <ide> driverName := v.DriverName() <ide> func (s *VolumeStore) Purge(name string) { <ide> delete(s.refs, name) <ide> delete(s.labels, name) <ide> delete(s.options, name) <del> s.globalLock.Unlock() <add> return nil <ide> } <ide> <ide> // VolumeStore is a struct that stores the list of volumes available and keeps track of their usage counts <ide> type VolumeStore struct { <ide> db *bolt.DB <ide> } <ide> <del>// List proxies to all registered volume drivers to get the full list of volumes <add>func filterByDriver(names []string) filterFunc { <add> return func(v volume.Volume) bool { <add> for _, name := range names { <add> if name == v.DriverName() { <add> return true <add> } <add> } <add> return false <add> } <add>} <add> <add>func (s *VolumeStore) byReferenced(referenced bool) filterFunc { <add> return func(v volume.Volume) bool { <add> return s.hasRef(v.Name()) == referenced <add> } <add>} <add> <add>func (s *VolumeStore) filter(ctx context.Context, vols *[]volume.Volume, by By) (warnings []string, err error) { <add> // note that this specifically does not support the `FromList` By type. <add> switch f := by.(type) { <add> case nil: <add> if *vols == nil { <add> var ls []volume.Volume <add> ls, warnings, err = s.list(ctx) <add> if err != nil { <add> return warnings, err <add> } <add> *vols = ls <add> } <add> case byDriver: <add> if *vols != nil { <add> filter(vols, filterByDriver([]string(f))) <add> return nil, nil <add> } <add> var ls []volume.Volume <add> ls, warnings, err = s.list(ctx, []string(f)...) <add> if err != nil { <add> return nil, err <add> } <add> *vols = ls <add> case ByReferenced: <add> // TODO(@cpuguy83): It would be nice to optimize this by looking at the list <add> // of referenced volumes, however the locking strategy makes this difficult <add> // without either providing inconsistent data or deadlocks. <add> if *vols == nil { <add> var ls []volume.Volume <add> ls, warnings, err = s.list(ctx) <add> if err != nil { <add> return nil, err <add> } <add> *vols = ls <add> } <add> filter(vols, s.byReferenced(bool(f))) <add> case andCombinator: <add> for _, by := range f { <add> w, err := s.filter(ctx, vols, by) <add> if err != nil { <add> return warnings, err <add> } <add> warnings = append(warnings, w...) <add> } <add> case orCombinator: <add> for _, by := range f { <add> switch by.(type) { <add> case byDriver: <add> var ls []volume.Volume <add> w, err := s.filter(ctx, &ls, by) <add> if err != nil { <add> return warnings, err <add> } <add> warnings = append(warnings, w...) <add> default: <add> ls, w, err := s.list(ctx) <add> if err != nil { <add> return warnings, err <add> } <add> warnings = append(warnings, w...) <add> w, err = s.filter(ctx, &ls, by) <add> if err != nil { <add> return warnings, err <add> } <add> warnings = append(warnings, w...) <add> *vols = append(*vols, ls...) <add> } <add> } <add> unique(vols) <add> case CustomFilter: <add> if *vols == nil { <add> var ls []volume.Volume <add> ls, warnings, err = s.list(ctx) <add> if err != nil { <add> return nil, err <add> } <add> *vols = ls <add> } <add> filter(vols, filterFunc(f)) <add> default: <add> return nil, errdefs.InvalidParameter(errors.Errorf("unsupported filter: %T", f)) <add> } <add> return warnings, nil <add>} <add> <add>func unique(ls *[]volume.Volume) { <add> names := make(map[string]bool, len(*ls)) <add> filter(ls, func(v volume.Volume) bool { <add> if names[v.Name()] { <add> return false <add> } <add> names[v.Name()] = true <add> return true <add> }) <add>} <add> <add>// Find lists volumes filtered by the past in filter. <ide> // If a driver returns a volume that has name which conflicts with another volume from a different driver, <ide> // the first volume is chosen and the conflicting volume is dropped. <del>func (s *VolumeStore) List() ([]volume.Volume, []string, error) { <del> vols, warnings, err := s.list() <add>func (s *VolumeStore) Find(ctx context.Context, by By) (vols []volume.Volume, warnings []string, err error) { <add> logrus.WithField("ByType", fmt.Sprintf("%T", by)).WithField("ByValue", fmt.Sprintf("%+v", by)).Debug("VolumeStore.Find") <add> switch f := by.(type) { <add> case nil, orCombinator, andCombinator, byDriver, ByReferenced, CustomFilter: <add> warnings, err = s.filter(ctx, &vols, by) <add> case fromList: <add> warnings, err = s.filter(ctx, f.ls, f.by) <add> default: <add> // Really shouldn't be possible, but makes sure that any new By's are added to this check. <add> err = errdefs.InvalidParameter(errors.Errorf("unsupported filter type: %T", f)) <add> } <ide> if err != nil { <ide> return nil, nil, &OpErr{Err: err, Op: "list"} <ide> } <add> <ide> var out []volume.Volume <ide> <ide> for _, v := range vols { <ide> func (s *VolumeStore) List() ([]volume.Volume, []string, error) { <ide> return out, warnings, nil <ide> } <ide> <add>type filterFunc func(volume.Volume) bool <add> <add>func filter(vols *[]volume.Volume, fn filterFunc) { <add> var evict []int <add> for i, v := range *vols { <add> if !fn(v) { <add> evict = append(evict, i) <add> } <add> } <add> <add> for n, i := range evict { <add> copy((*vols)[i-n:], (*vols)[i-n+1:]) <add> (*vols)[len(*vols)-1] = nil <add> *vols = (*vols)[:len(*vols)-1] <add> } <add>} <add> <ide> // list goes through each volume driver and asks for its list of volumes. <del>func (s *VolumeStore) list() ([]volume.Volume, []string, error) { <add>// TODO(@cpuguy83): plumb context through <add>func (s *VolumeStore) list(ctx context.Context, driverNames ...string) ([]volume.Volume, []string, error) { <ide> var ( <del> ls []volume.Volume <add> ls = []volume.Volume{} // do not return a nil value as this affects filtering <ide> warnings []string <ide> ) <ide> <del> drivers, err := s.drivers.GetAllDrivers() <add> var dls []volume.Driver <add> <add> all, err := s.drivers.GetAllDrivers() <ide> if err != nil { <ide> return nil, nil, err <ide> } <add> if len(driverNames) == 0 { <add> dls = all <add> } else { <add> idx := make(map[string]bool, len(driverNames)) <add> for _, name := range driverNames { <add> idx[name] = true <add> } <add> for _, d := range all { <add> if idx[d.Name()] { <add> dls = append(dls, d) <add> } <add> } <add> } <ide> <ide> type vols struct { <ide> vols []volume.Volume <ide> err error <ide> driverName string <ide> } <del> chVols := make(chan vols, len(drivers)) <add> chVols := make(chan vols, len(dls)) <ide> <del> for _, vd := range drivers { <add> for _, vd := range dls { <ide> go func(d volume.Driver) { <ide> vs, err := d.List() <ide> if err != nil { <ide> func (s *VolumeStore) list() ([]volume.Volume, []string, error) { <ide> } <ide> <ide> badDrivers := make(map[string]struct{}) <del> for i := 0; i < len(drivers); i++ { <add> for i := 0; i < len(dls); i++ { <ide> vs := <-chVols <ide> <ide> if vs.err != nil { <ide> warnings = append(warnings, vs.err.Error()) <ide> badDrivers[vs.driverName] = struct{}{} <del> logrus.Warn(vs.err) <ide> } <ide> ls = append(ls, vs.vols...) <ide> } <ide> func (s *VolumeStore) list() ([]volume.Volume, []string, error) { <ide> return ls, warnings, nil <ide> } <ide> <del>// CreateWithRef creates a volume with the given name and driver and stores the ref <del>// This ensures there's no race between creating a volume and then storing a reference. <del>func (s *VolumeStore) CreateWithRef(name, driverName, ref string, opts, labels map[string]string) (volume.Volume, error) { <add>// Create creates a volume with the given name and driver <add>// If the volume needs to be created with a reference to prevent race conditions <add>// with volume cleanup, make sure to use the `CreateWithReference` option. <add>func (s *VolumeStore) Create(ctx context.Context, name, driverName string, createOpts ...opts.CreateOption) (volume.Volume, error) { <add> var cfg opts.CreateConfig <add> for _, o := range createOpts { <add> o(&cfg) <add> } <add> <ide> name = normalizeVolumeName(name) <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <ide> <del> v, err := s.create(name, driverName, opts, labels) <add> select { <add> case <-ctx.Done(): <add> return nil, ctx.Err() <add> default: <add> } <add> <add> v, err := s.create(ctx, name, driverName, cfg.Options, cfg.Labels) <ide> if err != nil { <ide> if _, ok := err.(*OpErr); ok { <ide> return nil, err <ide> } <ide> return nil, &OpErr{Err: err, Name: name, Op: "create"} <ide> } <ide> <del> s.setNamed(v, ref) <add> s.setNamed(v, cfg.Reference) <ide> return v, nil <ide> } <ide> <del>// Create creates a volume with the given name and driver. <del>// This is just like CreateWithRef() except we don't store a reference while holding the lock. <del>func (s *VolumeStore) Create(name, driverName string, opts, labels map[string]string) (volume.Volume, error) { <del> return s.CreateWithRef(name, driverName, "", opts, labels) <del>} <del> <ide> // checkConflict checks the local cache for name collisions with the passed in name, <ide> // for existing volumes with the same name but in a different driver. <ide> // This is used by `Create` as a best effort to prevent name collisions for volumes. <ide> func (s *VolumeStore) Create(name, driverName string, opts, labels map[string]st <ide> // TODO(cpuguy83): With v2 plugins this shouldn't be a problem. Could also potentially <ide> // use a connect timeout for this kind of check to ensure we aren't blocking for a <ide> // long time. <del>func (s *VolumeStore) checkConflict(name, driverName string) (volume.Volume, error) { <add>func (s *VolumeStore) checkConflict(ctx context.Context, name, driverName string) (volume.Volume, error) { <ide> // check the local cache <ide> v, _ := s.getNamed(name) <ide> if v == nil { <ide> func (s *VolumeStore) checkConflict(name, driverName string) (volume.Volume, err <ide> <ide> // let's check if the found volume ref <ide> // is stale by checking with the driver if it still exists <del> exists, err := volumeExists(s.drivers, v) <add> exists, err := volumeExists(ctx, s.drivers, v) <ide> if err != nil { <ide> return nil, errors.Wrapf(errNameConflict, "found reference to volume '%s' in driver '%s', but got an error while checking the driver: %v", name, vDriverName, err) <ide> } <ide> func (s *VolumeStore) checkConflict(name, driverName string) (volume.Volume, err <ide> } <ide> <ide> // doesn't exist, so purge it from the cache <del> s.Purge(name) <add> s.purge(ctx, name) <ide> return nil, nil <ide> } <ide> <ide> // volumeExists returns if the volume is still present in the driver. <ide> // An error is returned if there was an issue communicating with the driver. <del>func volumeExists(store *drivers.Store, v volume.Volume) (bool, error) { <del> exists, err := lookupVolume(store, v.DriverName(), v.Name()) <add>func volumeExists(ctx context.Context, store *drivers.Store, v volume.Volume) (bool, error) { <add> exists, err := lookupVolume(ctx, store, v.DriverName(), v.Name()) <ide> if err != nil { <ide> return false, err <ide> } <ide> func volumeExists(store *drivers.Store, v volume.Volume) (bool, error) { <ide> // for the given volume name, an error is returned after checking if the reference is stale. <ide> // If the reference is stale, it will be purged and this create can continue. <ide> // It is expected that callers of this function hold any necessary locks. <del>func (s *VolumeStore) create(name, driverName string, opts, labels map[string]string) (volume.Volume, error) { <add>func (s *VolumeStore) create(ctx context.Context, name, driverName string, opts, labels map[string]string) (volume.Volume, error) { <ide> // Validate the name in a platform-specific manner <ide> <ide> // volume name validation is specific to the host os and not on container image <ide> func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st <ide> return nil, err <ide> } <ide> <del> v, err := s.checkConflict(name, driverName) <add> v, err := s.checkConflict(ctx, name, driverName) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st <ide> <ide> // Since there isn't a specified driver name, let's see if any of the existing drivers have this volume name <ide> if driverName == "" { <del> v, _ = s.getVolume(name) <add> v, _ = s.getVolume(ctx, name, "") <ide> if v != nil { <ide> return v, nil <ide> } <ide> func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st <ide> return volumeWrapper{v, labels, vd.Scope(), opts}, nil <ide> } <ide> <del>// GetWithRef gets a volume with the given name from the passed in driver and stores the ref <del>// This is just like Get(), but we store the reference while holding the lock. <del>// This makes sure there are no races between checking for the existence of a volume and adding a reference for it <del>func (s *VolumeStore) GetWithRef(name, driverName, ref string) (volume.Volume, error) { <del> name = normalizeVolumeName(name) <del> s.locks.Lock(name) <del> defer s.locks.Unlock(name) <del> <del> if driverName == "" { <del> driverName = volume.DefaultDriverName <del> } <del> vd, err := s.drivers.GetDriver(driverName) <del> if err != nil { <del> return nil, &OpErr{Err: err, Name: name, Op: "get"} <del> } <del> <del> v, err := vd.Get(name) <del> if err != nil { <del> return nil, &OpErr{Err: err, Name: name, Op: "get"} <del> } <del> <del> s.setNamed(v, ref) <del> <del> s.globalLock.RLock() <del> defer s.globalLock.RUnlock() <del> return volumeWrapper{v, s.labels[name], vd.Scope(), s.options[name]}, nil <del>} <del> <ide> // Get looks if a volume with the given name exists and returns it if so <del>func (s *VolumeStore) Get(name string) (volume.Volume, error) { <add>func (s *VolumeStore) Get(ctx context.Context, name string, getOptions ...opts.GetOption) (volume.Volume, error) { <add> var cfg opts.GetConfig <add> for _, o := range getOptions { <add> o(&cfg) <add> } <ide> name = normalizeVolumeName(name) <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <ide> <del> v, err := s.getVolume(name) <add> v, err := s.getVolume(ctx, name, cfg.Driver) <ide> if err != nil { <ide> return nil, &OpErr{Err: err, Name: name, Op: "get"} <ide> } <del> s.setNamed(v, "") <add> if cfg.Driver != "" && v.DriverName() != cfg.Driver { <add> return nil, &OpErr{Name: name, Op: "get", Err: errdefs.Conflict(errors.New("found volume driver does not match passed in driver"))} <add> } <add> s.setNamed(v, cfg.Reference) <ide> return v, nil <ide> } <ide> <ide> // getVolume requests the volume, if the driver info is stored it just accesses that driver, <ide> // if the driver is unknown it probes all drivers until it finds the first volume with that name. <ide> // it is expected that callers of this function hold any necessary locks <del>func (s *VolumeStore) getVolume(name string) (volume.Volume, error) { <add>func (s *VolumeStore) getVolume(ctx context.Context, name, driverName string) (volume.Volume, error) { <ide> var meta volumeMetadata <ide> meta, err := s.getMeta(name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <del> driverName := meta.Driver <add> if driverName != "" { <add> if meta.Driver == "" { <add> meta.Driver = driverName <add> } <add> if driverName != meta.Driver { <add> return nil, errdefs.Conflict(errors.New("provided volume driver does not match stored driver")) <add> } <add> } <add> <add> if driverName == "" { <add> driverName = meta.Driver <add> } <ide> if driverName == "" { <ide> s.globalLock.RLock() <add> select { <add> case <-ctx.Done(): <add> s.globalLock.RUnlock() <add> return nil, ctx.Err() <add> default: <add> } <ide> v, exists := s.names[name] <ide> s.globalLock.RUnlock() <ide> if exists { <ide> func (s *VolumeStore) getVolume(name string) (volume.Volume, error) { <ide> } <ide> <ide> if meta.Driver != "" { <del> vol, err := lookupVolume(s.drivers, meta.Driver, name) <add> vol, err := lookupVolume(ctx, s.drivers, meta.Driver, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> if vol == nil { <del> s.Purge(name) <add> s.purge(ctx, name) <ide> return nil, errNoSuchVolume <ide> } <ide> <ide> func (s *VolumeStore) getVolume(name string) (volume.Volume, error) { <ide> } <ide> <ide> for _, d := range drivers { <add> select { <add> case <-ctx.Done(): <add> return nil, ctx.Err() <add> default: <add> } <ide> v, err := d.Get(name) <ide> if err != nil || v == nil { <ide> continue <ide> func (s *VolumeStore) getVolume(name string) (volume.Volume, error) { <ide> // If the driver returns an error that is not communication related the <ide> // error is logged but not returned. <ide> // If the volume is not found it will return `nil, nil`` <del>func lookupVolume(store *drivers.Store, driverName, volumeName string) (volume.Volume, error) { <add>// TODO(@cpuguy83): plumb through the context to lower level components <add>func lookupVolume(ctx context.Context, store *drivers.Store, driverName, volumeName string) (volume.Volume, error) { <ide> if driverName == "" { <ide> driverName = volume.DefaultDriverName <ide> } <ide> func lookupVolume(store *drivers.Store, driverName, volumeName string) (volume.V <ide> <ide> // At this point, the error could be anything from the driver, such as "no such volume" <ide> // Let's not check an error here, and instead check if the driver returned a volume <del> logrus.WithError(err).WithField("driver", driverName).WithField("volume", volumeName).Warnf("Error while looking up volume") <add> logrus.WithError(err).WithField("driver", driverName).WithField("volume", volumeName).Debug("Error while looking up volume") <ide> } <ide> return v, nil <ide> } <ide> <ide> // Remove removes the requested volume. A volume is not removed if it has any refs <del>func (s *VolumeStore) Remove(v volume.Volume) error { <del> name := normalizeVolumeName(v.Name()) <add>func (s *VolumeStore) Remove(ctx context.Context, v volume.Volume, rmOpts ...opts.RemoveOption) error { <add> var cfg opts.RemoveConfig <add> for _, o := range rmOpts { <add> o(&cfg) <add> } <add> <add> name := v.Name() <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <ide> <add> select { <add> case <-ctx.Done(): <add> return ctx.Err() <add> default: <add> } <add> <ide> if s.hasRef(name) { <del> return &OpErr{Err: errVolumeInUse, Name: v.Name(), Op: "remove", Refs: s.getRefs(name)} <add> return &OpErr{Err: errVolumeInUse, Name: name, Op: "remove", Refs: s.getRefs(name)} <add> } <add> <add> v, err := s.getVolume(ctx, name, v.DriverName()) <add> if err != nil { <add> return err <ide> } <ide> <ide> vd, err := s.drivers.GetDriver(v.DriverName()) <ide> func (s *VolumeStore) Remove(v volume.Volume) error { <ide> <ide> logrus.Debugf("Removing volume reference: driver %s, name %s", v.DriverName(), name) <ide> vol := unwrapVolume(v) <del> if err := vd.Remove(vol); err != nil { <del> return &OpErr{Err: err, Name: name, Op: "remove"} <add> <add> err = vd.Remove(vol) <add> if err != nil { <add> err = &OpErr{Err: err, Name: name, Op: "remove"} <ide> } <ide> <del> s.Purge(name) <del> return nil <add> if err == nil || cfg.PurgeOnError { <add> if e := s.purge(ctx, name); e != nil && err == nil { <add> err = e <add> } <add> } <add> return err <ide> } <ide> <del>// Dereference removes the specified reference to the volume <del>func (s *VolumeStore) Dereference(v volume.Volume, ref string) { <del> name := v.Name() <del> <add>// Release releases the specified reference to the volume <add>func (s *VolumeStore) Release(ctx context.Context, name string, ref string) error { <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <add> select { <add> case <-ctx.Done(): <add> return ctx.Err() <add> default: <add> } <ide> <ide> s.globalLock.Lock() <ide> defer s.globalLock.Unlock() <ide> <add> select { <add> case <-ctx.Done(): <add> return ctx.Err() <add> default: <add> } <add> <ide> if s.refs[name] != nil { <ide> delete(s.refs[name], ref) <ide> } <add> return nil <ide> } <ide> <del>// Refs gets the current list of refs for the given volume <del>func (s *VolumeStore) Refs(v volume.Volume) []string { <del> name := v.Name() <add>// CountReferences gives a count of all references for a given volume. <add>func (s *VolumeStore) CountReferences(v volume.Volume) int { <add> name := normalizeVolumeName(v.Name()) <ide> <ide> s.locks.Lock(name) <ide> defer s.locks.Unlock(name) <add> s.globalLock.Lock() <add> defer s.globalLock.Unlock() <ide> <del> return s.getRefs(name) <del>} <del> <del>// FilterByDriver returns the available volumes filtered by driver name <del>func (s *VolumeStore) FilterByDriver(name string) ([]volume.Volume, error) { <del> vd, err := s.drivers.GetDriver(name) <del> if err != nil { <del> return nil, &OpErr{Err: err, Name: name, Op: "list"} <del> } <del> ls, err := vd.List() <del> if err != nil { <del> return nil, &OpErr{Err: err, Name: name, Op: "list"} <del> } <del> for i, v := range ls { <del> options := map[string]string{} <del> s.globalLock.RLock() <del> for key, value := range s.options[v.Name()] { <del> options[key] = value <del> } <del> ls[i] = volumeWrapper{v, s.labels[v.Name()], vd.Scope(), options} <del> s.globalLock.RUnlock() <del> } <del> return ls, nil <del>} <del> <del>// FilterByUsed returns the available volumes filtered by if they are in use or not. <del>// `used=true` returns only volumes that are being used, while `used=false` returns <del>// only volumes that are not being used. <del>func (s *VolumeStore) FilterByUsed(vols []volume.Volume, used bool) []volume.Volume { <del> return s.filter(vols, func(v volume.Volume) bool { <del> s.locks.Lock(v.Name()) <del> hasRef := s.hasRef(v.Name()) <del> s.locks.Unlock(v.Name()) <del> return used == hasRef <del> }) <del>} <del> <del>// filterFunc defines a function to allow filter volumes in the store <del>type filterFunc func(vol volume.Volume) bool <del> <del>// filter returns the available volumes filtered by a filterFunc function <del>func (s *VolumeStore) filter(vols []volume.Volume, f filterFunc) []volume.Volume { <del> var ls []volume.Volume <del> for _, v := range vols { <del> if f(v) { <del> ls = append(ls, v) <del> } <del> } <del> return ls <add> return len(s.refs[name]) <ide> } <ide> <ide> func unwrapVolume(v volume.Volume) volume.Volume { <ide> func unwrapVolume(v volume.Volume) volume.Volume { <ide> func (s *VolumeStore) Shutdown() error { <ide> return s.db.Close() <ide> } <del> <del>// GetDriverList gets the list of volume drivers from the configured volume driver <del>// store. <del>// TODO(@cpuguy83): This should be factored out into a separate service. <del>func (s *VolumeStore) GetDriverList() []string { <del> return s.drivers.GetDriverList() <del>} <add><path>volume/service/store_test.go <del><path>volume/store/store_test.go <del>package store // import "github.com/docker/docker/volume/store" <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> import ( <add> "context" <ide> "errors" <ide> "fmt" <ide> "io/ioutil" <ide> import ( <ide> <ide> "github.com/docker/docker/volume" <ide> volumedrivers "github.com/docker/docker/volume/drivers" <add> "github.com/docker/docker/volume/service/opts" <ide> volumetestutils "github.com/docker/docker/volume/testutils" <ide> "github.com/google/go-cmp/cmp" <ide> "github.com/gotestyourself/gotestyourself/assert" <ide> func TestCreate(t *testing.T) { <ide> defer cleanup() <ide> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake") <ide> <del> v, err := s.Create("fake1", "fake", nil, nil) <add> ctx := context.Background() <add> v, err := s.Create(ctx, "fake1", "fake") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> if v.Name() != "fake1" { <ide> t.Fatalf("Expected fake1 volume, got %v", v) <ide> } <del> if l, _, _ := s.List(); len(l) != 1 { <add> if l, _, _ := s.Find(ctx, nil); len(l) != 1 { <ide> t.Fatalf("Expected 1 volume in the store, got %v: %v", len(l), l) <ide> } <ide> <del> if _, err := s.Create("none", "none", nil, nil); err == nil { <add> if _, err := s.Create(ctx, "none", "none"); err == nil { <ide> t.Fatalf("Expected unknown driver error, got nil") <ide> } <ide> <del> _, err = s.Create("fakeerror", "fake", map[string]string{"error": "create error"}, nil) <add> _, err = s.Create(ctx, "fakeerror", "fake", opts.WithCreateOptions(map[string]string{"error": "create error"})) <ide> expected := &OpErr{Op: "create", Name: "fakeerror", Err: errors.New("create error")} <ide> if err != nil && err.Error() != expected.Error() { <ide> t.Fatalf("Expected create fakeError: create error, got %v", err) <ide> func TestRemove(t *testing.T) { <ide> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake") <ide> s.drivers.Register(volumetestutils.NewFakeDriver("noop"), "noop") <ide> <add> ctx := context.Background() <add> <ide> // doing string compare here since this error comes directly from the driver <ide> expected := "no such volume" <del> if err := s.Remove(volumetestutils.NoopVolume{}); err == nil || !strings.Contains(err.Error(), expected) { <add> var v volume.Volume = volumetestutils.NoopVolume{} <add> if err := s.Remove(ctx, v); err == nil || !strings.Contains(err.Error(), expected) { <ide> t.Fatalf("Expected error %q, got %v", expected, err) <ide> } <ide> <del> v, err := s.CreateWithRef("fake1", "fake", "fake", nil, nil) <add> v, err := s.Create(ctx, "fake1", "fake", opts.WithCreateReference("fake")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if err := s.Remove(v); !IsInUse(err) { <add> if err := s.Remove(ctx, v); !IsInUse(err) { <ide> t.Fatalf("Expected ErrVolumeInUse error, got %v", err) <ide> } <del> s.Dereference(v, "fake") <del> if err := s.Remove(v); err != nil { <add> s.Release(ctx, v.Name(), "fake") <add> if err := s.Remove(ctx, v); err != nil { <ide> t.Fatal(err) <ide> } <del> if l, _, _ := s.List(); len(l) != 0 { <add> if l, _, _ := s.Find(ctx, nil); len(l) != 0 { <ide> t.Fatalf("Expected 0 volumes in the store, got %v, %v", len(l), l) <ide> } <ide> } <ide> func TestList(t *testing.T) { <ide> drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake") <ide> drivers.Register(volumetestutils.NewFakeDriver("fake2"), "fake2") <ide> <del> s, err := New(dir, drivers) <add> s, err := NewStore(dir, drivers) <ide> assert.NilError(t, err) <ide> <del> if _, err := s.Create("test", "fake", nil, nil); err != nil { <add> ctx := context.Background() <add> if _, err := s.Create(ctx, "test", "fake"); err != nil { <ide> t.Fatal(err) <ide> } <del> if _, err := s.Create("test2", "fake2", nil, nil); err != nil { <add> if _, err := s.Create(ctx, "test2", "fake2"); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> ls, _, err := s.List() <add> ls, _, err := s.Find(ctx, nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestList(t *testing.T) { <ide> } <ide> <ide> // and again with a new store <del> s, err = New(dir, drivers) <add> s, err = NewStore(dir, drivers) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> ls, _, err = s.List() <add> ls, _, err = s.Find(ctx, nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestList(t *testing.T) { <ide> } <ide> } <ide> <del>func TestFilterByDriver(t *testing.T) { <add>func TestFindByDriver(t *testing.T) { <ide> t.Parallel() <ide> s, cleanup := setupTest(t) <ide> defer cleanup() <ide> <del> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake") <del> s.drivers.Register(volumetestutils.NewFakeDriver("noop"), "noop") <add> assert.Assert(t, s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake")) <add> assert.Assert(t, s.drivers.Register(volumetestutils.NewFakeDriver("noop"), "noop")) <ide> <del> if _, err := s.Create("fake1", "fake", nil, nil); err != nil { <del> t.Fatal(err) <del> } <del> if _, err := s.Create("fake2", "fake", nil, nil); err != nil { <del> t.Fatal(err) <del> } <del> if _, err := s.Create("fake3", "noop", nil, nil); err != nil { <del> t.Fatal(err) <del> } <add> ctx := context.Background() <add> _, err := s.Create(ctx, "fake1", "fake") <add> assert.NilError(t, err) <ide> <del> if l, _ := s.FilterByDriver("fake"); len(l) != 2 { <del> t.Fatalf("Expected 2 volumes, got %v, %v", len(l), l) <del> } <add> _, err = s.Create(ctx, "fake2", "fake") <add> assert.NilError(t, err) <ide> <del> if l, _ := s.FilterByDriver("noop"); len(l) != 1 { <del> t.Fatalf("Expected 1 volume, got %v, %v", len(l), l) <del> } <add> _, err = s.Create(ctx, "fake3", "noop") <add> assert.NilError(t, err) <add> <add> l, _, err := s.Find(ctx, ByDriver("fake")) <add> assert.NilError(t, err) <add> assert.Equal(t, len(l), 2) <add> <add> l, _, err = s.Find(ctx, ByDriver("noop")) <add> assert.NilError(t, err) <add> assert.Equal(t, len(l), 1) <add> <add> l, _, err = s.Find(ctx, ByDriver("nosuchdriver")) <add> assert.NilError(t, err) <add> assert.Equal(t, len(l), 0) <ide> } <ide> <del>func TestFilterByUsed(t *testing.T) { <add>func TestFindByReferenced(t *testing.T) { <ide> t.Parallel() <ide> s, cleanup := setupTest(t) <ide> defer cleanup() <ide> <ide> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake") <ide> s.drivers.Register(volumetestutils.NewFakeDriver("noop"), "noop") <ide> <del> if _, err := s.CreateWithRef("fake1", "fake", "volReference", nil, nil); err != nil { <add> ctx := context.Background() <add> if _, err := s.Create(ctx, "fake1", "fake", opts.WithCreateReference("volReference")); err != nil { <ide> t.Fatal(err) <ide> } <del> if _, err := s.Create("fake2", "fake", nil, nil); err != nil { <add> if _, err := s.Create(ctx, "fake2", "fake"); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> vols, _, err := s.List() <del> if err != nil { <del> t.Fatal(err) <del> } <add> dangling, _, err := s.Find(ctx, ByReferenced(false)) <add> assert.Assert(t, err) <add> assert.Assert(t, len(dangling) == 1) <add> assert.Check(t, dangling[0].Name() == "fake2") <ide> <del> dangling := s.FilterByUsed(vols, false) <del> if len(dangling) != 1 { <del> t.Fatalf("expected 1 dangling volume, got %v", len(dangling)) <del> } <del> if dangling[0].Name() != "fake2" { <del> t.Fatalf("expected dangling volume fake2, got %s", dangling[0].Name()) <del> } <del> <del> used := s.FilterByUsed(vols, true) <del> if len(used) != 1 { <del> t.Fatalf("expected 1 used volume, got %v", len(used)) <del> } <del> if used[0].Name() != "fake1" { <del> t.Fatalf("expected used volume fake1, got %s", used[0].Name()) <del> } <add> used, _, err := s.Find(ctx, ByReferenced(true)) <add> assert.Assert(t, err) <add> assert.Assert(t, len(used) == 1) <add> assert.Check(t, used[0].Name() == "fake1") <ide> } <ide> <ide> func TestDerefMultipleOfSameRef(t *testing.T) { <ide> func TestDerefMultipleOfSameRef(t *testing.T) { <ide> defer cleanup() <ide> s.drivers.Register(volumetestutils.NewFakeDriver("fake"), "fake") <ide> <del> v, err := s.CreateWithRef("fake1", "fake", "volReference", nil, nil) <add> ctx := context.Background() <add> v, err := s.Create(ctx, "fake1", "fake", opts.WithCreateReference("volReference")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if _, err := s.GetWithRef("fake1", "fake", "volReference"); err != nil { <add> if _, err := s.Get(ctx, "fake1", opts.WithGetDriver("fake"), opts.WithGetReference("volReference")); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> s.Dereference(v, "volReference") <del> if err := s.Remove(v); err != nil { <add> s.Release(ctx, v.Name(), "volReference") <add> if err := s.Remove(ctx, v); err != nil { <ide> t.Fatal(err) <ide> } <ide> } <ide> func TestCreateKeepOptsLabelsWhenExistsRemotely(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> v, err := s.Create("foo", "fake", nil, map[string]string{"hello": "world"}) <add> ctx := context.Background() <add> v, err := s.Create(ctx, "foo", "fake", opts.WithCreateLabels(map[string]string{"hello": "world"})) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestDefererencePluginOnCreateError(t *testing.T) { <ide> pg := volumetestutils.NewFakePluginGetter(p) <ide> s.drivers = volumedrivers.NewStore(pg) <ide> <add> ctx := context.Background() <ide> // create a good volume so we have a plugin reference <del> _, err = s.Create("fake1", d.Name(), nil, nil) <add> _, err = s.Create(ctx, "fake1", d.Name()) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> // Now create another one expecting an error <del> _, err = s.Create("fake2", d.Name(), map[string]string{"error": "some error"}, nil) <add> _, err = s.Create(ctx, "fake2", d.Name(), opts.WithCreateOptions(map[string]string{"error": "some error"})) <ide> if err == nil || !strings.Contains(err.Error(), "some error") { <ide> t.Fatalf("expected an error on create: %v", err) <ide> } <ide> func TestRefDerefRemove(t *testing.T) { <ide> defer cleanup() <ide> s.drivers.Register(volumetestutils.NewFakeDriver(driverName), driverName) <ide> <del> v, err := s.CreateWithRef("test", driverName, "test-ref", nil, nil) <add> ctx := context.Background() <add> v, err := s.Create(ctx, "test", driverName, opts.WithCreateReference("test-ref")) <ide> assert.NilError(t, err) <ide> <del> err = s.Remove(v) <add> err = s.Remove(ctx, v) <ide> assert.Assert(t, is.ErrorContains(err, "")) <ide> assert.Equal(t, errVolumeInUse, err.(*OpErr).Err) <ide> <del> s.Dereference(v, "test-ref") <del> err = s.Remove(v) <add> s.Release(ctx, v.Name(), "test-ref") <add> err = s.Remove(ctx, v) <ide> assert.NilError(t, err) <ide> } <ide> <ide> func TestGet(t *testing.T) { <ide> defer cleanup() <ide> s.drivers.Register(volumetestutils.NewFakeDriver(driverName), driverName) <ide> <del> _, err := s.Get("not-exist") <add> ctx := context.Background() <add> _, err := s.Get(ctx, "not-exist") <ide> assert.Assert(t, is.ErrorContains(err, "")) <ide> assert.Equal(t, errNoSuchVolume, err.(*OpErr).Err) <ide> <del> v1, err := s.Create("test", driverName, nil, map[string]string{"a": "1"}) <add> v1, err := s.Create(ctx, "test", driverName, opts.WithCreateLabels(map[string]string{"a": "1"})) <ide> assert.NilError(t, err) <ide> <del> v2, err := s.Get("test") <add> v2, err := s.Get(ctx, "test") <ide> assert.NilError(t, err) <ide> assert.DeepEqual(t, v1, v2, cmpVolume) <ide> <ide> dv := v2.(volume.DetailedVolume) <ide> assert.Equal(t, "1", dv.Labels()["a"]) <ide> <del> err = s.Remove(v1) <add> err = s.Remove(ctx, v1) <ide> assert.NilError(t, err) <ide> } <ide> <del>func TestGetWithRef(t *testing.T) { <add>func TestGetWithReference(t *testing.T) { <ide> t.Parallel() <ide> <ide> driverName := "test-get-with-ref" <ide> s, cleanup := setupTest(t) <ide> defer cleanup() <ide> s.drivers.Register(volumetestutils.NewFakeDriver(driverName), driverName) <ide> <del> _, err := s.GetWithRef("not-exist", driverName, "test-ref") <add> ctx := context.Background() <add> _, err := s.Get(ctx, "not-exist", opts.WithGetDriver(driverName), opts.WithGetReference("test-ref")) <ide> assert.Assert(t, is.ErrorContains(err, "")) <ide> <del> v1, err := s.Create("test", driverName, nil, map[string]string{"a": "1"}) <add> v1, err := s.Create(ctx, "test", driverName, opts.WithCreateLabels(map[string]string{"a": "1"})) <ide> assert.NilError(t, err) <ide> <del> v2, err := s.GetWithRef("test", driverName, "test-ref") <add> v2, err := s.Get(ctx, "test", opts.WithGetDriver(driverName), opts.WithGetReference("test-ref")) <ide> assert.NilError(t, err) <ide> assert.DeepEqual(t, v1, v2, cmpVolume) <ide> <del> err = s.Remove(v2) <add> err = s.Remove(ctx, v2) <ide> assert.Assert(t, is.ErrorContains(err, "")) <ide> assert.Equal(t, errVolumeInUse, err.(*OpErr).Err) <ide> <del> s.Dereference(v2, "test-ref") <del> err = s.Remove(v2) <add> s.Release(ctx, v2.Name(), "test-ref") <add> err = s.Remove(ctx, v2) <ide> assert.NilError(t, err) <ide> } <ide> <ide> func setupTest(t *testing.T) (*VolumeStore, func()) { <ide> assert.NilError(t, err) <ide> <ide> cleanup := func() { <add> t.Helper() <ide> err := os.RemoveAll(dir) <ide> assert.Check(t, err) <ide> } <ide> <del> s, err := New(dir, volumedrivers.NewStore(nil)) <add> s, err := NewStore(dir, volumedrivers.NewStore(nil)) <ide> assert.Check(t, err) <ide> return s, func() { <ide> s.Shutdown() <ide> cleanup() <ide> } <ide> } <add> <add>func TestFilterFunc(t *testing.T) { <add> testDriver := volumetestutils.NewFakeDriver("test") <add> testVolume, err := testDriver.Create("test", nil) <add> assert.NilError(t, err) <add> testVolume2, err := testDriver.Create("test2", nil) <add> assert.NilError(t, err) <add> testVolume3, err := testDriver.Create("test3", nil) <add> assert.NilError(t, err) <add> <add> for _, test := range []struct { <add> vols []volume.Volume <add> fn filterFunc <add> desc string <add> expect []volume.Volume <add> }{ <add> {desc: "test nil list", vols: nil, expect: nil, fn: func(volume.Volume) bool { return true }}, <add> {desc: "test empty list", vols: []volume.Volume{}, expect: []volume.Volume{}, fn: func(volume.Volume) bool { return true }}, <add> {desc: "test filter non-empty to empty", vols: []volume.Volume{testVolume}, expect: []volume.Volume{}, fn: func(volume.Volume) bool { return false }}, <add> {desc: "test nothing to fitler non-empty list", vols: []volume.Volume{testVolume}, expect: []volume.Volume{testVolume}, fn: func(volume.Volume) bool { return true }}, <add> {desc: "test filter some", vols: []volume.Volume{testVolume, testVolume2}, expect: []volume.Volume{testVolume}, fn: func(v volume.Volume) bool { return v.Name() == testVolume.Name() }}, <add> {desc: "test filter middle", vols: []volume.Volume{testVolume, testVolume2, testVolume3}, expect: []volume.Volume{testVolume, testVolume3}, fn: func(v volume.Volume) bool { return v.Name() != testVolume2.Name() }}, <add> {desc: "test filter middle and last", vols: []volume.Volume{testVolume, testVolume2, testVolume3}, expect: []volume.Volume{testVolume}, fn: func(v volume.Volume) bool { return v.Name() != testVolume2.Name() && v.Name() != testVolume3.Name() }}, <add> {desc: "test filter first and last", vols: []volume.Volume{testVolume, testVolume2, testVolume3}, expect: []volume.Volume{testVolume2}, fn: func(v volume.Volume) bool { return v.Name() != testVolume.Name() && v.Name() != testVolume3.Name() }}, <add> } { <add> t.Run(test.desc, func(t *testing.T) { <add> test := test <add> t.Parallel() <add> <add> filter(&test.vols, test.fn) <add> assert.DeepEqual(t, test.vols, test.expect, cmpVolume) <add> }) <add> } <add>} <add><path>volume/service/store_unix.go <del><path>volume/store/store_unix.go <del>// +build linux freebsd <add>// +build linux freebsd darwin <ide> <del>package store // import "github.com/docker/docker/volume/store" <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> // normalizeVolumeName is a platform specific function to normalize the name <ide> // of a volume. This is a no-op on Unix-like platforms <add><path>volume/service/store_windows.go <del><path>volume/store/store_windows.go <del>package store // import "github.com/docker/docker/volume/store" <add>package service // import "github.com/docker/docker/volume/service" <ide> <ide> import "strings" <ide> <ide><path>volume/testutils/testutils.go <ide> func (FakeVolume) Mount(_ string) (string, error) { return "fake", nil } <ide> func (FakeVolume) Unmount(_ string) error { return nil } <ide> <ide> // Status provides low-level details about the volume <del>func (FakeVolume) Status() map[string]interface{} { return nil } <add>func (FakeVolume) Status() map[string]interface{} { <add> return map[string]interface{}{"datakey": "datavalue"} <add>} <ide> <ide> // CreatedAt provides the time the volume (directory) was created at <ide> func (FakeVolume) CreatedAt() (time.Time, error) { return time.Now(), nil }
50
Ruby
Ruby
ensure @@homebrew_repository@@ is always relocated
e2d032a6b6c765e0a6311a84a7b70f5ddf12b665
<ide><path>Library/Homebrew/keg_relocate.rb <ide> class Keg <ide> PREFIX_PLACEHOLDER = "" <ide> CELLAR_PLACEHOLDER = "" <add> REPOSITORY_PLACEHOLDER = "" <ide> LIBRARY_PLACEHOLDER = "" <ide> <del> # TODO: delete these after Homebrew 2.7.0 is released. <del> REPOSITORY_PLACEHOLDER = "" <add> # TODO: delete this after Homebrew 2.7.0 is released. <ide> REPOSITORY_LIBRARY_PLACEHOLDER = "#{REPOSITORY_PLACEHOLDER}/Library" <ide> <del> Relocation = Struct.new(:old_prefix, :old_cellar, :old_library, <del> :new_prefix, :new_cellar, :new_library, <add> Relocation = Struct.new(:old_prefix, :old_cellar, :old_repository, :old_library, <add> :new_prefix, :new_cellar, :new_repository, :new_library, <ide> # TODO: delete these after Homebrew 2.7.0 is released. <del> :old_repository, :new_repository, <ide> :old_repository_library, :new_repository_library) do <ide> # Use keyword args instead of positional args for initialization. <ide> def initialize(**kwargs) <ide> def replace_placeholders_with_locations(files, skip_linkage: false) <ide> relocation = Relocation.new( <ide> old_prefix: PREFIX_PLACEHOLDER, <ide> old_cellar: CELLAR_PLACEHOLDER, <add> old_repository: REPOSITORY_PLACEHOLDER, <ide> old_library: LIBRARY_PLACEHOLDER, <ide> new_prefix: HOMEBREW_PREFIX.to_s, <ide> new_cellar: HOMEBREW_CELLAR.to_s, <add> new_repository: HOMEBREW_REPOSITORY.to_s, <ide> new_library: HOMEBREW_LIBRARY.to_s, <ide> # TODO: delete these after Homebrew 2.7.0 is released. <del> old_repository: REPOSITORY_PLACEHOLDER, <del> new_repository: HOMEBREW_REPOSITORY.to_s, <ide> old_repository_library: REPOSITORY_LIBRARY_PLACEHOLDER, <ide> new_repository_library: HOMEBREW_LIBRARY.to_s, <ide> ) <ide> def replace_text_in_files(relocation, files: nil) <ide> }.compact <ide> # when HOMEBREW_PREFIX == HOMEBREW_REPOSITORY we should use HOMEBREW_PREFIX for all relocations to avoid <ide> # being unable to differentiate between them. <del> # TODO: delete this after Homebrew 2.7.0 is released. <ide> replacements[relocation.old_repository] = relocation.new_repository if HOMEBREW_PREFIX != HOMEBREW_REPOSITORY <ide> changed = s.gsub!(Regexp.union(replacements.keys.sort_by(&:length).reverse), replacements) <ide> next unless changed
1
Ruby
Ruby
add missing require
ceba010ea254e987eb266e31c55f45fe51b80713
<ide><path>activesupport/lib/active_support/notifications/instrumenter.rb <add>require 'securerandom' <add> <ide> module ActiveSupport <ide> module Notifications <ide> # Instrumentors are stored in a thread local.
1
PHP
PHP
add new test file
ac78ad07c2a18a18ec7ce93d56824a55d56768bc
<ide><path>build/test/data/text.php <add>Lorem ipsum dolor sit amet <add>consectetuer adipiscing elit <add>Sed lorem leo <add>lorem leo consectetuer adipiscing elit <add>Sed lorem leo <add>rhoncus sit amet <add>elementum at <add>bibendum at, eros <add>Cras at mi et tortor egestas vestibulum <add>sed Cras at mi vestibulum <add>Phasellus sed felis sit amet <add>orci dapibus semper.
1
PHP
PHP
add messege test to allowempty when set as array
d9f362e7ff5da39812a84373b7375084675411be
<ide><path>src/Validation/Validator.php <ide> public function remove($field, $rule = null) <ide> */ <ide> public function requirePresence($field, $mode = true, $message = null) <ide> { <add> $settingsDefault = [ <add> 'mode' => $mode, <add> 'message' => $message <add> ]; <add> <ide> if (!is_array($field)) { <del> $field = $this->_convertValidatorToArray($field, ['mode', 'message'], [$mode, $message]); <add> $field = $this->_convertValidatorToArray($field, $settingsDefault); <ide> } <ide> <ide> foreach ($field as $fieldName => $setting) { <del> $settings = $this->_convertValidatorToArray($fieldName, ['mode', 'message'], [$mode, $message], $setting); <add> $settings = $this->_convertValidatorToArray($fieldName, $settingsDefault, $setting); <ide> $fieldName = current(array_keys($settings)); <ide> <ide> $this->field($fieldName)->isPresenceRequired($settings[$fieldName]['mode']); <ide> public function requirePresence($field, $mode = true, $message = null) <ide> */ <ide> public function allowEmpty($field, $when = true, $message = null) <ide> { <add> $settingsDefault = [ <add> 'when' => $when, <add> 'message' => $message <add> ]; <add> <ide> if (!is_array($field)) { <del> $field = $this->_convertValidatorToArray($field, ['when', 'message'], [$when, $message]); <add> $field = $this->_convertValidatorToArray($field, $settingsDefault); <ide> } <ide> <ide> foreach ($field as $fieldName => $setting) { <del> $settings = $this->_convertValidatorToArray($fieldName, ['when', 'message'], [$when, $message], $setting); <add> $settings = $this->_convertValidatorToArray($fieldName, $settingsDefault, $setting); <ide> $fieldName = current(array_keys($settings)); <ide> <ide> $this->field($fieldName)->isEmptyAllowed($settings[$fieldName]['when']); <ide> public function allowEmpty($field, $when = true, $message = null) <ide> * Converts validator to fieldName => $settings array <ide> * <ide> * @param int|string $fieldName name of field <del> * @param array $settingKeys keys that will be used to create default settings <del> * @param array $settingsValues values that will be used to create default settings <add> * @param array $settingDefaults default settings <ide> * @param string|array $settings settings from data <ide> * @return array <ide> */ <del> protected function _convertValidatorToArray($fieldName, $settingKeys = [], $settingsValues = [], $settings = []) <add> protected function _convertValidatorToArray($fieldName, $settingDefaults = [], $settings = []) <ide> { <ide> if (is_string($settings)) { <ide> $fieldName = $settings; <ide> protected function _convertValidatorToArray($fieldName, $settingKeys = [], $sett <ide> sprintf('Invalid field "%s" setting, must be an array.', $fieldName) <ide> ); <ide> } <del> $settings += array_combine($settingKeys, $settingsValues); <add> $settings += $settingDefaults; <ide> return [$fieldName => $settings]; <ide> } <ide> <ide> protected function _convertValidatorToArray($fieldName, $settingKeys = [], $sett <ide> */ <ide> public function notEmpty($field, $message = null, $when = false) <ide> { <add> $settingsDefault = [ <add> 'when' => $when, <add> 'message' => $message <add> ]; <add> <ide> if (!is_array($field)) { <del> $field = $this->_convertValidatorToArray( <del> $field, <del> ['when', 'message'], <del> [$when, $message] <del> ); <add> $field = $this->_convertValidatorToArray($field, $settingsDefault); <ide> } <ide> <ide> foreach ($field as $fieldName => $setting) { <del> $settings = $this->_convertValidatorToArray( <del> $fieldName, <del> ['when', 'message'], <del> [$when, $message], <del> $setting <del> ); <add> $settings = $this->_convertValidatorToArray($fieldName, $settingsDefault, $setting); <ide> $fieldName = current(array_keys($settings)); <ide> $whenSetting = $settings[$fieldName]['when']; <ide> <ide><path>tests/TestCase/Validation/ValidatorTest.php <ide> public function testAllowEmptyAsArray() <ide> 'title', <ide> 'subject', <ide> 'posted_at' => [ <del> 'when' => false <add> 'when' => false, <add> 'message' => 'Post time cannot be empty' <ide> ], <ide> 'updated_at' => [ <ide> 'when' => true <ide> ], <ide> 'show_at' => [ <ide> 'when' => 'update' <ide> ] <del> ], 'create'); <add> ], 'create', 'Cannot be empty'); <ide> $this->assertEquals('create', $validator->field('title')->isEmptyAllowed()); <ide> $this->assertEquals('create', $validator->field('subject')->isEmptyAllowed()); <ide> $this->assertFalse($validator->field('posted_at')->isEmptyAllowed()); <ide> $this->assertTrue($validator->field('updated_at')->isEmptyAllowed()); <ide> $this->assertEquals('update', $validator->field('show_at')->isEmptyAllowed()); <add> <add> $errors = $validator->errors([ <add> 'title' => '', <add> 'subject' => null, <add> 'posted_at' => null, <add> 'updated_at' => null, <add> 'show_at' => '' <add> ], false); <add> <add> $expected = [ <add> 'title' => ['_empty' => 'Cannot be empty'], <add> 'subject' => ['_empty' => 'Cannot be empty'], <add> 'posted_at' => ['_empty' => 'Post time cannot be empty'] <add> ]; <add> $this->assertEquals($expected, $errors); <ide> } <ide> <ide> /**
2
Javascript
Javascript
stringify jsonpscripttype option
21b5a026baa846679cab96f55d9d7ebfb7e34174
<ide><path>lib/JsonpMainTemplatePlugin.js <ide> class JsonpMainTemplatePlugin { <ide> }); <ide> return this.asString([ <ide> "var script = document.createElement('script');", <del> `script.type = '${jsonpScriptType}';`, <add> `script.type = ${JSON.stringify(jsonpScriptType)};`, <ide> "script.charset = 'utf-8';", <ide> "script.async = true;", <ide> `script.timeout = ${chunkLoadTimeout};`,
1
PHP
PHP
add tests for url generated with named route
0ae87e3d3f9aeaeed629fb58f9d108dd9032d193
<ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testUrlGenerationNamedRoute() { <ide> array('controller' => 'users', 'action' => 'view'), <ide> array('_name' => 'test') <ide> ); <add> Router::connect( <add> '/view/*', <add> ['action' => 'view'], <add> ['_name' => 'Articles::view'] <add> ); <add> <ide> $url = Router::url('test', array('name' => 'mark')); <ide> $this->assertEquals('/users/mark', $url); <ide> <ide> public function testUrlGenerationNamedRoute() { <ide> <ide> $url = Router::url('users-index'); <ide> $this->assertEquals('/users', $url); <add> <add> $url = Router::url('Articles::view'); <add> $this->assertEquals('/view/', $url); <add> <add> $url = Router::url('Articles::view', ['1']); <add> $this->assertEquals('/view/1', $url); <ide> } <ide> <ide> /**
1
Ruby
Ruby
consolidate sudo checks
4c9ac19e878750cf2c2832759d9902796079d9f0
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install <ide> end <ide> end unless ARGV.force? <ide> <del> if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero? <del> raise "Cowardly refusing to `sudo brew install'\n#{SUDO_BAD_ERRMSG}" <del> end <del> <ide> install_formulae ARGV.formulae <ide> end <ide> <ide><path>Library/Homebrew/cmd/link.rb <ide> module Homebrew extend self <ide> def link <ide> raise KegUnspecifiedError if ARGV.named.empty? <ide> <del> if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero? <del> raise "Cowardly refusing to `sudo brew link'\n#{SUDO_BAD_ERRMSG}" <del> end <del> <ide> mode = OpenStruct.new <ide> <ide> mode.overwrite = true if ARGV.include? '--overwrite' <ide><path>Library/Homebrew/cmd/pin.rb <ide> <ide> module Homebrew extend self <ide> def pin <del> if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero? <del> abort "Cowardly refusing to `sudo pin'" <del> end <ide> raise FormulaUnspecifiedError if ARGV.named.empty? <ide> <ide> ARGV.formulae.each do |f| <ide><path>Library/Homebrew/cmd/unpin.rb <ide> <ide> module Homebrew extend self <ide> def unpin <del> if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero? <del> abort "Cowardly refusing to `sudo unpin'" <del> end <ide> raise FormulaUnspecifiedError if ARGV.named.empty? <ide> <ide> ARGV.formulae.each do |f| <ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def plural_s <ide> <ide> module Homebrew extend self <ide> def upgrade <del> if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero? <del> # note we only abort if Homebrew is *not* installed as sudo and the user <del> # calls brew as root. The fix is to chown brew to root. <del> abort "Cowardly refusing to `sudo brew upgrade'" <del> end <del> <ide> Homebrew.perform_preinstall_checks <ide> <ide> if ARGV.named.empty? <ide><path>Library/Homebrew/exceptions.rb <ide> def to_s <ide> super + advice.to_s <ide> end <ide> end <del> <del>module Homebrew extend self <del> SUDO_BAD_ERRMSG = <<-EOS.undent <del> You can use brew with sudo, but only if the brew executable is owned by root. <del> However, this is both not recommended and completely unsupported so do so at <del> your own risk. <del> EOS <del>end <ide><path>Library/Homebrew/global.rb <ide> module Homebrew extend self <ide> require 'compat' unless ARGV.include? "--no-compat" or ENV['HOMEBREW_NO_COMPAT'] <ide> <ide> ORIGINAL_PATHS = ENV['PATH'].split(':').map{ |p| Pathname.new(p).expand_path rescue nil }.compact.freeze <add> <add>SUDO_BAD_ERRMSG = <<-EOS.undent <add> You can use brew with sudo, but only if the brew executable is owned by root. <add> However, this is both not recommended and completely unsupported so do so at <add> your own risk. <add>EOS <ide><path>Library/brew.rb <ide> def require? path <ide> begin <ide> trap("INT", std_trap) # restore default CTRL-C handler <ide> <del> aliases = {'ls' => :list, <del> 'homepage' => :home, <del> '-S' => :search, <del> 'up' => :update, <del> 'ln' => :link, <del> 'instal' => :install, # gem does the same <del> 'rm' => :uninstall, <del> 'remove' => :uninstall, <del> 'configure' => :diy, <del> 'abv' => :info, <del> 'dr' => :doctor, <add> aliases = {'ls' => 'list', <add> 'homepage' => 'home', <add> '-S' => 'search', <add> 'up' => 'update', <add> 'ln' => 'link', <add> 'instal' => 'install', # gem does the same <add> 'rm' => 'uninstall', <add> 'remove' => 'uninstall', <add> 'configure' => 'diy', <add> 'abv' => 'info', <add> 'dr' => 'doctor', <ide> '--repo' => '--repository', <ide> 'environment' => '--env' # same as gem <ide> } <ide> <ide> cmd = ARGV.shift <ide> cmd = aliases[cmd] if aliases[cmd] <ide> <del> if cmd == '-c1' <add> if cmd == '-c1' # Shortcut for one line of configuration <ide> cmd = '--config' <ide> ARGV.unshift('-1') <ide> end <ide> <add> sudo_check = Set.new %w[ install link pin unpin upgrade ] <add> <add> if sudo_check.include? cmd <add> if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero? <add> raise "Cowardly refusing to `sudo brew #{cmd}`\n#{SUDO_BAD_ERRMSG}" <add> end <add> end <add> <ide> # Add example external commands to PATH before checking. <ide> ENV['PATH'] += ":#{HOMEBREW_REPOSITORY}/Library/Contributions/cmd" <ide> if require? HOMEBREW_REPOSITORY/"Library/Homebrew/cmd"/cmd
8
Ruby
Ruby
add missing require to active_support/callbacks.rb
3b3a43eb097a1aac197193fc68269af489504b89
<ide><path>activesupport/lib/active_support/callbacks.rb <ide> require "active_support/core_ext/array/extract_options" <ide> require "active_support/core_ext/class/attribute" <ide> require "active_support/core_ext/string/filters" <add>require "active_support/core_ext/object/blank" <ide> require "thread" <ide> <ide> module ActiveSupport
1
Text
Text
remove reverted commits from 1.2.4
78ba429e6a3269594afbffcca2980e76281c43e0
<ide><path>CHANGELOG.md <ide> - **$parse:** micro-optimization for ensureSafeObject function <ide> ([689dfb16](https://github.com/angular/angular.js/commit/689dfb167924a61aef444ce7587fb987d8080990), <ide> [#5246](https://github.com/angular/angular.js/issues/5246)) <del>- **$resource:** Use shallow copy instead of angular.copy <del> ([a55c1e79](https://github.com/angular/angular.js/commit/a55c1e79cf8894c2d348d4cf911b28dcc8a6995e), <del> [#5300](https://github.com/angular/angular.js/issues/5300)) <del>- **Angular.js:** Use call and === instead of apply and == in type check functions <del> ([785a5fd7](https://github.com/angular/angular.js/commit/785a5fd7c182f39f4ae80d603c0098bc63ce41a4), <del> [#5295](https://github.com/angular/angular.js/issues/5295)) <ide> - **Scope:** short-circuit after dirty-checking last dirty watcher <ide> ([d070450c](https://github.com/angular/angular.js/commit/d070450cd2b3b3a3aa34b69d3fa1f4cc3be025dd), <ide> [#5272](https://github.com/angular/angular.js/issues/5272), [#5287](https://github.com/angular/angular.js/issues/5287))
1
Javascript
Javascript
provide template inlining
e2b1d9e994e50bcd01d237302a3357bc7ebb6fa5
<ide><path>src/AngularPublic.js <ide> function publishExternalAPI(angular){ <ide> input: inputDirective, <ide> textarea: inputDirective, <ide> form: ngFormDirective, <add> script: scriptTemplateLoader, <ide> select: selectDirective, <ide> option: optionDirective, <ide> ngBind: ngBindDirective, <ide><path>src/widgets.js <ide> var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp <ide> }); <ide> }; <ide> }]; <add> <add> <add>var scriptTemplateLoader = ['$templateCache', function($templateCache) { <add> return { <add> compile: function(element, attr) { <add> if (attr.type == 'text/ng-template') { <add> var templateUrl = attr.id; <add> $templateCache.put(templateUrl, element.text()); <add> } <add> } <add> }; <add>}]; <ide><path>test/widgetsSpec.js <ide> describe('widget', function() { <ide> })); <ide> }); <ide> }); <add> <add> <add> describe('scriptTemplateLoader', function() { <add> it('should populate $templateCache with contents of a ng-template script element', inject( <add> function($compile, $templateCache) { <add> if (msie <=8) return; <add> // in ie8 it is not possible to create a script tag with the right content. <add> // it always comes up as empty. I was trying to set the text of the <add> // script tag, but that did not work either, so I gave up. <add> $compile('<div>foo' + <add> '<script id="/ignore">ignore me</script>' + <add> '<script type="text/ng-template" id="/myTemplate.html"><x>{{y}}</x></script>' + <add> '</div>' ); <add> expect($templateCache.get('/myTemplate.html')).toBe('<x>{{y}}</x>'); <add> expect($templateCache.get('/ignore')).toBeUndefined(); <add> } <add> )); <add> }); <ide> });
3
Javascript
Javascript
fix silly unnecessary defprop
c64b3166dc1d2855266ec2b86a03ec2d786398f1
<ide><path>packages/ember-metal/lib/meta.js <ide> export function meta(obj, writable) { <ide> return ret || EMPTY_META; <ide> } <ide> <del> if (obj.__defineNonEnumerable) { <del> obj.__defineNonEnumerable(EMBER_META_PROPERTY); <del> } else { <del> Object.defineProperty(obj, '__ember_meta__', META_DESC); <add> if (ret && ret.source === obj) { <add> return ret; <ide> } <ide> <ide> if (!ret) { <ide> ret = new Meta(obj); <ide> if (isEnabled('mandatory-setter')) { <ide> ret.writableValues(); <ide> } <del> } else if (ret.source !== obj) { <add> } else { <ide> ret = new Meta(obj, ret); <ide> } <add> <add> if (obj.__defineNonEnumerable) { <add> obj.__defineNonEnumerable(EMBER_META_PROPERTY); <add> } else { <add> Object.defineProperty(obj, '__ember_meta__', META_DESC); <add> } <ide> obj.__ember_meta__ = ret; <add> <ide> return ret; <ide> }
1
Text
Text
fix formdata example
3d13b67c562d45434536697bb232e2b1fba8e035
<ide><path>README.md <ide> form.append('my_field', 'my value'); <ide> form.append('my_buffer', new Buffer(10)); <ide> form.append('my_file', fs.createReadStream('/foo/bar.jpg')); <ide> <del>axios.post('https://example.com', form, { headers: form.getHeaders() }) <add>axios.post('https://example.com', form.getBuffer(), { headers: form.getHeaders() }) <ide> ``` <ide> <ide> Alternatively, use an interceptor:
1
Text
Text
add missing period in getting started guide
25a49953133f40cec4967a67c660332fa51db33c
<ide><path>guides/source/getting_started.md <ide> These changes will ensure that all articles have a title that is at least five <ide> characters long. Rails can validate a variety of conditions in a model, <ide> including the presence or uniqueness of columns, their format, and the <ide> existence of associated objects. Validations are covered in detail in [Active <del>Record Validations](active_record_validations.html) <add>Record Validations](active_record_validations.html). <ide> <ide> With the validation now in place, when you call `@article.save` on an invalid <ide> article, it will return `false`. If you open
1
Ruby
Ruby
promote log stream to a local
effddda4f9efc336bef6e39eb93a6a9985b3ed44
<ide><path>Library/Homebrew/formula.rb <ide> def system cmd, *args <ide> pid = fork { exec_cmd(cmd, args, rd, wr, logfn) } <ide> wr.close <ide> <del> File.open(logfn, 'w') do |f| <del> f.puts Time.now, "", cmd, args, "" <del> <del> if ARGV.verbose? <del> while buf = rd.gets <del> f.puts buf <del> puts buf <del> end <del> elsif IO.respond_to?(:copy_stream) <del> IO.copy_stream(rd, f) <del> else <del> buf = "" <del> f.write(buf) while rd.read(1024, buf) <add> log = File.open(logfn, "w") <add> log.puts Time.now, "", cmd, args, "" <add> <add> if ARGV.verbose? <add> while buf = rd.gets <add> log.puts buf <add> puts buf <ide> end <add> elsif IO.respond_to?(:copy_stream) <add> IO.copy_stream(rd, log) <add> else <add> buf = "" <add> log.write(buf) while rd.read(1024, buf) <add> end <ide> <del> Process.wait(pid) <add> Process.wait(pid) <ide> <del> $stdout.flush <add> $stdout.flush <ide> <del> unless $?.success? <del> f.flush <del> Kernel.system "/usr/bin/tail", "-n", "5", logfn unless ARGV.verbose? <del> f.puts <del> require 'cmd/config' <del> Homebrew.dump_build_config(f) <del> raise BuildError.new(self, cmd, args) <del> end <add> unless $?.success? <add> log.flush <add> Kernel.system "/usr/bin/tail", "-n", "5", logfn unless ARGV.verbose? <add> log.puts <add> require 'cmd/config' <add> Homebrew.dump_build_config(log) <add> raise BuildError.new(self, cmd, args) <ide> end <ide> ensure <ide> rd.close unless rd.closed?
1
Python
Python
apply renames fixer
ffdad17d0db1d55d39911d637c650ea0acada78b
<ide><path>numpy/core/arrayprint.py <ide> from .multiarray import format_longfloat, datetime_as_string, datetime_data <ide> from .fromnumeric import ravel <ide> <add>if sys.version_info[0] >= 3: <add> _MAXINT = sys.maxsize <add> _MININT = -sys.maxsize - 1 <add>else: <add> _MAXINT = sys.maxint <add> _MININT = -sys.maxint - 1 <ide> <ide> def product(x, y): return x*y <ide> <ide> def _digits(x, precision, format): <ide> return precision - len(s) + len(z) <ide> <ide> <del>_MAXINT = sys.maxint <del>_MININT = -sys.maxint-1 <ide> class IntegerFormat(object): <ide> def __init__(self, data): <ide> try: <ide><path>numpy/oldnumeric/ma.py <ide> """ <ide> from __future__ import division, absolute_import, print_function <ide> <del>import types, sys <add>import sys <add>import types <add>import warnings <add>from functools import reduce <ide> <ide> import numpy.core.umath as umath <ide> import numpy.core.fromnumeric as fromnumeric <ide> from numpy.core.numeric import newaxis, ndarray, inf <ide> from numpy.core.fromnumeric import amax, amin <ide> from numpy.core.numerictypes import bool_, typecodes <ide> import numpy.core.numeric as numeric <del>import warnings <del>from functools import reduce <add> <add>if sys.version_info[0] >= 3: <add> _MAXINT = sys.maxsize <add> _MININT = -sys.maxsize - 1 <add>else: <add> _MAXINT = sys.maxint <add> _MININT = -sys.maxint - 1 <ide> <ide> <ide> # Ufunc domain lookup for __array_wrap__ <ide> def minimum_fill_value (obj): <ide> if isinstance(obj, types.FloatType): <ide> return numeric.inf <ide> elif isinstance(obj, types.IntType) or isinstance(obj, types.LongType): <del> return sys.maxint <add> return _MAXINT <ide> elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray): <ide> x = obj.dtype.char <ide> if x in typecodes['Float']: <ide> return numeric.inf <ide> if x in typecodes['Integer']: <del> return sys.maxint <add> return _MAXINT <ide> if x in typecodes['UnsignedInteger']: <del> return sys.maxint <add> return _MAXINT <ide> else: <ide> raise TypeError('Unsuitable type for calculating minimum.') <ide> <ide> def maximum_fill_value (obj): <ide> if isinstance(obj, types.FloatType): <ide> return -inf <ide> elif isinstance(obj, types.IntType) or isinstance(obj, types.LongType): <del> return -sys.maxint <add> return -_MAXINT <ide> elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray): <ide> x = obj.dtype.char <ide> if x in typecodes['Float']: <ide> return -inf <ide> if x in typecodes['Integer']: <del> return -sys.maxint <add> return -_MAXINT <ide> if x in typecodes['UnsignedInteger']: <ide> return 0 <ide> else: <ide><path>tools/py3tool.py <ide> 'raise', <ide> 'raw_input', <ide> 'reduce', <del># 'renames', <add> 'renames', <ide> 'repr', <ide> 'setliteral', <ide> 'standarderror',
3
Text
Text
add link to github-pr-helper
8383ecfcdfae662e0f3269d333538a55540d9270
<ide><path>CONTRIBUTING.md <ide> That's it! Thank you for your contribution! <ide> When the patch is reviewed and merged, you can safely delete your branch and pull the changes <ide> from the main (upstream) repository: <ide> <del>```shell <del># Delete the remote branch on Github: <del>git push origin --delete my-fix-branch <add>* Delete the remote branch on Github: <ide> <del># Check out the master branch: <del>git checkout master -f <add> ```shell <add> git push origin --delete my-fix-branch <add> ``` <ide> <del># Delete the local branch: <del>git branch -D my-fix-branch <add>* Check out the master branch: <add> <add> ```shell <add> git checkout master -f <add> ``` <add> <add>* Delete the local branch: <add> <add> ```shell <add> git branch -D my-fix-branch <add> ``` <add> <add>* Update your master with the latest upstream version: <add> <add> ```shell <add> git pull --ff upstream master <add> ``` <add> <add>### GitHub Pull Request Helper <add> <add>We track Pull Requests by attaching labels and assigning to milestones. For some reason GitHub <add>does not provide a good UI for managing labels on Pull Requests (unlike Issues). We have developed <add>a simple Chrome Extension that enables you to view (and manage if you have permission) the labels <add>on Pull Requests. You can get the extension from the Chrome WebStore - <add>[GitHub PR Helper](github-pr-helper) <ide> <del># Update your master with the latest upstream version: <del>git pull --ff upstream master <del>``` <ide> ## Coding Rules <ide> To ensure consistency throughout the source code, keep these rules in mind as you are working: <ide> <ide> You can find out more detailed information about contributing in the <ide> [individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html <ide> [corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html <ide> [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# <add>[github-pr-helper]: https://chrome.google.com/webstore/detail/github-pr-helper/mokbklfnaddkkbolfldepnkfmanfhpen <ide>\ No newline at end of file
1
Javascript
Javascript
increase maxbuffer to fix enobufs error
bdf248d4db30fac4a6c23337e5c4db1e2fa6892a
<ide><path>script/lib/compress-artifacts.js <ide> function compress(inputDirPath, outputArchivePath) { <ide> } <ide> compressArguments.push(outputArchivePath, path.basename(inputDirPath)); <ide> spawnSync(compressCommand, compressArguments, { <del> cwd: path.dirname(inputDirPath) <add> cwd: path.dirname(inputDirPath), <add> maxBuffer: 2024 * 2024 <ide> }); <ide> }
1
Text
Text
make labels and list style consistent
1676b8477f2f2ae3b6f603a1e89c73400beb156d
<ide><path>CHANGELOG.md <ide> is `$locals`. <ide> [#13236](https://github.com/angular/angular.js/issues/13236)) <ide> <ide> <del>## Breaking Changes <del> <del> <ide> <a name="1.5.0-beta.2"></a> <ide> # 1.5.0-beta.2 effective-delegation (2015-11-17) <ide> <ide> requirement more strict and alerts the developer explicitly. <ide> [#2318](https://github.com/angular/angular.js/issues/2318), [#9319](https://github.com/angular/angular.js/issues/9319), [#12159](https://github.com/angular/angular.js/issues/12159)) <ide> <ide> <del>## Breaking Changes <del> <del> <ide> <a name="1.3.20"></a> <ide> # 1.3.20 shallow-translucence (2015-09-29) <ide> <ide> requirement more strict and alerts the developer explicitly. <ide> ([d434f3db](https://github.com/angular/angular.js/commit/d434f3db53d6209eb140b904e83bbde401686c16)) <ide> <ide> <del>## Breaking Changes <del> <del> <ide> <a name="1.2.29"></a> <ide> # 1.2.29 ultimate-deprecation (2015-09-29) <ide> <ide> requirement more strict and alerts the developer explicitly. <ide> [#9936](https://github.com/angular/angular.js/issues/9936)) <ide> <ide> <del>## Breaking Changes <del> <del> <ide> <a name="1.4.6"></a> <ide> # 1.4.6 multiplicative-elevation (2015-09-17) <ide> <ide> describe('$q.when', function() { <ide> <ide> ## Breaking Changes <ide> <del>### ngAnimate <del> <del>- **$animateCss:** due to [d5683d21](https://github.com/angular/angular.js/commit/d5683d21165e725bc5a850e795f681b0a8a008f5), <add>- **ngAnimate** - $animateCss: due to [d5683d21](https://github.com/angular/angular.js/commit/d5683d21165e725bc5a850e795f681b0a8a008f5), <ide> The $animateCss service will now always return an <ide> object even if the animation is not set to run. If your code is using <ide> $animateCss then please consider the following code change: <ide> $animateProvider.classNameFilter(/ng-animate-special/); <ide> ``` <ide> <ide> <del>### ngOptions <del> <del>- ** due to [dfa722a8](https://github.com/angular/angular.js/commit/dfa722a8a6864793fd9580d8ae704a06d10b5509), <add>- **ngOptions**: due to [dfa722a8](https://github.com/angular/angular.js/commit/dfa722a8a6864793fd9580d8ae704a06d10b5509), <ide> <ide> <ide> Although it is unlikely that anyone is using it in this way, this change does change the
1
Python
Python
apply suggestions from code review
8d297a801eabaa740fc07d4826cb03951cc1d729
<ide><path>numpy/ma/tests/test_core.py <ide> def test_creation_with_list_of_maskedarrays_no_bool_cast(self): <ide> normal_int = np.arange(2) <ide> res = np.ma.asarray([masked_str, normal_int]) <ide> assert_array_equal(res.mask, [[True, False], [False, False]]) <del> # Te above only failed due a long chain of oddity, try also with <add> <add> # The above only failed due a long chain of oddity, try also with <ide> # an object array that cannot be converted to bool always: <ide> class NotBool(): <ide> def __bool__(self):
1
Text
Text
expand bi-directional associations guide [ci skip]
9e4b3f4e9e23420703bbee01a511f43d513b5841
<ide><path>guides/source/association_basics.md <ide> class Book < ApplicationRecord <ide> end <ide> ``` <ide> <del>Active Record will attempt to automatically identify that these two models share a bi-directional association based on the association name. In this way, Active Record will only load one copy of the `Author` object, making your application more efficient and preventing inconsistent data: <del> <del>```irb <del>irb> a = Author.first <del>irb> b = a.books.first <del>irb> a.first_name == b.author.first_name <del>=> true <del>irb> a.first_name = 'David' <del>irb> a.first_name == b.author.first_name <del>=> true <del>``` <add>Active Record will attempt to automatically identify that these two models share <add>a bi-directional association based on the association name. This information <add>allows Active Record to: <add> <add>* Prevent needless queries for already-loaded data <add> <add> ```irb <add> irb> author = Author.first <add> irb> author.books.all? do |book| <add> irb> book.author.equal?(author) # No additional queries executed here <add> irb> end <add> => true <add> ``` <add> <add>* Prevent inconsistent data (since there is only one copy of the `Author` object <add> loaded) <add> <add> ```irb <add> irb> author = Author.first <add> irb> book = author.books.first <add> irb> author.name == book.author.name <add> => true <add> irb> author.name = "Changed Name" <add> irb> author.name == book.author.name <add> => true <add> ``` <add> <add>* Autosave associations in more cases <add> <add> ```irb <add> irb> author = Author.new <add> irb> book = author.books.new <add> irb> book.save! <add> irb> book.persisted? <add> => true <add> irb> author.persisted? <add> => true <add> ``` <add> <add>* Validate the [presence](active_record_validations.html#presence) and <add> [absence](active_record_validations.html#absence) of associations in more <add> cases <add> <add> ```irb <add> irb> book = Book.new <add> irb> book.valid? <add> => false <add> irb> book.errors.full_messages <add> => ["Author must exist"] <add> irb> author = Author.new <add> irb> book = author.books.new <add> irb> book.valid? <add> => true <add> ``` <ide> <ide> Active Record supports automatic identification for most associations with <ide> standard names. However, Active Record will not automatically identify <ide> class Book < ApplicationRecord <ide> end <ide> ``` <ide> <del>Active Record will no longer automatically recognize the bi-directional association: <add>Because of the `:foreign_key` option, Active Record will no longer automatically <add>recognize the bi-directional association. This can cause your application to: <ide> <del>```irb <del>irb> a = Author.first <del>irb> b = a.books.first <del>irb> a.first_name == b.writer.first_name <del>=> true <del>irb> a.first_name = 'David' <del>irb> a.first_name == b.writer.first_name <del>=> false <del>``` <add>* Execute needless queries for the same data (in this example causing N+1 queries) <add> <add> ```irb <add> irb> author = Author.first <add> irb> author.books.any? do |book| <add> irb> book.author.equal?(author) # This executes an author query for every book <add> irb> end <add> => false <add> ``` <add> <add>* Reference multiple copies of a model with inconsistent data <add> <add> ```irb <add> irb> author = Author.first <add> irb> book = author.books.first <add> irb> author.name == book.author.name <add> => true <add> irb> author.name = "Changed Name" <add> irb> author.name == book.author.name <add> => false <add> ``` <add> <add>* Fail to autosave associations <add> <add> ```irb <add> irb> author = Author.new <add> irb> book = author.books.new <add> irb> book.save! <add> irb> book.persisted? <add> => true <add> irb> author.persisted? <add> => false <add> ``` <add> <add>* Fail to validate presence or absence <add> <add> ```irb <add> irb> author = Author.new <add> irb> book = author.books.new <add> irb> book.valid? <add> => false <add> irb> book.errors.full_messages <add> => ["Author must exist"] <add> ``` <ide> <ide> Active Record provides the `:inverse_of` option so you can explicitly declare bi-directional associations: <ide> <ide> class Book < ApplicationRecord <ide> end <ide> ``` <ide> <del>By including the `:inverse_of` option in the `has_many` association declaration, Active Record will now recognize the bi-directional association: <del> <del>```irb <del>irb> a = Author.first <del>irb> b = a.books.first <del>irb> a.first_name == b.writer.first_name <del>=> true <del>irb> a.first_name = 'David' <del>irb> a.first_name == b.writer.first_name <del>=> true <del>``` <add>By including the `:inverse_of` option in the `has_many` association declaration, <add>Active Record will now recognize the bi-directional association and behave as in <add>the initial examples above. <ide> <ide> Detailed Association Reference <ide> ------------------------------ <ide> When we execute `@user.todos.create` then the `@todo` record will have its <ide> ##### `:inverse_of` <ide> <ide> The `:inverse_of` option specifies the name of the `has_many` or `has_one` association that is the inverse of this association. <add>See the [bi-directional association](#bi-directional-associations) section for more details. <ide> <ide> ```ruby <ide> class Author < ApplicationRecord <ide> TIP: In any case, Rails will not create foreign key columns for you. You need to <ide> ##### `:inverse_of` <ide> <ide> The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. <add>See the [bi-directional association](#bi-directional-associations) section for more details. <ide> <ide> ```ruby <ide> class Supplier < ApplicationRecord <ide> TIP: In any case, Rails will not create foreign key columns for you. You need to <ide> ##### `:inverse_of` <ide> <ide> The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. <add>See the [bi-directional association](#bi-directional-associations) section for more details. <ide> <ide> ```ruby <ide> class Author < ApplicationRecord
1
Javascript
Javascript
improve description for reset type flags
ea9bfc70ac7a099d12bd5f42fb7e5633a1596390
<ide><path>lib/cli.js <ide> const getArguments = (schema = webpackSchema) => { <ide> { <ide> type: "reset", <ide> multiple: false, <del> description: `Clear all items provided in configuration. ${description}`, <add> description: `Clear all items provided in "${schemaPath}" configuration. ${description}`, <ide> path: schemaPath <ide> } <ide> ],
1
Ruby
Ruby
avoid early return
f6eedf946487980c740f5e0595fb46a5a2710597
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def run <ide> @status = success ? :passed : :failed <ide> puts_result <ide> <del> return unless File.exist?(log) <del> @output = File.read(log) <del> if has_output? and (not success or @puts_output_on_success) <del> puts @output <add> if File.exist?(log) <add> @output = File.read(log) <add> if has_output? and (not success or @puts_output_on_success) <add> puts @output <add> end <add> FileUtils.rm(log) unless ARGV.include? "--keep-logs" <ide> end <del> FileUtils.rm(log) unless ARGV.include? "--keep-logs" <ide> end <ide> end <ide>
1