1 | /**
|
2 | Licensed to the Apache Software Foundation (ASF) under one
|
3 | or more contributor license agreements. See the NOTICE file
|
4 | distributed with this work for additional information
|
5 | regarding copyright ownership. The ASF licenses this file
|
6 | to you under the Apache License, Version 2.0 (the
|
7 | "License"); you may not use this file except in compliance
|
8 | with the License. You may obtain a copy of the License at
|
9 |
|
10 | http://www.apache.org/licenses/LICENSE-2.0
|
11 |
|
12 | Unless required by applicable law or agreed to in writing,
|
13 | software distributed under the License is distributed on an
|
14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
15 | KIND, either express or implied. See the License for the
|
16 | specific language governing permissions and limitations
|
17 | under the License.
|
18 | */
|
19 |
|
20 | /* jshint quotmark:false */
|
21 |
|
22 | var events = require('./events');
|
23 | var Q = require('q');
|
24 |
|
25 | function ActionStack () {
|
26 | this.stack = [];
|
27 | this.completed = [];
|
28 | }
|
29 |
|
30 | ActionStack.prototype = {
|
31 | createAction: function (handler, action_params, reverter, revert_params) {
|
32 | return {
|
33 | handler: {
|
34 | run: handler,
|
35 | params: action_params
|
36 | },
|
37 | reverter: {
|
38 | run: reverter,
|
39 | params: revert_params
|
40 | }
|
41 | };
|
42 | },
|
43 | push: function (tx) {
|
44 | this.stack.push(tx);
|
45 | },
|
46 | // Returns a promise.
|
47 | process: function (platform) {
|
48 | events.emit('verbose', 'Beginning processing of action stack for ' + platform + ' project...');
|
49 |
|
50 | while (this.stack.length) {
|
51 | var action = this.stack.shift();
|
52 | var handler = action.handler.run;
|
53 | var action_params = action.handler.params;
|
54 |
|
55 | try {
|
56 | handler.apply(null, action_params);
|
57 | } catch (e) {
|
58 | events.emit('warn', 'Error during processing of action! Attempting to revert...');
|
59 | this.stack.unshift(action);
|
60 | var issue = 'Uh oh!\n';
|
61 | // revert completed tasks
|
62 | while (this.completed.length) {
|
63 | var undo = this.completed.shift();
|
64 | var revert = undo.reverter.run;
|
65 | var revert_params = undo.reverter.params;
|
66 |
|
67 | try {
|
68 | revert.apply(null, revert_params);
|
69 | } catch (err) {
|
70 | events.emit('warn', 'Error during reversion of action! We probably really messed up your project now, sorry! D:');
|
71 | issue += 'A reversion action failed: ' + err.message + '\n';
|
72 | }
|
73 | }
|
74 | e.message = issue + e.message;
|
75 | return Q.reject(e);
|
76 | }
|
77 | this.completed.push(action);
|
78 | }
|
79 | events.emit('verbose', 'Action stack processing complete.');
|
80 |
|
81 | return Q();
|
82 | }
|
83 | };
|
84 |
|
85 | module.exports = ActionStack;
|