'use strict';

var Widget = require('../widget');
var maybeExtendOptionsFromDescriptor = require('./utils/maybe-extend-options-from-descriptor');
var maybeReadSrcdocFile = require('./utils/maybe-read-srcdoc-file');

module.exports = function (options, context) {
  return maybeExtendOptionsFromDescriptor(options)
    .then(function () {
      if (!options.id) {
        throw new Error('missing id');
      }

      return maybeReadSrcdocFile(options);
    })
    .then(function () {
      if (!options.version) {
        return new Widget(options, context).read()
          .then(function (response) {
            response = JSON.parse(response);
            let version = response.sys.version;
            options.version = version;

            return new Widget(options, context).save()
              .then(function (widget) {
                console.log(widget);
              });
          });
      } else {
        return new Widget(options, context).save()
        .then(function (widget) {
          console.log(widget);
        });
      }
    })
    .catch(function (e) {
      console.error(`Failed to update the widget: ${e.message}`);
      process.exit(1);
    });
};

@@ -480,33 +480,32 @@
  () %7B%0A      if (
-!
 options.version)
@@ -526,79 +526,29 @@
 urn 
-new Widget(options, context).read()%0A          .then(function (respon
+options;%0A      %7D el
 se
-)
  %7B%0A 
@@ -558,99 +558,59 @@
     
-    response = JSON.parse(response);%0A            let version = response.sys.version
+return loadCurrentVersion(options, context)
 ;%0A      
     
@@ -609,54 +609,49 @@
     
+%7D%0A
     
-  options.version = version;%0A%0A     
+%7D).then(function (options) %7B%0A
       
- 
 retu
@@ -689,24 +689,16 @@
 .save()%0A
-        
       .t
@@ -729,24 +729,16 @@
         
- 
-       
 console.
@@ -760,55 +760,289 @@
     
+%7D);%0A
     
+%7D)%0A
     
-%7D);%0A          %7D);%0A      %7D else %7B%0A      
+.catch(function (e) %7B%0A      console.error(%60Failed to update the widget: $%7Be.message%7D%60);%0A      process.exit(1);%0A    %7D);%0A%7D;%0A%0A/**%0A * GETs the widget from the server and extends %60options%60 with the%0A * current version.%0A */%0Afunction loadCurrentVersion (options, context) %7B%0A
   re
@@ -1075,27 +1075,23 @@
 ontext).
-save
+read
 ()%0A
-    
     .the
@@ -1094,38 +1094,40 @@
 .then(function (
-widget
+response
 ) %7B%0A          co
@@ -1124,173 +1124,136 @@
     
-    console.log(widget);%0A        %7D);%0A      %7D%0A    %7D)%0A    .catch(function (e) %7B%0A      console.error(%60Failed to update the widget: $%7Be.message%7D%60);%0A      process.exit(1)
+response = JSON.parse(response);%0A      let version = response.sys.version;%0A      options.version = version;%0A      return options
 ;%0A  
@@ -1251,18 +1251,17 @@
 tions;%0A    %7D);%0A%7D
-;
 %0A

Remove code duplication