<commit_before>(function(window, document) {
    "use strict";

    var Woopra = {};

    var console = window.console;

    /*
     * Helper functions
     */

    Woopra.CONSTANTS = {
        EVENT_ENDPOINT: window.location.protocol + '//www.woopra.com/track/ce/',
        PING_ENDPOINT: window.location.protocol + '//www.woopra.com/track/ping/'
    };

    Woopra.extend = function(o1, o2) {
        for (var key in o2) {
            o1[key] = o2[key];
        }
    };

    Woopra.readCookie = function(name) {
        if (name === '') {
            return '';
        }
        var c = "" + document.cookie;

        var i = c.indexOf(name);
        if (i === -1){
            return "";
        }
        var k = c.indexOf(';', i);
        if (k === -1){
            k = c.length;
        }

        return window.unescape(c.substring(i + name.length + 1, k));
    };

    Woopra.setCookie = function(k, v, exp, domain, path) {
        var cookie = [];
        cookie.push(k + '=' + v);
        cookie.push('expires=' + exp);
        cookie.push('path=' + path);
        cookie.push('domain=.' + domain);

        document.cookie = cookie.join('; ');
    };

    Woopra.getCampaignData = function(url) {
        var vars = Woopra.getUrlParams();
        var campaign = {};
        var campaignKeys = ['source', 'medium', 'content', 'campaign', 'term'];
        for (var i=0;i<campaignKeys.length;i++) {
            var key = campaignKeys[i];
            var value = vars['utm_' + key] || vars['woo_' + key];
            if (typeof value != 'undefined') {
                campaign['campaign_' + ((key=='campaign')?'name':key)] = value;
            }
        }
        return campaign;
    };

    Woopra.getUrlParams = function(url) {
        var vars = {};
        window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            vars[key] = decodeURIComponent(value.split("+").join(" "));
        });
        return vars;
    };

    Woopra.buildUrlParams = function(params, prefix) {
        var _prefix = prefix || '',
            key,
            p = [];

        if (typeof params === 'undefined') {
            return params;
        }

        for (key in params) {
            p.push(_prefix + encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
        }
        return p.join('&');
    };

    Woopra.randomString = function() {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
            i,
            rnum,
            s = '';

        for (i = 0; i < 12; i++) {
            rnum = Math.floor(Math.random() * chars.length);
            s += chars.substring(rnum, rnum + 1);
        }

        return s;
    };

    Woopra.loadScript = function(url, callback) {
        var ssc,
            script = document.createElement('script');

        script.type = 'text/javascript';
        script.src = url;
        script.async = true;

        if (typeof script.onreadystatechange != 'undefined') {
            script.onreadystatechange = function() {
                if (this.readyState === 'complete'|| this.readyState === 'loaded') {
                    if (callback) {
                        callback();
                    }
                    Woopra.removeScript(script);
                }
            };
        } else {
            script.onload = function(){
                if (callback) {
                    callback();
                }
                Woopra.removeScript(script);
            };
        }

        ssc = document.getElementsByTagName('script')[0];
        ssc.parentNode.insertBefore(script, ssc);
    };

    Woopra.removeScript = function(script) {
        script.parentNode.removeChild(script);
    };

    Woopra.getHost = function() {
        return window.location.host.replace('www.','');
    };

    Woopra.endsWith = function(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    };

    var Tracker = function(instanceName) {
        this.visitorData = {};
        this.visitData = {};
        this.options = {};
        this.instanceName = instanceName;
        this.idle = 0;
        this.cookie = '';
        this._loaded = false;
    };

    Tracker.prototype = {
        init: function(instanceName) {
            this._setOptions();
            this._processQueue('config');
            this._setupCookie();
            this._loaded = true;
            this._processQueue();
        },

        /**
         * Processes the tracker queue in case user tries to push events
         * before tracker is ready.
         */
        _processQueue: function(type) {
            var i,
                action,
                events,
                _wpt = window._wpt[this.instanceName];

            if (_wpt && _wpt._e) {
                events = _wpt._e;
                for (i = 0; i < events.length; i++) {
                    action = events[i];
                    if (typeof action !== 'undefined' && this[action[0]] &&
                        (typeof type === 'undefined' || type === action[0])) {
                        this[action[0]].apply(this, Array.prototype.slice.call(action, 1));
                    }
                }
            }
        },

        /**
         * Sets the initial options
         */
        _setOptions: function() {
            var exp = new Date();

            // Set default options
            exp.setDate(exp.getDate()+365);
            this.config({
                domain : Woopra.getHost(),
                cookie_name : 'wooTracker',
                cookie_domain : null,
                cookie_path : '/',
                cookie_expire : exp,
                ping : true,
                ping_interval : 12000,
                idle_timeout : 300000,
                download_pause : 200,
                outgoing_pause : 400,
                download_tracking : true,
                outgoing_tracking : true,
                ignore_query_url: true
            });
        },

        /**
         * Sets up the tracking cookie
         */
        _setupCookie: function() {
            // Setup cookie
            this.cookie = Woopra.readCookie(this.config('cookie_name'));
            if (this.cookie && this.cookie.length > 0) {
            }
            else {
                this.cookie = Woopra.randomString();
            }

            if (this.config('cookie_domain') === null) {
                if (Woopra.endsWith(window.location.host, '.' + this.config('domain'))) {
                    this.config('cookie_domain', this.config('domain'));
                } else {
                    this.config('cookie_domain', Woopra.getHost());
                }
            }
            Woopra.setCookie(
                this.config('cookie_name'),
                this.cookie,
                this.config('cookie_exp'),
                this.config('cookie_domain'),
                this.config('cookie_path')
            );
        },

        /**
         * Sets/gets values from dataStore depending on arguments passed
         *
         * @param dataStore Object The tracker property to read/write
         * @param key String/Object Returns property object if key and value is undefined,
         *      acts as a getter if only `key` is defined and a string, and
         *      acts as a setter if `key` and `value` are defined OR if `key` is an object.
         */
        _dataSetter: function(dataStore, key, value) {
            var i;

            if (typeof key === 'undefined') {
                return dataStore;
            }

            if (typeof value === 'undefined') {
                if (typeof key === 'string') {
                    return dataStore[key];
                }
                if (typeof key === 'object') {
                    for (i in key) {
                        dataStore[i] = key[i];
                        //this._dataSetter(dataStore, i, key[i]);
                    }
                }
            }
            else {
                dataStore[key] = value;
            }

            return this;
        },

        /**
         * Builds the correct tracking URL and performs an HTTP request
         */
        _push: function(endpoint, options) {
            var _options = options || {},
                _endpoint = Woopra.CONSTANTS.EVENT_ENDPOINT,
                random = 'ra=' + Woopra.randomString(),
                queryString,
                scriptUrl,
                data = [];

            data.push(random);
            data.push(Woopra.buildUrlParams(this.getOptionParams()));

            if (_options.visitorData) {
                data.push(Woopra.buildUrlParams(_options.visitorData, 'cv_'));
            }

            if (_options.eventData) {
                data.push(Woopra.buildUrlParams(_options.eventData, 'ce_'));
            }

            queryString = '?' + data.join('&');

            scriptUrl = _endpoint + queryString;
            Woopra.loadScript(scriptUrl, _options.callback);
        },

        /**
         * Sets configuration options
         */
        config: function(key, value) {
            return this._dataSetter(this.options, key, value);
        },

        /**
         * Use to attach custom visit data that doesn't stick to visitor
         * ** Not in use yet
         */
        visit: function(key, value) {
            return this._dataSetter(this.visitData, key, value);
        },

        /**
         * Attach custom visitor data
         */
        identify: function(key, value) {
            console.log('$$$', this.visitorData);
            var blah = this._dataSetter(this.visitorData, key, value);
            console.log('aweorkaewor', blah);

            return blah;
        },

        /**
         *
         */
        track: function(name, options) {
            var event = {};

            // Load campaign params (load first to allow overrides)
            Woopra.extend(event, Woopra.getCampaignData());

        },

        call: function() {
        },

        _track: function(name, options) {
            var event = {},
                callback;

            // Track default: pageview
            if (typeof name === 'undefined') {
                event.name = 'pv',
                event.url = this.getPageURL();
                event.title = this.getPageTitle();
            }
            // Track custom events
            else if (options === 'undefined') {
                if (typeof name === 'string') {
                    event.name = name;
                }
                if (typeof name === 'object') {
                    this._dataSetter(event, name);
                }
            }
            // Track custom events in format of name,object
            else {
                event.name = name;
                this._dataSetter(event, options);
            }

            // Extract callback
            if (typeof event.hitCallback === 'function') {
                callback = event.hitCallback;
                delete event.hitCallback;
            }

            this._push('event', {
                visitorData: this.visitorData,
                eventData: event,
                callback: callback
            });

            this.startPing();
        },

        startPing: function() {
            var self = this;
            if (typeof this.pingInterval == 'undefined') {
                window.clearInterval(this.pingInterval);
                delete this.pingInterval;
            }
            this.pingInterval = window.setInterval(function() {
                self.ping();
            }, this.config('ping_interval'));
        },

        /**
         * Pings tracker with visitor info
         */
        ping: function() {
            this._push('ping', {
                visitorData: this.visitorData
            });

            return this;
        },

        /**
         * Pushes visitor data to server without sending an event
         */
        push: function() {
            this._push('identify', {
                visitorData: this.visitorData
            });
            return this;
        },

        getPageUrl: function() {
            if (this.options.ignore_query_url) {
                return window.location.pathname;
            } else {
                return window.location.pathname + window.location.search;
            }
        },

        getPageTitle: function() {
            return (document.getElementsByTagName('title').length === 0) ? '' : document.getElementsByTagName('title')[0].innerHTML;
        },

        getOptionParams: function() {
            var o = {
                alias: this.config('domain'),
                cookie: Woopra.readCookie(this.config('cookie_name')),
                meta: Woopra.readCookie('wooMeta') || '',
                screen: window.screen.width + 'x' + window.screen.height,
                language: window.navigator.browserLanguage || window.navigator.language || "",
                referer: document.referrer,
                idle: '' + parseInt(this.idle/1000, 10),
                vs: 'w'
            };
            /*
             if(t.vs==2){
                 r['vs']='w';
                 t.vs=0;
             }else{
                 if(t.idle==0){
                     r['vs']='r';
                 }else{
                     r['vs']='i';
                 }
                 }*/
                return o;

            }
        };

         //Woopra.Tracker = Tracker;
         var _public = {
             Tracker: Tracker
         };

         // Initialize instances & preloaded settings/events
         if (typeof window._wpt !== 'undefined') {
             for (var name in window._wpt) {
                 cosnole.log(name);
                 var instance = new Tracker(name);
                 instance.init();
                 window[name]=instance;
             }
         }

         window.Woopra = _public || {};

         if (typeof window.exports !== 'undefined') {
             window.exports.Woopra = _public;
         }

     })(window, document);
<commit_msg>Change ENDPOINT constants<commit_after>(function(window, document) {
    "use strict";

    var Woopra = {};

    var console = window.console;

    /*
     * Helper functions
     */

    Woopra.CONSTANTS = {
        ENDPOINT: window.location.protocol + '//www.woopra.com/track/',
        EVENT_ENDPOINT: window.location.protocol + '//www.woopra.com/track/ce/',
        PING_ENDPOINT: window.location.protocol + '//www.woopra.com/track/ping/'
    };

    Woopra.extend = function(o1, o2) {
        for (var key in o2) {
            o1[key] = o2[key];
        }
    };

    Woopra.readCookie = function(name) {
        if (name === '') {
            return '';
        }
        var c = "" + document.cookie;

        var i = c.indexOf(name);
        if (i === -1){
            return "";
        }
        var k = c.indexOf(';', i);
        if (k === -1){
            k = c.length;
        }

        return window.unescape(c.substring(i + name.length + 1, k));
    };

    Woopra.setCookie = function(k, v, exp, domain, path) {
        var cookie = [];
        cookie.push(k + '=' + v);
        cookie.push('expires=' + exp);
        cookie.push('path=' + path);
        cookie.push('domain=.' + domain);

        document.cookie = cookie.join('; ');
    };

    Woopra.getCampaignData = function(url) {
        var vars = Woopra.getUrlParams();
        var campaign = {};
        var campaignKeys = ['source', 'medium', 'content', 'campaign', 'term'];
        for (var i=0;i<campaignKeys.length;i++) {
            var key = campaignKeys[i];
            var value = vars['utm_' + key] || vars['woo_' + key];
            if (typeof value != 'undefined') {
                campaign['campaign_' + ((key=='campaign')?'name':key)] = value;
            }
        }
        return campaign;
    };

    Woopra.getUrlParams = function(url) {
        var vars = {};
        window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            vars[key] = decodeURIComponent(value.split("+").join(" "));
        });
        return vars;
    };

    Woopra.buildUrlParams = function(params, prefix) {
        var _prefix = prefix || '',
            key,
            p = [];

        if (typeof params === 'undefined') {
            return params;
        }

        for (key in params) {
            p.push(_prefix + encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
        }
        return p.join('&');
    };

    Woopra.randomString = function() {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
            i,
            rnum,
            s = '';

        for (i = 0; i < 12; i++) {
            rnum = Math.floor(Math.random() * chars.length);
            s += chars.substring(rnum, rnum + 1);
        }

        return s;
    };

    Woopra.loadScript = function(url, callback) {
        var ssc,
            script = document.createElement('script');

        script.type = 'text/javascript';
        script.src = url;
        script.async = true;

        if (typeof script.onreadystatechange != 'undefined') {
            script.onreadystatechange = function() {
                if (this.readyState === 'complete'|| this.readyState === 'loaded') {
                    if (callback) {
                        callback();
                    }
                    Woopra.removeScript(script);
                }
            };
        } else {
            script.onload = function(){
                if (callback) {
                    callback();
                }
                Woopra.removeScript(script);
            };
        }

        ssc = document.getElementsByTagName('script')[0];
        ssc.parentNode.insertBefore(script, ssc);
    };

    Woopra.removeScript = function(script) {
        script.parentNode.removeChild(script);
    };

    Woopra.getHost = function() {
        return window.location.host.replace('www.','');
    };

    Woopra.endsWith = function(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    };

    var Tracker = function(instanceName) {
        this.visitorData = {};
        this.visitData = {};
        this.options = {};
        this.instanceName = instanceName;
        this.idle = 0;
        this.cookie = '';
        this._loaded = false;
    };

    Tracker.prototype = {
        init: function(instanceName) {
            this._setOptions();
            this._processQueue('config');
            this._setupCookie();
            this._loaded = true;
            this._processQueue();
        },

        /**
         * Processes the tracker queue in case user tries to push events
         * before tracker is ready.
         */
        _processQueue: function(type) {
            var i,
                action,
                events,
                _wpt = window._wpt[this.instanceName];

            if (_wpt && _wpt._e) {
                events = _wpt._e;
                for (i = 0; i < events.length; i++) {
                    action = events[i];
                    if (typeof action !== 'undefined' && this[action[0]] &&
                        (typeof type === 'undefined' || type === action[0])) {
                        this[action[0]].apply(this, Array.prototype.slice.call(action, 1));
                    }
                }
            }
        },

        /**
         * Sets the initial options
         */
        _setOptions: function() {
            var exp = new Date();

            // Set default options
            exp.setDate(exp.getDate()+365);
            this.config({
                domain : Woopra.getHost(),
                cookie_name : 'wooTracker',
                cookie_domain : null,
                cookie_path : '/',
                cookie_expire : exp,
                ping : true,
                ping_interval : 12000,
                idle_timeout : 300000,
                download_pause : 200,
                outgoing_pause : 400,
                download_tracking : true,
                outgoing_tracking : true,
                ignore_query_url: true
            });
        },

        /**
         * Sets up the tracking cookie
         */
        _setupCookie: function() {
            // Setup cookie
            this.cookie = Woopra.readCookie(this.config('cookie_name'));
            if (this.cookie && this.cookie.length > 0) {
            }
            else {
                this.cookie = Woopra.randomString();
            }

            if (this.config('cookie_domain') === null) {
                if (Woopra.endsWith(window.location.host, '.' + this.config('domain'))) {
                    this.config('cookie_domain', this.config('domain'));
                } else {
                    this.config('cookie_domain', Woopra.getHost());
                }
            }
            Woopra.setCookie(
                this.config('cookie_name'),
                this.cookie,
                this.config('cookie_exp'),
                this.config('cookie_domain'),
                this.config('cookie_path')
            );
        },

        /**
         * Sets/gets values from dataStore depending on arguments passed
         *
         * @param dataStore Object The tracker property to read/write
         * @param key String/Object Returns property object if key and value is undefined,
         *      acts as a getter if only `key` is defined and a string, and
         *      acts as a setter if `key` and `value` are defined OR if `key` is an object.
         */
        _dataSetter: function(dataStore, key, value) {
            var i;

            if (typeof key === 'undefined') {
                return dataStore;
            }

            if (typeof value === 'undefined') {
                if (typeof key === 'string') {
                    return dataStore[key];
                }
                if (typeof key === 'object') {
                    for (i in key) {
                        dataStore[i] = key[i];
                        //this._dataSetter(dataStore, i, key[i]);
                    }
                }
            }
            else {
                dataStore[key] = value;
            }

            return this;
        },

        /**
         * Builds the correct tracking Url and performs an HTTP request
         */
        _push: function(endpoint, options) {
            var _options = options || {},
                _endpoint = Woopra.CONSTANTS.ENDPOINT + endpoint + '/',
                random = 'ra=' + Woopra.randomString(),
                queryString,
                scriptUrl,
                data = [];

            data.push(random);
            data.push(Woopra.buildUrlParams(this.getOptionParams()));

            if (_options.visitorData) {
                data.push(Woopra.buildUrlParams(_options.visitorData, 'cv_'));
            }

            if (_options.eventData) {
                data.push(Woopra.buildUrlParams(_options.eventData, 'ce_'));
            }

            queryString = '?' + data.join('&');

            scriptUrl = _endpoint + queryString;
            Woopra.loadScript(scriptUrl, _options.callback);
        },

        /**
         * Sets configuration options
         */
        config: function(key, value) {
            return this._dataSetter(this.options, key, value);
        },

        /**
         * Use to attach custom visit data that doesn't stick to visitor
         * ** Not in use yet
         */
        visit: function(key, value) {
            return this._dataSetter(this.visitData, key, value);
        },

        /**
         * Attach custom visitor data
         */
        identify: function(key, value) {
            console.log('$$$', this.visitorData);
            var blah = this._dataSetter(this.visitorData, key, value);
            console.log('aweorkaewor', blah);

            return blah;
        },

        /**
         *
         */
        track: function(name, options) {
            var event = {};

            // Load campaign params (load first to allow overrides)
            Woopra.extend(event, Woopra.getCampaignData());

        },

        call: function() {
        },

        _track: function(name, options) {
            var event = {},
                callback;

            // Track default: pageview
            if (typeof name === 'undefined') {
                event.name = 'pv',
                event.url = this.getPageURL();
                event.title = this.getPageTitle();
            }
            // Track custom events
            else if (options === 'undefined') {
                if (typeof name === 'string') {
                    event.name = name;
                }
                if (typeof name === 'object') {
                    this._dataSetter(event, name);
                }
            }
            // Track custom events in format of name,object
            else {
                event.name = name;
                this._dataSetter(event, options);
            }

            // Extract callback
            if (typeof event.hitCallback === 'function') {
                callback = event.hitCallback;
                delete event.hitCallback;
            }

            this._push('event', {
                visitorData: this.visitorData,
                eventData: event,
                callback: callback
            });

            this.startPing();
        },

        startPing: function() {
            var self = this;
            if (typeof this.pingInterval == 'undefined') {
                window.clearInterval(this.pingInterval);
                delete this.pingInterval;
            }
            this.pingInterval = window.setInterval(function() {
                self.ping();
            }, this.config('ping_interval'));
        },

        /**
         * Pings tracker with visitor info
         */
        ping: function() {
            this._push('ping', {
                visitorData: this.visitorData
            });

            return this;
        },

        /**
         * Pushes visitor data to server without sending an event
         */
        push: function() {
            this._push('identify', {
                visitorData: this.visitorData
            });
            return this;
        },

        getPageUrl: function() {
            if (this.options.ignore_query_url) {
                return window.location.pathname;
            } else {
                return window.location.pathname + window.location.search;
            }
        },

        getPageTitle: function() {
            return (document.getElementsByTagName('title').length === 0) ? '' : document.getElementsByTagName('title')[0].innerHTML;
        },

        getOptionParams: function() {
            var o = {
                alias: this.config('domain'),
                cookie: Woopra.readCookie(this.config('cookie_name')),
                meta: Woopra.readCookie('wooMeta') || '',
                screen: window.screen.width + 'x' + window.screen.height,
                language: window.navigator.browserLanguage || window.navigator.language || "",
                referer: document.referrer,
                idle: '' + parseInt(this.idle/1000, 10),
                vs: 'w'
            };
            /*
             if(t.vs==2){
                 r['vs']='w';
                 t.vs=0;
             }else{
                 if(t.idle==0){
                     r['vs']='r';
                 }else{
                     r['vs']='i';
                 }
                 }*/
                return o;

            }
        };

         //Woopra.Tracker = Tracker;
         var _public = {
             Tracker: Tracker
         };

         // Initialize instances & preloaded settings/events
         if (typeof window._wpt !== 'undefined') {
             for (var name in window._wpt) {
                 cosnole.log(name);
                 var instance = new Tracker(name);
                 instance.init();
                 window[name]=instance;
             }
         }

         window.Woopra = _public || {};

         if (typeof window.exports !== 'undefined') {
             window.exports.Woopra = _public;
         }

     })(window, document);
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import {
  View,
  StyleSheet,
  Platform,
  Image,
  Text as NativeText,
} from 'react-native';
import fonts from '../config/fonts';
import colors from '../config/colors';
import Text from '../text/Text';
import Divider from '../divider/Divider';
import normalize from '../helpers/normalizeText';
import ViewPropTypes from '../config/ViewPropTypes';
import BackgroundImage from '../config/BackgroundImage';

const Card = props => {
  const {
    children,
    flexDirection,
    containerStyle,
    wrapperStyle,
    imageWrapperStyle,
    title,
    titleStyle,
    featuredTitle,
    featuredTitleStyle,
    featuredSubtitle,
    featuredSubtitleStyle,
    dividerStyle,
    image,
    imageStyle,
    fontFamily,
    imageProps,
    ...attributes
  } = props;

  return (
    <View
      {...attributes}
      style={[
        styles.container,
        image && { padding: 0 },
        containerStyle && containerStyle,
      ]}
    >
      <View
        style={[
          styles.wrapper,
          wrapperStyle && wrapperStyle,
          flexDirection && { flexDirection },
        ]}
      >
        {title === '' ||
          (title &&
            title.length > 0 &&
            <View>
              <Text
                style={[
                  styles.cardTitle,
                  image && styles.imageCardTitle,
                  titleStyle && titleStyle,
                  fontFamily && { fontFamily },
                ]}
              >
                {title}
              </Text>
              {!image &&
                <Divider
                  style={[styles.divider, dividerStyle && dividerStyle]}
                />}
            </View>)}
        {image &&
          <View style={imageWrapperStyle && imageWrapperStyle}>
            <BackgroundImage
              resizeMode="cover"
              style={[{ width: null, height: 150 }, imageStyle && imageStyle]}
              source={image}
              {...imageProps}
            >
              {(featuredTitle || featuredSubtitle) &&
                <View style={styles.overlayContainer}>
                  {featuredTitle &&
                    <Text
                      style={[
                        styles.featuredTitle,
                        featuredTitleStyle && featuredTitleStyle,
                      ]}
                    >
                      {featuredTitle}
                    </Text>}
                  {featuredSubtitle &&
                    <Text
                      style={[
                        styles.featuredSubtitle,
                        featuredSubtitleStyle && featuredSubtitleStyle,
                      ]}
                    >
                      {featuredSubtitle}
                    </Text>}
                </View>}
            </BackgroundImage>
            <View style={[{ padding: 10 }, wrapperStyle && wrapperStyle]}>
              {children}
            </View>
          </View>}
        {!image && children}
      </View>
    </View>
  );
};

Card.propTypes = {
  children: PropTypes.any,
  flexDirection: PropTypes.string,
  containerStyle: ViewPropTypes.style,
  wrapperStyle: ViewPropTypes.style,
  overlayStyle: ViewPropTypes.style,
  title: PropTypes.string,
  titleStyle: NativeText.propTypes.style,
  featuredTitle: PropTypes.string,
  featuredTitleStyle: Text.propTypes.style,
  featuredSubtitle: PropTypes.string,
  featuredSubtitleStyle: Text.propTypes.style,
  dividerStyle: ViewPropTypes.style,
  image: Image.propTypes.source,
  imageStyle: ViewPropTypes.style,
  imageWrapperStyle: ViewPropTypes.style,
  fontFamily: PropTypes.string,
  imageProps: PropTypes.object,
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    borderColor: colors.grey5,
    borderWidth: 1,
    padding: 15,
    margin: 15,
    marginBottom: 0,
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .2)',
        shadowOffset: { height: 0, width: 0 },
        shadowOpacity: 1,
        shadowRadius: 1,
      },
      android: {
        elevation: 1,
      },
    }),
  },
  featuredTitle: {
    fontSize: normalize(18),
    marginBottom: 8,
    color: 'white',
    ...Platform.select({
      ios: {
        fontWeight: '800',
      },
      android: {
        ...fonts.android.black,
      },
    }),
  },
  featuredSubtitle: {
    fontSize: normalize(13),
    marginBottom: 8,
    color: 'white',
    ...Platform.select({
      ios: {
        fontWeight: '400',
      },
      android: {
        ...fonts.android.black,
      },
    }),
  },
  wrapper: {
    backgroundColor: 'transparent',
  },
  divider: {
    marginBottom: 15,
  },
  cardTitle: {
    fontSize: normalize(14),
    ...Platform.select({
      ios: {
        fontWeight: 'bold',
      },
      android: {
        ...fonts.android.black,
      },
    }),
    textAlign: 'center',
    marginBottom: 15,
    color: colors.grey1,
  },
  imageCardTitle: {
    marginTop: 15,
  },
  overlayContainer: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
    alignSelf: 'stretch',
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
});

export default Card;
<commit_msg>Card's title numberOfLines<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import {
  View,
  StyleSheet,
  Platform,
  Image,
  Text as NativeText,
} from 'react-native';
import fonts from '../config/fonts';
import colors from '../config/colors';
import Text from '../text/Text';
import Divider from '../divider/Divider';
import normalize from '../helpers/normalizeText';
import ViewPropTypes from '../config/ViewPropTypes';
import BackgroundImage from '../config/BackgroundImage';

const Card = props => {
  const {
    children,
    flexDirection,
    containerStyle,
    wrapperStyle,
    imageWrapperStyle,
    title,
    titleStyle,
    titleNumberOfLines,
    featuredTitle,
    featuredTitleStyle,
    featuredSubtitle,
    featuredSubtitleStyle,
    dividerStyle,
    image,
    imageStyle,
    fontFamily,
    imageProps,
    ...attributes
  } = props;

  return (
    <View
      {...attributes}
      style={[
        styles.container,
        image && { padding: 0 },
        containerStyle && containerStyle,
      ]}
    >
      <View
        style={[
          styles.wrapper,
          wrapperStyle && wrapperStyle,
          flexDirection && { flexDirection },
        ]}
      >
        {title === '' ||
          (title &&
            title.length > 0 &&
            <View>
              <Text
                style={[
                  styles.cardTitle,
                  image && styles.imageCardTitle,
                  titleStyle && titleStyle,
                  fontFamily && { fontFamily },
                ]}
                numberOfLines={titleNumberOfLines}
              >
                {title}
              </Text>
              {!image &&
                <Divider
                  style={[styles.divider, dividerStyle && dividerStyle]}
                />}
            </View>)}
        {image &&
          <View style={imageWrapperStyle && imageWrapperStyle}>
            <BackgroundImage
              resizeMode="cover"
              style={[{ width: null, height: 150 }, imageStyle && imageStyle]}
              source={image}
              {...imageProps}
            >
              {(featuredTitle || featuredSubtitle) &&
                <View style={styles.overlayContainer}>
                  {featuredTitle &&
                    <Text
                      style={[
                        styles.featuredTitle,
                        featuredTitleStyle && featuredTitleStyle,
                      ]}
                    >
                      {featuredTitle}
                    </Text>}
                  {featuredSubtitle &&
                    <Text
                      style={[
                        styles.featuredSubtitle,
                        featuredSubtitleStyle && featuredSubtitleStyle,
                      ]}
                    >
                      {featuredSubtitle}
                    </Text>}
                </View>}
            </BackgroundImage>
            <View style={[{ padding: 10 }, wrapperStyle && wrapperStyle]}>
              {children}
            </View>
          </View>}
        {!image && children}
      </View>
    </View>
  );
};

Card.propTypes = {
  children: PropTypes.any,
  flexDirection: PropTypes.string,
  containerStyle: ViewPropTypes.style,
  wrapperStyle: ViewPropTypes.style,
  overlayStyle: ViewPropTypes.style,
  title: PropTypes.string,
  titleStyle: NativeText.propTypes.style,
  featuredTitle: PropTypes.string,
  featuredTitleStyle: Text.propTypes.style,
  featuredSubtitle: PropTypes.string,
  featuredSubtitleStyle: Text.propTypes.style,
  dividerStyle: ViewPropTypes.style,
  image: Image.propTypes.source,
  imageStyle: ViewPropTypes.style,
  imageWrapperStyle: ViewPropTypes.style,
  fontFamily: PropTypes.string,
  imageProps: PropTypes.object,
  titleNumberOfLines: PropTypes.number,
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    borderColor: colors.grey5,
    borderWidth: 1,
    padding: 15,
    margin: 15,
    marginBottom: 0,
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .2)',
        shadowOffset: { height: 0, width: 0 },
        shadowOpacity: 1,
        shadowRadius: 1,
      },
      android: {
        elevation: 1,
      },
    }),
  },
  featuredTitle: {
    fontSize: normalize(18),
    marginBottom: 8,
    color: 'white',
    ...Platform.select({
      ios: {
        fontWeight: '800',
      },
      android: {
        ...fonts.android.black,
      },
    }),
  },
  featuredSubtitle: {
    fontSize: normalize(13),
    marginBottom: 8,
    color: 'white',
    ...Platform.select({
      ios: {
        fontWeight: '400',
      },
      android: {
        ...fonts.android.black,
      },
    }),
  },
  wrapper: {
    backgroundColor: 'transparent',
  },
  divider: {
    marginBottom: 15,
  },
  cardTitle: {
    fontSize: normalize(14),
    ...Platform.select({
      ios: {
        fontWeight: 'bold',
      },
      android: {
        ...fonts.android.black,
      },
    }),
    textAlign: 'center',
    marginBottom: 15,
    color: colors.grey1,
  },
  imageCardTitle: {
    marginTop: 15,
  },
  overlayContainer: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
    alignSelf: 'stretch',
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
});

export default Card;
<|endoftext|>


<commit_before>import { _ } from 'azk';
import { promiseResolve, promiseReject, isPromise } from 'azk/utils/promises';
import { Cli as AzkCli } from 'azk/cli/cli';
import { UI } from 'azk/cli/ui';
import { InvalidCommandError } from 'azk/utils/errors';

export class Cli extends AzkCli {
  invalidCmd(error) {
    this.fail("commands.not_found", error.command);
    this.showUsage();
    return promiseResolve(1);
  }
}

export function cli(args, cwd, ui = UI) {
  var result;
  try {
    var azk_cli = new Cli();
    azk_cli
      // Options
      .route('help', (p, args) => p.help || p['--help'] || _.isEmpty(args))
      .route('version', (p) => p.version || p['--version'])
      // Commands
      .route('agent')
      .route('vm')
      .route('config')
      .route('docker')
      .route('doctor')
      .route('info')
      .route('init')
      .route('scale')
      .route('shell')
      .route('status')
      .route('start')
      .route('restart', (p) => p.restart, 'start.index')
      .route('stop'   , (p) => p.stop   , 'start.index')
      .route('logs')
      .route('help'); // If you do not fall in any other route, the help is called.

    result = azk_cli.run({
      argv: args.slice(2)
    }, {
      ui: ui,
      cwd: process.cwd()
    });
  } catch (e) {
    result = (e instanceof InvalidCommandError) ?
      azk_cli.invalidCmd(e) : promiseReject(e);
  }

  if (isPromise(result)) {
    result
      .then((code) => {
        ui.exit(code ? code : 0);
      })
      .catch((error) => {
        ui.fail(error);
        ui.exit(error.code ? error.code : 127);
      });
  } else {
    ui.exit(result);
  }
}
<commit_msg>[Cli] Fixing not showing help to command `agent` or `vm` withou action<commit_after>import { _ } from 'azk';
import { promiseResolve, promiseReject, isPromise } from 'azk/utils/promises';
import { Cli as AzkCli } from 'azk/cli/cli';
import { UI } from 'azk/cli/ui';
import { InvalidCommandError } from 'azk/utils/errors';

export class Cli extends AzkCli {
  invalidCmd(error) {
    this.fail("commands.not_found", error.command);
    this.showUsage();
    return promiseResolve(1);
  }
}

export function cli(args, cwd, ui = UI) {
  var result;
  try {
    var azk_cli = new Cli();
    azk_cli
      // Options
      .route('help', (p, args) => p.help || p['--help'] || _.isEmpty(args))
      .route('version', (p) => p.version || p['--version'])
      // Commands
      .route('agent', (p, args) => p.vm && /(start|status|stop)/.test(args))
      .route('vm', (p, args) => p.vm && /(ssh|start|status|installed|stop|remove)/.test(args))
      .route('config')
      .route('docker')
      .route('doctor')
      .route('info')
      .route('init')
      .route('scale')
      .route('shell')
      .route('status')
      .route('start')
      .route('restart', (p) => p.restart, 'start.index')
      .route('stop'   , (p) => p.stop   , 'start.index')
      .route('logs')
      .route('help'); // If you do not fall in any other route, the help is called.

    result = azk_cli.run({
      argv: args.slice(2)
    }, {
      ui: ui,
      cwd: process.cwd()
    });
  } catch (e) {
    result = (e instanceof InvalidCommandError) ?
      azk_cli.invalidCmd(e) : promiseReject(e);
  }

  if (isPromise(result)) {
    result
      .then((code) => {
        ui.exit(code ? code : 0);
      })
      .catch((error) => {
        ui.fail(error);
        ui.exit(error.code ? error.code : 127);
      });
  } else {
    ui.exit(result);
  }
}
<|endoftext|>


<commit_before>/* @flow */

import {ConsoleReporter, JSONReporter} from '../reporters/index.js';
import {sortAlpha} from '../util/misc.js';
import {registries, registryNames} from '../registries/index.js';
import * as commands from './commands/index.js';
import * as constants from '../constants.js';
import * as network from '../util/network.js';
import {MessageError} from '../errors.js';
import aliases from './aliases.js';
import Config from '../config.js';
import {hyphenate, camelCase} from '../util/misc.js';

const chalk = require('chalk');
const commander = require('commander');
const fs = require('fs');
const invariant = require('invariant');
const lockfile = require('proper-lockfile');
const loudRejection = require('loud-rejection');
const net = require('net');
const onDeath = require('death');
const path = require('path');
const pkg = require('../../package.json');

loudRejection();

//
const startArgs = process.argv.slice(0, 2);
let args = process.argv.slice(2);

// ignore all arguments after a --
let endArgs = [];
for (let i = 0; i < args.length; i++) {
  const arg = args[i];
  if (arg === '--') {
    endArgs = args.slice(i + 1);
    args = args.slice(0, i);
  }
}

// set global options
commander.version(pkg.version);
commander.usage('[command] [flags]');
commander.option('--offline', 'trigger an error if any required dependencies are not available in local cache');
commander.option('--prefer-offline', 'use network only if dependencies are not available in local cache');
commander.option('--strict-semver');
commander.option('--json', '');
commander.option('--ignore-scripts', "don't run lifecycle scripts");
commander.option('--har', 'save HAR output of network traffic');
commander.option('--ignore-platform', 'ignore platform checks');
commander.option('--ignore-engines', 'ignore engines check');
commander.option('--ignore-optional', '');
commander.option('--force', 'ignore all caches');
commander.option('--no-bin-links', "don't generate bin links when setting up packages");
commander.option('--flat', 'only allow one version of a package');
commander.option('--prod, --production', '');
commander.option('--no-lockfile', "don't read or generate a lockfile");
commander.option('--pure-lockfile', "don't generate a lockfile");
commander.option('--global-folder <path>', '');
commander.option(
  '--modules-folder <path>',
  'rather than installing modules into the node_modules folder relative to the cwd, output them here',
);
commander.option(
  '--cache-folder <path>',
  'specify a custom folder to store the yarn cache',
);
commander.option(
  '--mutex <type>[:specifier]',
  'use a mutex to ensure only one yarn instance is executing',
);
commander.option(
  '--no-emoji',
  'disable emoji in output',
);
commander.option('--proxy <host>', '');
commander.option('--https-proxy <host>', '');
commander.option(
  '--no-progress',
  'disable progress bar',
);

// get command name
let commandName: ?string = args.shift() || '';
let command;

//
const getDocsLink = (name) => `https://yarnpkg.com/en/docs/cli/${name || ''}`;
const getDocsInfo = (name) => 'Visit ' + chalk.bold(getDocsLink(name)) + ' for documentation about this command.';

//
if (commandName === 'help' || commandName === '--help' || commandName === '-h') {
  commandName = 'help';
  if (args.length) {
    const helpCommand = hyphenate(args[0]);
    if (commands[helpCommand]) {
      commander.on('--help', () => console.log('  ' + getDocsInfo(helpCommand) + '\n'));
    }
  } else {
    commander.on('--help', () => {
      console.log('  Commands:\n');
      for (const name of Object.keys(commands).sort(sortAlpha)) {
        if (commands[name].useless) {
          continue;
        }

        console.log(`    - ${hyphenate(name)}`);
      }
      console.log('\n  Run `' + chalk.bold('yarn help COMMAND') + '` for more information on specific commands.');
      console.log('  Visit ' + chalk.bold(getDocsLink()) + ' to learn more about Yarn.\n');
    });
  }
}

// if no args or command name looks like a flag then default to `install`
if (!commandName || commandName[0] === '-') {
  if (commandName) {
    args.unshift(commandName);
  }
  commandName = 'install';
}

// aliases: i -> install
if (commandName && typeof aliases[commandName] === 'string') {
  const alias = aliases[commandName];
  command = {
    run(config: Config, reporter: ConsoleReporter | JSONReporter): Promise<void> {
      throw new MessageError(`Did you mean \`yarn ${alias}\`?`);
    },
  };
}

//
if (commandName === 'help' && args.length) {
  commandName = camelCase(args.shift());
  args.push('--help');
}

//
invariant(commandName, 'Missing command name');
if (!command) {
  const camelised = camelCase(commandName);
  if (camelised) {
    command = commands[camelised];
  }
}

//
if (command && typeof command.setFlags === 'function') {
  command.setFlags(commander);
}

if (commandName === 'help' || args.indexOf('--help') >= 0 || args.indexOf('-h') >= 0) {
  const examples: Array<string> = (command && command.examples) || [];
  if (examples.length) {
    commander.on('--help', () => {
      console.log('  Examples:\n');
      for (const example of examples) {
        console.log(`    $ yarn ${example}`);
      }
      console.log();
    });
  }

  commander.parse(startArgs.concat(args));
  commander.help();
  process.exit(1);
}

//
if (!command) {
  args.unshift(commandName);
  command = commands.run;
}
invariant(command, 'missing command');

// parse flags
commander.parse(startArgs.concat(args));
commander.args = commander.args.concat(endArgs);

//
let Reporter = ConsoleReporter;
if (commander.json) {
  Reporter = JSONReporter;
}
const reporter = new Reporter({
  emoji: commander.emoji && process.stdout.isTTY && process.platform === 'darwin',
  noProgress: commander.noProgress,
});
reporter.initPeakMemoryCounter();

//
const config = new Config(reporter);

// print header
let outputWrapper = true;
if (typeof command.hasWrapper === 'function') {
  outputWrapper = command.hasWrapper(commander, commander.args);
}
if (outputWrapper) {
  reporter.header(commandName, pkg);
}

if (command.noArguments && commander.args.length) {
  reporter.error(reporter.lang('noArguments'));
  reporter.info(getDocsInfo(commandName));
  process.exit(1);
}

//
if (commander.yes) {
  reporter.warn(reporter.lang('yesWarning'));
}

//
if (!commander.offline && network.isOffline()) {
  reporter.warn(reporter.lang('networkWarning'));
}

//
if (command.requireLockfile && !fs.existsSync(path.join(config.cwd, constants.LOCKFILE_FILENAME))) {
  reporter.error(reporter.lang('noRequiredLockfile'));
  process.exit(1);
}

//
const run = (): Promise<void> => {
  invariant(command, 'missing command');
  return command.run(config, reporter, commander, commander.args).then(() => {
    reporter.close();
    if (outputWrapper) {
      reporter.footer(false);
    }
  });
};

//
const runEventuallyWithFile = (mutexFilename: ?string, isFirstTime?: boolean): Promise<void> => {
  return new Promise((ok) => {
    const lockFilename = mutexFilename || path.join(config.cwd, constants.SINGLE_INSTANCE_FILENAME);
    lockfile.lock(lockFilename, {realpath: false}, (err: mixed, release: () => void) => {
      if (err) {
        if (isFirstTime) {
          reporter.warn(reporter.lang('waitingInstance'));
        }
        setTimeout(() => {
          ok(runEventuallyWithFile(mutexFilename, isFirstTime));
        }, 200); // do not starve the CPU
      } else {
        onDeath(() => {
          process.exit(1);
        });
        ok(run().then(release));
      }
    });
  });
};

//
const runEventuallyWithNetwork = (mutexPort: ?string): Promise<void> => {
  return new Promise((ok) => {
    const connectionOptions = {
      port: +mutexPort || constants.SINGLE_INSTANCE_PORT,
    };

    const clients = [];
    const server = net.createServer((client: net$Socket) => {
      clients.push(client);
    });

    server.on('error', () => {
      // another yarnn instance exists, let's connect to it to know when it dies.
      reporter.warn(reporter.lang('waitingInstance'));
      const socket = net.createConnection(connectionOptions);

      socket
        .on('data', () => {
          // the server has informed us he's going to die soon™.
          socket.unref(); // let it die
          process.nextTick(() => {
            ok(runEventuallyWithNetwork(mutexPort));
          });
        })
        .on('error', () => {
          // No server to listen to ? :O let's retry to become the next server then.
          process.nextTick(() => {
            ok(runEventuallyWithNetwork(mutexPort));
          });
        });
    });

    const onServerEnd = (): Promise<void> => {
      clients.forEach((client) => {
        client.write('closing. kthanx, bye.');
      });
      server.close();
      return Promise.resolve();
    };

    // open the server and continue only if succeed.
    server.listen(connectionOptions, () => {
      // ensure the server gets closed properly on SIGNALS.
      onDeath(onServerEnd);

      ok(run().then(onServerEnd));
    });
  });
};

function onUnexpectedError(err: Error) {
  function indent(str: string): string {
    return '\n  ' + str.trim().split('\n').join('\n  ');
  }

  const log = [];
  log.push(`Arguments: ${indent(process.argv.join(' '))}`);
  log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);
  log.push(`Yarn version: ${indent(pkg.version)}`);
  log.push(`Node version: ${indent(process.versions.node)}`);
  log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);

  // add manifests
  for (const registryName of registryNames) {
    const possibleLoc = path.join(config.cwd, registries[registryName].filename);
    const manifest = fs.existsSync(possibleLoc) ? fs.readFileSync(possibleLoc, 'utf8') : 'No manifest';
    log.push(`${registryName} manifest: ${indent(manifest)}`);
  }

  // lockfile
  const lockLoc = path.join(config.cwd, constants.LOCKFILE_FILENAME);
  const lockfile = fs.existsSync(lockLoc) ? fs.readFileSync(lockLoc, 'utf8') : 'No lockfile';
  log.push(`Lockfile: ${indent(lockfile)}`);

  log.push(`Trace: ${indent(err.stack)}`);

  const errorLoc = path.join(config.cwd, 'yarn-error.log');
  fs.writeFileSync(errorLoc, log.join('\n\n') + '\n');

  reporter.error(reporter.lang('unexpectedError', err.message));
  reporter.info(reporter.lang('bugReport', errorLoc));
}

//
config.init({
  binLinks: commander.binLinks,
  modulesFolder: commander.modulesFolder,
  globalFolder: commander.globalFolder,
  cacheFolder: commander.cacheFolder,
  preferOffline: commander.preferOffline,
  captureHar: commander.har,
  ignorePlatform: commander.ignorePlatform,
  ignoreEngines: commander.ignoreEngines,
  ignoreScripts: commander.ignoreScripts,
  offline: commander.preferOffline || commander.offline,
  looseSemver: !commander.strictSemver,
  production: commander.production,
  httpProxy: commander.proxy,
  httpsProxy: commander.httpsProxy,
  commandName,
}).then(() => {
  const exit = () => {
    process.exit(0);
  };

  const mutex: mixed = commander.mutex;
  if (mutex && typeof mutex === 'string') {
    const parts = mutex.split(':');
    const mutexType = parts.shift();
    const mutexSpecifier = parts.join(':');

    if (mutexType === 'file') {
      return runEventuallyWithFile(mutexSpecifier, true).then(exit);
    } else if (mutexType === 'network') {
      return runEventuallyWithNetwork(mutexSpecifier).then(exit);
    } else {
      throw new MessageError(`Unknown single instance type ${mutexType}`);
    }
  } else {
    return run().then(exit);
  }
}).catch((err: Error) => {
  if (err instanceof MessageError) {
    reporter.error(err.message);
  } else {
    onUnexpectedError(err);
  }

  if (commandName) {
    const actualCommandForHelp = commands[commandName] ? commandName : aliases[commandName];
    if (command && actualCommandForHelp) {
      reporter.info(getDocsInfo(actualCommandForHelp));
    }
  }

  process.exit(1);
});
<commit_msg>Include description for --ignore-optional (#1868)<commit_after>/* @flow */

import {ConsoleReporter, JSONReporter} from '../reporters/index.js';
import {sortAlpha} from '../util/misc.js';
import {registries, registryNames} from '../registries/index.js';
import * as commands from './commands/index.js';
import * as constants from '../constants.js';
import * as network from '../util/network.js';
import {MessageError} from '../errors.js';
import aliases from './aliases.js';
import Config from '../config.js';
import {hyphenate, camelCase} from '../util/misc.js';

const chalk = require('chalk');
const commander = require('commander');
const fs = require('fs');
const invariant = require('invariant');
const lockfile = require('proper-lockfile');
const loudRejection = require('loud-rejection');
const net = require('net');
const onDeath = require('death');
const path = require('path');
const pkg = require('../../package.json');

loudRejection();

//
const startArgs = process.argv.slice(0, 2);
let args = process.argv.slice(2);

// ignore all arguments after a --
let endArgs = [];
for (let i = 0; i < args.length; i++) {
  const arg = args[i];
  if (arg === '--') {
    endArgs = args.slice(i + 1);
    args = args.slice(0, i);
  }
}

// set global options
commander.version(pkg.version);
commander.usage('[command] [flags]');
commander.option('--offline', 'trigger an error if any required dependencies are not available in local cache');
commander.option('--prefer-offline', 'use network only if dependencies are not available in local cache');
commander.option('--strict-semver');
commander.option('--json', '');
commander.option('--ignore-scripts', "don't run lifecycle scripts");
commander.option('--har', 'save HAR output of network traffic');
commander.option('--ignore-platform', 'ignore platform checks');
commander.option('--ignore-engines', 'ignore engines check');
commander.option('--ignore-optional', 'ignore optional dependencies');
commander.option('--force', 'ignore all caches');
commander.option('--no-bin-links', "don't generate bin links when setting up packages");
commander.option('--flat', 'only allow one version of a package');
commander.option('--prod, --production', '');
commander.option('--no-lockfile', "don't read or generate a lockfile");
commander.option('--pure-lockfile', "don't generate a lockfile");
commander.option('--global-folder <path>', '');
commander.option(
  '--modules-folder <path>',
  'rather than installing modules into the node_modules folder relative to the cwd, output them here',
);
commander.option(
  '--cache-folder <path>',
  'specify a custom folder to store the yarn cache',
);
commander.option(
  '--mutex <type>[:specifier]',
  'use a mutex to ensure only one yarn instance is executing',
);
commander.option(
  '--no-emoji',
  'disable emoji in output',
);
commander.option('--proxy <host>', '');
commander.option('--https-proxy <host>', '');
commander.option(
  '--no-progress',
  'disable progress bar',
);

// get command name
let commandName: ?string = args.shift() || '';
let command;

//
const getDocsLink = (name) => `https://yarnpkg.com/en/docs/cli/${name || ''}`;
const getDocsInfo = (name) => 'Visit ' + chalk.bold(getDocsLink(name)) + ' for documentation about this command.';

//
if (commandName === 'help' || commandName === '--help' || commandName === '-h') {
  commandName = 'help';
  if (args.length) {
    const helpCommand = hyphenate(args[0]);
    if (commands[helpCommand]) {
      commander.on('--help', () => console.log('  ' + getDocsInfo(helpCommand) + '\n'));
    }
  } else {
    commander.on('--help', () => {
      console.log('  Commands:\n');
      for (const name of Object.keys(commands).sort(sortAlpha)) {
        if (commands[name].useless) {
          continue;
        }

        console.log(`    - ${hyphenate(name)}`);
      }
      console.log('\n  Run `' + chalk.bold('yarn help COMMAND') + '` for more information on specific commands.');
      console.log('  Visit ' + chalk.bold(getDocsLink()) + ' to learn more about Yarn.\n');
    });
  }
}

// if no args or command name looks like a flag then default to `install`
if (!commandName || commandName[0] === '-') {
  if (commandName) {
    args.unshift(commandName);
  }
  commandName = 'install';
}

// aliases: i -> install
if (commandName && typeof aliases[commandName] === 'string') {
  const alias = aliases[commandName];
  command = {
    run(config: Config, reporter: ConsoleReporter | JSONReporter): Promise<void> {
      throw new MessageError(`Did you mean \`yarn ${alias}\`?`);
    },
  };
}

//
if (commandName === 'help' && args.length) {
  commandName = camelCase(args.shift());
  args.push('--help');
}

//
invariant(commandName, 'Missing command name');
if (!command) {
  const camelised = camelCase(commandName);
  if (camelised) {
    command = commands[camelised];
  }
}

//
if (command && typeof command.setFlags === 'function') {
  command.setFlags(commander);
}

if (commandName === 'help' || args.indexOf('--help') >= 0 || args.indexOf('-h') >= 0) {
  const examples: Array<string> = (command && command.examples) || [];
  if (examples.length) {
    commander.on('--help', () => {
      console.log('  Examples:\n');
      for (const example of examples) {
        console.log(`    $ yarn ${example}`);
      }
      console.log();
    });
  }

  commander.parse(startArgs.concat(args));
  commander.help();
  process.exit(1);
}

//
if (!command) {
  args.unshift(commandName);
  command = commands.run;
}
invariant(command, 'missing command');

// parse flags
commander.parse(startArgs.concat(args));
commander.args = commander.args.concat(endArgs);

//
let Reporter = ConsoleReporter;
if (commander.json) {
  Reporter = JSONReporter;
}
const reporter = new Reporter({
  emoji: commander.emoji && process.stdout.isTTY && process.platform === 'darwin',
  noProgress: commander.noProgress,
});
reporter.initPeakMemoryCounter();

//
const config = new Config(reporter);

// print header
let outputWrapper = true;
if (typeof command.hasWrapper === 'function') {
  outputWrapper = command.hasWrapper(commander, commander.args);
}
if (outputWrapper) {
  reporter.header(commandName, pkg);
}

if (command.noArguments && commander.args.length) {
  reporter.error(reporter.lang('noArguments'));
  reporter.info(getDocsInfo(commandName));
  process.exit(1);
}

//
if (commander.yes) {
  reporter.warn(reporter.lang('yesWarning'));
}

//
if (!commander.offline && network.isOffline()) {
  reporter.warn(reporter.lang('networkWarning'));
}

//
if (command.requireLockfile && !fs.existsSync(path.join(config.cwd, constants.LOCKFILE_FILENAME))) {
  reporter.error(reporter.lang('noRequiredLockfile'));
  process.exit(1);
}

//
const run = (): Promise<void> => {
  invariant(command, 'missing command');
  return command.run(config, reporter, commander, commander.args).then(() => {
    reporter.close();
    if (outputWrapper) {
      reporter.footer(false);
    }
  });
};

//
const runEventuallyWithFile = (mutexFilename: ?string, isFirstTime?: boolean): Promise<void> => {
  return new Promise((ok) => {
    const lockFilename = mutexFilename || path.join(config.cwd, constants.SINGLE_INSTANCE_FILENAME);
    lockfile.lock(lockFilename, {realpath: false}, (err: mixed, release: () => void) => {
      if (err) {
        if (isFirstTime) {
          reporter.warn(reporter.lang('waitingInstance'));
        }
        setTimeout(() => {
          ok(runEventuallyWithFile(mutexFilename, isFirstTime));
        }, 200); // do not starve the CPU
      } else {
        onDeath(() => {
          process.exit(1);
        });
        ok(run().then(release));
      }
    });
  });
};

//
const runEventuallyWithNetwork = (mutexPort: ?string): Promise<void> => {
  return new Promise((ok) => {
    const connectionOptions = {
      port: +mutexPort || constants.SINGLE_INSTANCE_PORT,
    };

    const clients = [];
    const server = net.createServer((client: net$Socket) => {
      clients.push(client);
    });

    server.on('error', () => {
      // another yarnn instance exists, let's connect to it to know when it dies.
      reporter.warn(reporter.lang('waitingInstance'));
      const socket = net.createConnection(connectionOptions);

      socket
        .on('data', () => {
          // the server has informed us he's going to die soon™.
          socket.unref(); // let it die
          process.nextTick(() => {
            ok(runEventuallyWithNetwork(mutexPort));
          });
        })
        .on('error', () => {
          // No server to listen to ? :O let's retry to become the next server then.
          process.nextTick(() => {
            ok(runEventuallyWithNetwork(mutexPort));
          });
        });
    });

    const onServerEnd = (): Promise<void> => {
      clients.forEach((client) => {
        client.write('closing. kthanx, bye.');
      });
      server.close();
      return Promise.resolve();
    };

    // open the server and continue only if succeed.
    server.listen(connectionOptions, () => {
      // ensure the server gets closed properly on SIGNALS.
      onDeath(onServerEnd);

      ok(run().then(onServerEnd));
    });
  });
};

function onUnexpectedError(err: Error) {
  function indent(str: string): string {
    return '\n  ' + str.trim().split('\n').join('\n  ');
  }

  const log = [];
  log.push(`Arguments: ${indent(process.argv.join(' '))}`);
  log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);
  log.push(`Yarn version: ${indent(pkg.version)}`);
  log.push(`Node version: ${indent(process.versions.node)}`);
  log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);

  // add manifests
  for (const registryName of registryNames) {
    const possibleLoc = path.join(config.cwd, registries[registryName].filename);
    const manifest = fs.existsSync(possibleLoc) ? fs.readFileSync(possibleLoc, 'utf8') : 'No manifest';
    log.push(`${registryName} manifest: ${indent(manifest)}`);
  }

  // lockfile
  const lockLoc = path.join(config.cwd, constants.LOCKFILE_FILENAME);
  const lockfile = fs.existsSync(lockLoc) ? fs.readFileSync(lockLoc, 'utf8') : 'No lockfile';
  log.push(`Lockfile: ${indent(lockfile)}`);

  log.push(`Trace: ${indent(err.stack)}`);

  const errorLoc = path.join(config.cwd, 'yarn-error.log');
  fs.writeFileSync(errorLoc, log.join('\n\n') + '\n');

  reporter.error(reporter.lang('unexpectedError', err.message));
  reporter.info(reporter.lang('bugReport', errorLoc));
}

//
config.init({
  binLinks: commander.binLinks,
  modulesFolder: commander.modulesFolder,
  globalFolder: commander.globalFolder,
  cacheFolder: commander.cacheFolder,
  preferOffline: commander.preferOffline,
  captureHar: commander.har,
  ignorePlatform: commander.ignorePlatform,
  ignoreEngines: commander.ignoreEngines,
  ignoreScripts: commander.ignoreScripts,
  offline: commander.preferOffline || commander.offline,
  looseSemver: !commander.strictSemver,
  production: commander.production,
  httpProxy: commander.proxy,
  httpsProxy: commander.httpsProxy,
  commandName,
}).then(() => {
  const exit = () => {
    process.exit(0);
  };

  const mutex: mixed = commander.mutex;
  if (mutex && typeof mutex === 'string') {
    const parts = mutex.split(':');
    const mutexType = parts.shift();
    const mutexSpecifier = parts.join(':');

    if (mutexType === 'file') {
      return runEventuallyWithFile(mutexSpecifier, true).then(exit);
    } else if (mutexType === 'network') {
      return runEventuallyWithNetwork(mutexSpecifier).then(exit);
    } else {
      throw new MessageError(`Unknown single instance type ${mutexType}`);
    }
  } else {
    return run().then(exit);
  }
}).catch((err: Error) => {
  if (err instanceof MessageError) {
    reporter.error(err.message);
  } else {
    onUnexpectedError(err);
  }

  if (commandName) {
    const actualCommandForHelp = commands[commandName] ? commandName : aliases[commandName];
    if (command && actualCommandForHelp) {
      reporter.info(getDocsInfo(actualCommandForHelp));
    }
  }

  process.exit(1);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var app = require("commander");
var async = require("async");
var stdin = require("get-stdin");
var trunc = require("lodash.trunc");
var moment = require("moment");
var opn = require("opn");
var api = require("./lib/api");
var getInbox = require("./lib/get-inbox");
var Configstore = require("configstore");
var conf = new Configstore("wunderline", { platform: "web" });
var auth = require("./lib/auth");

function openTask(task) {
  var web = "https://www.wunderlist.com/#/tasks/" + task.id;
  var mac = "wunderlist://tasks/" + task.id;
  if (conf.get("platform") === "mac") return opn(mac);
  opn(web);
}

function openList(list) {
  var web = "https://www.wunderlist.com/#/lists/" + list.id;
  var mac = "wunderlist://lists/" + list.id;
  if (conf.get("platform") === "mac") return opn(mac);
  opn(web);
}

app
  .description("Add a task to your inbox")
  .usage("[task]")
  .option("-l, --list [name]", "Specify a list other than your inbox")
  .option("--starred", "Set the new task as starred")
  .option("--today", "Set the due date to today")
  .option("--tomorrow", "Set the due date to tomorrow")
  .option("--due [date]", "Set a specific due date")
  .option("--note [note]", "Attach a note to the new task")
  .option("--subtask [task]", "Add a subtask to the new task", collect, [])
  .option("-o, --open", "Open Wunderlist on completion")
  .option("-s, --stdin", "Create tasks from stdin")
  .parse(process.argv);

function truncateTitle(title) {
  return trunc(title.trim(), 254);
}

function collect(value, memo) {
  memo.push(value);
  return memo;
}

function getListId(cb) {
  if (!app.list) {
    return getInbox(function(inbox) {
      cb(inbox.id);
    });
  }

  var list = {
    title: app.list.trim()
  };

  api("/lists", function(err, res, body) {
    if (err) process.exit(1);

    var existing = body.filter(function(item) {
      return item.title.toLowerCase().trim() === list.title.toLowerCase();
    });
    if (existing.length > 0) {
      return cb(existing[0].id);
    }
    api.post({ url: "/lists", body: list }, function(err, res, body) {
      if (err) process.exit(1);

      cb(body.id);
    });
  });
}

function main() {
  var dueDate;
  var starred = false;

  if (app.today) {
    dueDate = moment().format("YYYY-MM-DD");
  }

  if (app.tomorrow) {
    dueDate = moment().add(1, "day").format("YYYY-MM-DD");
  }

  if (app.due) {
    if (/\d{4}\-\d{2}\-\d{2}/.test(app.due)) {
      dueDate = app.due;
    } else {
      console.error("Invalid due date!");
      process.exit(1);
    }
  }

  if (app.starred) {
    starred = true;
  }

  if (typeof app.stdin === "undefined") {
    var title = app.args.join(" ");

    if (!title) {
      process.exit(1);
    }

    async.waterfall(
      [
        function(cb) {
          getListId(function(inboxId) {
            cb(null, inboxId);
          });
        },
        function(inboxId, cb) {
          cb(null, {
            title: truncateTitle(title),
            list_id: inboxId,
            due_date: dueDate,
            starred: starred
          });
        },
        function(task, cb) {
          api.post({ url: "/tasks", body: task }, function(err, res, body) {
            if (err || body.error) {
              console.error(JSON.stringify(err || body.error, null, 2));
              process.exit(1);
            }

            cb(null, body);
          });
        },
        function(task, cb) {
          if (app.note) {
            api.post(
              { url: "/notes", body: { task_id: task.id, content: app.note } },
              function(err, res, body) {
                if (err || body.error) {
                  console.error(JSON.stringify(err || body.error, null, 2));
                  process.exit(1);
                }

                cb(null, task);
              }
            );
          } else {
            cb(null, task);
          }
        },
        function(task, cb) {
          if (app.subtask) {
            for (var i = app.subtask.length - 1; i >= 0; i--) {
              api.post(
                {
                  url: "/subtasks",
                  body: {
                    task_id: task.id,
                    title: app.subtask[i],
                    completed: false
                  }
                },
                function(err, res, body) {
                  if (err || body.error) {
                    console.error(JSON.stringify(err || body.error, null, 2));
                    process.exit(1);
                  }

                  cb(null, task);
                }
              );
            }
          } else {
            cb(null, task);
          }
        }
      ],
      function(err, res) {
        if (err) {
          process.exit(1);
        }
        if (app.open) {
          openTask(res);
        }
        process.exit();
      }
    );
  }

  if (app.stdin === true) {
    async.waterfall(
      [
        function(cb) {
          stdin().then(data => {
            var sep = data.indexOf("\r\n") !== -1 ? "\r\n" : "\n";
            var lines = data.trim().split(sep);
            cb(null, lines);
          });
        },
        function(lines, cb) {
          getListId(function(listId) {
            cb(null, listId, lines);
          });
        },
        function(listId, lines, cb) {
          var tasks = lines
            .filter(function(line) {
              return line.trim().length > 0;
            })
            .map(function(line) {
              return {
                title: truncateTitle(line),
                due_date: dueDate,
                list_id: listId,
                starred: starred
              };
            });
          cb(null, tasks);
        }
      ],
      function(err, tasks) {
        if (err) {
          process.exit(1);
        }

        async.each(
          tasks,
          function(task, finished) {
            api.post({ url: "/tasks", body: task }, function(err, res, body) {
              if (err || body.error) {
                console.error(JSON.stringify(err || body.error, null, 2));
                process.exit(1);
              }
              process.stderr.write(".");
              finished();
            });
          },
          function() {
            if (app.open && tasks.length > 0) {
              openList({ id: tasks[0].list_id });
            }

            process.exit();
          }
        );
      }
    );
  }
}

auth(main);
<commit_msg>Use async.eachOfSeries for subtask-requests<commit_after>#!/usr/bin/env node

var app = require("commander");
var async = require("async");
var stdin = require("get-stdin");
var trunc = require("lodash.trunc");
var moment = require("moment");
var opn = require("opn");
var api = require("./lib/api");
var getInbox = require("./lib/get-inbox");
var Configstore = require("configstore");
var conf = new Configstore("wunderline", { platform: "web" });
var auth = require("./lib/auth");

function openTask(task) {
  var web = "https://www.wunderlist.com/#/tasks/" + task.id;
  var mac = "wunderlist://tasks/" + task.id;
  if (conf.get("platform") === "mac") return opn(mac);
  opn(web);
}

function openList(list) {
  var web = "https://www.wunderlist.com/#/lists/" + list.id;
  var mac = "wunderlist://lists/" + list.id;
  if (conf.get("platform") === "mac") return opn(mac);
  opn(web);
}

app
  .description("Add a task to your inbox")
  .usage("[task]")
  .option("-l, --list [name]", "Specify a list other than your inbox")
  .option("--starred", "Set the new task as starred")
  .option("--today", "Set the due date to today")
  .option("--tomorrow", "Set the due date to tomorrow")
  .option("--due [date]", "Set a specific due date")
  .option("--note [note]", "Attach a note to the new task")
  .option("--subtask [task]", "Add a subtask to the new task", collect, [])
  .option("-o, --open", "Open Wunderlist on completion")
  .option("-s, --stdin", "Create tasks from stdin")
  .parse(process.argv);

function truncateTitle(title) {
  return trunc(title.trim(), 254);
}

function collect(value, memo) {
  memo.push(value);
  return memo;
}

function getListId(cb) {
  if (!app.list) {
    return getInbox(function(inbox) {
      cb(inbox.id);
    });
  }

  var list = {
    title: app.list.trim()
  };

  api("/lists", function(err, res, body) {
    if (err) process.exit(1);

    var existing = body.filter(function(item) {
      return item.title.toLowerCase().trim() === list.title.toLowerCase();
    });
    if (existing.length > 0) {
      return cb(existing[0].id);
    }
    api.post({ url: "/lists", body: list }, function(err, res, body) {
      if (err) process.exit(1);

      cb(body.id);
    });
  });
}

function main() {
  var dueDate;
  var starred = false;

  if (app.today) {
    dueDate = moment().format("YYYY-MM-DD");
  }

  if (app.tomorrow) {
    dueDate = moment().add(1, "day").format("YYYY-MM-DD");
  }

  if (app.due) {
    if (/\d{4}\-\d{2}\-\d{2}/.test(app.due)) {
      dueDate = app.due;
    } else {
      console.error("Invalid due date!");
      process.exit(1);
    }
  }

  if (app.starred) {
    starred = true;
  }

  if (typeof app.stdin === "undefined") {
    var title = app.args.join(" ");

    if (!title) {
      process.exit(1);
    }

    async.waterfall(
      [
        function(cb) {
          getListId(function(inboxId) {
            cb(null, inboxId);
          });
        },
        function(inboxId, cb) {
          cb(null, {
            title: truncateTitle(title),
            list_id: inboxId,
            due_date: dueDate,
            starred: starred
          });
        },
        function(task, cb) {
          api.post({ url: "/tasks", body: task }, function(err, res, body) {
            if (err || body.error) {
              console.error(JSON.stringify(err || body.error, null, 2));
              process.exit(1);
            }

            cb(null, body);
          });
        },
        function(task, cb) {
          if (app.note) {
            api.post(
              { url: "/notes", body: { task_id: task.id, content: app.note } },
              function(err, res, body) {
                if (err || body.error) {
                  console.error(JSON.stringify(err || body.error, null, 2));
                  process.exit(1);
                }

                cb(null, task);
              }
            );
          } else {
            cb(null, task);
          }
        },
        function(task, cb) {
          if (app.subtask) {
            async.eachOfSeries(app.subtask, function(
              subtask,
              i,
              subtask_callback
            ) {
              api.post(
                {
                  url: "/subtasks",
                  body: {
                    task_id: task.id,
                    title: subtask,
                    completed: false
                  }
                },
                function(err, res, body) {
                  if (err || body.error) {
                    console.error(JSON.stringify(err || body.error, null, 2));
                    process.exit(1);
                  }
                  subtask_callback(null);
                }
              );
            });
          } else {
            cb(null, task);
          }
        }
      ],
      function(err, res) {
        if (err) {
          process.exit(1);
        }
        if (app.open) {
          openTask(res);
        }
        process.exit();
      }
    );
  }

  if (app.stdin === true) {
    async.waterfall(
      [
        function(cb) {
          stdin().then(data => {
            var sep = data.indexOf("\r\n") !== -1 ? "\r\n" : "\n";
            var lines = data.trim().split(sep);
            cb(null, lines);
          });
        },
        function(lines, cb) {
          getListId(function(listId) {
            cb(null, listId, lines);
          });
        },
        function(listId, lines, cb) {
          var tasks = lines
            .filter(function(line) {
              return line.trim().length > 0;
            })
            .map(function(line) {
              return {
                title: truncateTitle(line),
                due_date: dueDate,
                list_id: listId,
                starred: starred
              };
            });
          cb(null, tasks);
        }
      ],
      function(err, tasks) {
        if (err) {
          process.exit(1);
        }

        async.each(
          tasks,
          function(task, finished) {
            api.post({ url: "/tasks", body: task }, function(err, res, body) {
              if (err || body.error) {
                console.error(JSON.stringify(err || body.error, null, 2));
                process.exit(1);
              }
              process.stderr.write(".");
              finished();
            });
          },
          function() {
            if (app.open && tasks.length > 0) {
              openList({ id: tasks[0].list_id });
            }

            process.exit();
          }
        );
      }
    );
  }
}

auth(main);
<|endoftext|>


<commit_before>var exec = require('cordova/exec');

/**
 * open
 * Open documents with compatible apps
 *
 * @param {String} args File URI
 * @param {Function} [success] Call on success
 * @param {Function} [error] Call on error
 */
exports.open = function(args, success, error) {
  if (!args || arguments.length === 0) return;

  function onSuccess() {
    // invoke optional callback
    if (typeof success === 'function') success();
  }

  function onError() {
    // invoke optional callback
    if (typeof error === 'function') error();
  }
  exec(onSuccess, onError, "BridgeOpen", "open", [args]);
};
<commit_msg>Add jsdoc header<commit_after>/**
 * @title Open - cordova.plugins.bridge.open
 * @overview Open documents with compatible apps.
 * @copyright © 2014 cordova-bridge
 * @license GPLv2
 * @author Carlos Antonio
*/

var exec = require('cordova/exec');

/**
 * open
 *
 * @param {String} args File URI
 * @param {Function} [success] Call on success
 * @param {Function} [error] Call on error
 */
exports.open = function(args, success, error) {
  if (!args || arguments.length === 0) return;

  function onSuccess() {
    // invoke optional callback
    if (typeof success === 'function') success();
  }

  function onError() {
    // invoke optional callback
    if (typeof error === 'function') error();
  }
  exec(onSuccess, onError, "BridgeOpen", "open", [args]);
};
<|endoftext|>