瀏覽代碼

Provide default content for new files and save them in example config

Benoît Hubert 8 年之前
父節點
當前提交
f0da600720
共有 3 個文件被更改,包括 35 次插入8 次删除
  1. 3 0
      js/ws-forms.js
  2. 14 0
      lib/ExampleStore.js
  3. 18 8
      sandboxApp.js

+ 3 - 0
js/ws-forms.js

@@ -126,6 +126,7 @@
           var filename = this.$input.val();
           var bits = filename.split('.');
           var lastIdx = bits.length - 1;
+          this.cantSubmit = '';
 
           // show warning if no extension has been provided
           if(bits.length < 2) {
@@ -138,6 +139,8 @@
           // show error if provided extension is invalid
           else {
             var ext = (bits[lastIdx]).toLowerCase();
+            console.log(bits);
+
             if( ['html', 'js', 'css'].indexOf( ext ) === -1 ) {
               this.cantSubmit = 'Impossible de valider: extension ' + ext + ' invalide (autorisées: .html/.js/.css)';
             }

+ 14 - 0
lib/ExampleStore.js

@@ -5,6 +5,7 @@ const Promise   = require('bluebird');
 const _         = require('lodash');
 const beautify  = require('json-beautify');
 const fs        = require('fs');
+const path      = require('path');
 
 function ExampleStore(path) {
   this.rootPath = path;
@@ -54,6 +55,19 @@ ExampleStore.prototype.loadExample = function(repo, slug) {
   return exampleConfig;
 };
 
+ExampleStore.prototype.addExampleFile = function(repoSlug, slug, filename) {
+  const repo    = this.getRepo(repoSlug);
+  const example = _.find(repo.examples, { slug });
+  let ext       = path.extname(filename).substr(1);
+  const target  = repo.fullPath + '/' + slug + '/config.json';
+  example[ext].push(filename);
+  console.log('after adding file', _.find(repo.examples, { slug }));
+  const config = _.clone(example);
+  delete config.slug;
+  configJSON = beautify(config, null, 2, 100);
+  return fs.writeFileAsync(target, configJSON);
+};
+
 ExampleStore.prototype.getList = function(path) {
   return _.find(this.repos, { path });
 }

+ 18 - 8
sandboxApp.js

@@ -94,11 +94,11 @@ function checkBodyPropsExist(props) {
   };
 }
 
-function checkFilename(filename) {
+function checkNameAndGetExt(filename) {
   const base = path.basename(filename);
   let ext    = path.extname(filename);
   ext = ext ? ext.toLowerCase().substr(1) : ext;
-  return base && ['html', 'js', 'css'].indexOf( ext ) > -1;
+  return base && ['html', 'js', 'css'].indexOf( ext ) > -1 ? ext : false;
 }
 
 /**
@@ -185,12 +185,19 @@ app.post('/:repoSlug/examples/:exampleSlug/file',
     const re = /^[A-Za-z0-9_\-\.]+$/;
     const targetDir = examplesDir + '/' + repoSlug + '/' + exampleSlug;
     const fullPath = targetDir + '/' + name;
+    const defaultContents = {
+      html: '<!-- ' + name + ' -->',
+      js: '// ' + name,
+      css: '/* ' + name + ' */',
+    }
+    let fileExt;
     if(! re.test(name)) {
       return res.status(400).json('Le paramètre `name` est incorrect: caractères autorisés: lettres, chiffres, _, - et .' );
     }
-    if( ! checkFilename(name)) {
+    if( ! ( fileExt = checkNameAndGetExt( name ) ) ) {
       return res.status(400).json("Le paramètre `name` est incorrect: il doit comporter un nom suivi d'une extension (.html, .js ou .css)" );
     }
+    const fileContent = defaultContents[fileExt];
     fs.statAsync(fullPath)
     // Invert the usual flow of a Promise. fs.stat() fails if file does not exist (which is what we want)
     // Hence .catch() is a success handler and .then() an error handler (has to rethrow)
@@ -202,12 +209,15 @@ app.post('/:repoSlug/examples/:exampleSlug/file',
       if( ! err.message.startsWith('ENOENT') ) {
         throw err;
       }
-      return fs.writeFileAsync(fullPath, '')
-      .then(() => res.json({
-        name,
-        path: fullPath
-      }));
+      return fs.writeFileAsync(fullPath, fileContent);
     })
+    .then(() => exStore.addExampleFile(repoSlug, exampleSlug, name))
+    .then(() => res.json({
+        name,
+        path: fullPath,
+        content: fileContent
+      })
+    )
     .catch(err => {
       const statusCode = err.message.startsWith('Le fichier') ? 409 : 500;
       return res.status(statusCode).send(err.message);