Skip to content

Commit

Permalink
refactoring: fileutils
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolaslabbe committed Oct 7, 2016
1 parent 3a2c7ab commit cf6f6f0
Show file tree
Hide file tree
Showing 15 changed files with 42 additions and 150 deletions.
5 changes: 2 additions & 3 deletions src/cli/Builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
cmsData,
FileParser,
config,
fileUtils,
fileAttr,
cmsTemplate,
Page
Expand All @@ -31,7 +30,7 @@ class Builder {
var json = fse.readJsonSync(file.path)
var text = cmsTemplate.template.getTemplate(json.abe_meta.template)

cmsData.source.getDataList(fileUtils.removeLast(json.abe_meta.link), text, json)
cmsData.source.getDataList(path.dirname(json.abe_meta.link), text, json)
.then(() => {
var page = new Page(json.abe_meta.template, text, json, true)
saveHtml(path.join(root, dest + json.abe_meta.link), page.html)
Expand All @@ -45,7 +44,7 @@ class Builder {
var json = fse.readJsonSync(file.path)
var text = cmsTemplate.template.getTemplate(json.abe_meta.template)

cmsData.source.getDataList(fileUtils.removeLast(json.abe_meta.link), text, json)
cmsData.source.getDataList(path.dirname(json.abe_meta.link), text, json)
.then(() => {
var page = new Page(json.abe_meta.template, text, json, true)
saveHtml(path.join(root, dest + json.abe_meta.link), page.html)
Expand Down
2 changes: 1 addition & 1 deletion src/cli/cms/operations/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var create = function(template, pathCreate, name, req, forceJson = {}, duplicate
var templatePath = fileUtils.getTemplatePath(template.replace(config.root, ''))
var filePath = path.join(pathCreate, name)
filePath = coreUtils.slug.clean(filePath)
filePath = fileUtils.getFilePath(filePath)
filePath = path.join(config.root, config.draft.url, filePath.replace(config.root))

if(templatePath !== null && filePath !== null) {
var tplUrl = FileParser.getFileDataFromUrl(filePath)
Expand Down
8 changes: 4 additions & 4 deletions src/cli/cms/operations/save.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export function save(url, tplPath, json = null, text = '', type = '', previousSa
}

if (tplPath.indexOf('.') > -1) {
tplPath = fileUtils.removeExtension(tplPath)
tplPath = tplPath.replace(/\..+$/, '')
}
var tpl = tplPath.replace(config.root, '')

Expand Down Expand Up @@ -112,7 +112,7 @@ export function save(url, tplPath, json = null, text = '', type = '', previousSa
text = cmsTemplate.template.getTemplate(fullTpl)
}

cmsData.source.getDataList(fileUtils.removeLast(tplUrl.publish.link), text, json)
cmsData.source.getDataList(path.dirname(tplUrl.publish.link), text, json)
.then(() => {

json = Hooks.instance.trigger('afterGetDataListOnSave', json)
Expand Down Expand Up @@ -190,7 +190,7 @@ export function saveJsonAndHtml(templateId, obj, html) {
}

export function saveJson(url, json) {
mkdirp.sync(fileUtils.removeLast(url))
mkdirp.sync(path.dirname(url))

if(typeof json.abe_source !== 'undefined' && json.abe_source !== null) {
delete json.abe_source
Expand All @@ -216,7 +216,7 @@ export function saveJson(url, json) {
}

export function saveHtml(url, html) {
mkdirp.sync(fileUtils.removeLast(url))
mkdirp.sync(path.dirname(url))
if(cmsData.fileAttr.test(url) && cmsData.fileAttr.get(url).s !== 'd'){
fileUtils.deleteOlderRevisionByType(cmsData.fileAttr.delete(url), cmsData.fileAttr.get(url).s)
}
Expand Down
2 changes: 1 addition & 1 deletion src/cli/cms/templates/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export function getTemplate (file) {
file = file.replace(path.join(config.root, config.templates.url), '')
file = file.replace(config.root, '')
if (file.indexOf('.') > -1) {
file = fileUtils.removeExtension(file)
file = file.replace(/\..+$/, '')
}
file = path.join(config.root, config.templates.url, file + '.' + config.files.templates.extension)
if(fileUtils.isFile(file)) {
Expand Down
20 changes: 11 additions & 9 deletions src/cli/core/utils/file-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@ export default class FileParser {
var match = (isFolder) ? true : (inversePattern) ? !extensions.test(level[i]) : extensions.test(level[i])
if((type === 'files' || type === null) && match) {

if(fileUtils.isValidFile(level[i])) {
if(level[i].indexOf('.') > -1) {
var extension = /(\.[\s\S]*)/.exec(level[i])[0]
var cleanName = cmsData.fileAttr.delete(level[i])
var cleanNameNoExt = fileUtils.removeExtension(cleanName)
var cleanNameNoExt = cleanName.replace(/\..+$/, '')
var fileData = cmsData.fileAttr.get(level[i])

var date
Expand All @@ -73,7 +73,9 @@ export default class FileParser {
date = stat.mtime
}
var status = fileData.s ? dirName.replace(config.root, '').replace(/^\//, '').split('/')[0] : 'published'
var cleanFilePath = fileUtils.cleanFilePath(pathLevel)


var cleanFilePath = cmsData.fileAttr.delete(pathLevel).replace(config.root, '').replace(/^\/?.+?\//, '')

var fileDate = moment(date)
var duration = moment.duration(moment(fileDate).diff(new Date())).humanize(true)
Expand Down Expand Up @@ -102,7 +104,7 @@ export default class FileParser {
if(!flatten) item['folders'] = []
arr.push(item)
// push current file name into array to check if siblings folder are assets folder
fileCurrentLevel.push(fileUtils.removeExtension(level[i]) + assets)
fileCurrentLevel.push(level[i].replace(/\..+$/, '') + assets)
}
}
if(!fileCurrentLevel.includes(level[i]) && match) {
Expand Down Expand Up @@ -181,7 +183,7 @@ export default class FileParser {

// now check if file for folder exist
Array.prototype.forEach.call(arr, (file) => {
var folderName = fileUtils.removeExtension(file.path) + assets
var folderName = file.path.replace(/\..+$/, '') + assets
try {
var directory = fse.lstatSync(folderName)
if (!directory.isDirectory()) {
Expand Down Expand Up @@ -263,8 +265,8 @@ export default class FileParser {
let extension = config.files.templates.extension
if(typeof url !== 'undefined' && url !== null) {

var dir = fileUtils.removeLast(url).replace(config.root, '')
var filename = fileUtils.filename(url)
var dir = path.dirname(url).replace(config.root, '')
var filename = path.basename(url)
var basePath = dir.replace(config.root, '').split('/')
var link = url.replace(config.root, '')
link = link.replace(/^\//, '').split('/')
Expand All @@ -289,7 +291,7 @@ export default class FileParser {
res.draft.file = filename
res.publish.file = cmsData.fileAttr.delete(filename)
res.publish.link = link
res.json.file = fileUtils.replaceExtension(filename, 'json')
res.json.file = filename.replace(`.${config.files.templates.extension}`, '.json')
res.publish.json = path.join(res.json.dir, cmsData.fileAttr.delete(res.json.file))

// set filename draft/json
Expand Down Expand Up @@ -475,7 +477,7 @@ export default class FileParser {
}

cmsOperations.save.save(
fileUtils.getFilePath(json.abe_meta.link),
path.join(config.root, config.draft.url, json.abe_meta.link.replace(config.root)),
json.abe_meta.template,
json,
'',
Expand Down
115 changes: 0 additions & 115 deletions src/cli/core/utils/file-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,66 +13,6 @@ export default class FileUtils {

constructor() {}

/**
* concatenate strings into a path. Each string being appended with a "/"
* @param {array} array of strings to be concatenated
* @return {string} path as the result of concatenation
*/
static concatPath() {
var cpath = ''
Array.prototype.forEach.call([].slice.call(arguments), (argument) => {
if(cpath !== '') argument = argument.replace(/^\//, '')
if(argument !== '') cpath += argument.replace(/\/$/, '') + '/'
})

cpath = cpath.replace(/\/$/, '')

return cpath
}

/**
* Remove the last segment of the path (ie. /the/path/to => /the/path)
* @param {string} path the path
* @return {string} The path with the last segment removed
*/
static removeLast(pathRemove) {

return pathRemove.substring(0, pathRemove.replace(/\/$/, '').lastIndexOf('/'))
}

/**
* Replace the extension in the path (ie. /the/path/to/file.txt => /the/path/to/file.json)
* @param {string} path The path
* @param {string} ext The extension to put as a replacement
* @return {string} The path with the new extension
*/
static replaceExtension(path, ext) {

return path.substring(0, path.lastIndexOf('.')) + '.' + ext
}

/**
* Remove the extension from the path if any
* @param {string} path The path
* @return {string} The path without extension
*/
static removeExtension(path) {
if (path.lastIndexOf('.') > -1) {
return path.substring(0, path.lastIndexOf('.'))
}
return path
}

/**
* Extract the filename from the path (ie. /the/path/to/file.json => file.json)
* @param {string} path The path
* @return {string} The filename extracted from the path
*/
static filename(path) {

return path.replace(/\/$/, '').substring(path.replace(/\/$/, '').lastIndexOf('/') + 1)
}

/**
* Check if the path given coreespond to an existing file
* @param {string} path The path
Expand All @@ -91,61 +31,6 @@ export default class FileUtils {
return false
}

/**
* Create the directory if it doesn't exist and create the json file
* @param {string} path The path
* @param {string} json The Json data
*/
static writeJson(path, json) {
mkdirp(FileUtils.removeLast(path))
fse.writeJsonSync(path, json, { space: 2, encoding: 'utf-8' })
}

static removeFile(file) {
fse.removeSync(file)
}

/**
* Check if the string given has an extension
* @param {string} fileName the filename to check
* @return {Boolean} Wether the filename has an extension or not
*/
static isValidFile(fileName) {
var dotPosition = fileName.indexOf('.')
if(dotPosition > 0) return true

return false
}

/* TODO: put this method in the right helper */
static cleanTplName(pathClean) {
var cleanTplName = cmsData.fileAttr.delete(pathClean)
cleanTplName = cleanTplName.replace(config.root, '')
cleanTplName = cleanTplName.split('/')
cleanTplName.shift()
return cleanTplName.join('/')
}

/* TODO: Remove this method and replace it with the previous one */
static cleanFilePath(pathClean) {
var cleanFilePath = cmsData.fileAttr.delete(pathClean)
cleanFilePath = cleanFilePath.replace(config.root, '')
cleanFilePath = cleanFilePath.split('/')
cleanFilePath.shift()
return cleanFilePath.join('/')
}


/* TODO: put this method in the right helper */
static getFilePath(pathFile) {
var res = null
if(typeof pathFile !== 'undefined' && pathFile !== null && pathFile !== '') {
res = pathFile.replace(config.root)
res = path.join(config.root, config.draft.url, res)
}
return res
}

/* TODO: refactor this method as Facade method to a method adding a fragment in a path */
static getTemplatePath(pathTemplate) {
if (pathTemplate.indexOf('.') === -1) { // no extension add one
Expand Down
2 changes: 1 addition & 1 deletion src/cli/core/utils/slug.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function clean(str) {
}

function slugify(str) {
str = fileUtils.removeExtension(str)
str = str.replace(/\..+$/, '')
str = slug(str, {separateNumbers: false})
str = `${str}.${config.files.templates.extension}`
return str.toLowerCase()
Expand Down
9 changes: 5 additions & 4 deletions src/server/controllers/editor.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {Promise} from 'es6-promise'
import path from 'path'

import {
cmsData,
Expand Down Expand Up @@ -229,7 +230,7 @@ export function editor(fileName, jsonPath, documentLink) {

text = cmsTemplate.template.getTemplate(fileName)

cmsData.source.getDataList(fileUtils.removeLast(documentLink), text, json, true)
cmsData.source.getDataList(path.dirname(documentLink), text, json, true)
.then(() => {
addSource(text, json, util)

Expand All @@ -242,14 +243,14 @@ export function editor(fileName, jsonPath, documentLink) {
if(typeof json.abe_meta !== 'undefined' && json.abe_meta !== null) {
var tpl = json.abe_meta.template.split('/')
tpl = tpl.pop()
json.abe_meta.cleanTemplate = fileUtils.removeExtension(tpl)
json.abe_meta.cleanTemplate = tpl.replace(/\..+$/, '')
}

if(typeof json.abe_meta !== 'undefined' && json.abe_meta !== null) {
var links = json.abe_meta.link.split('/')
var link = links.pop()
json.abe_meta.cleanName = fileUtils.removeExtension(link)
json.abe_meta.cleanFilename = fileUtils.removeExtension(links.join('/'))
json.abe_meta.cleanName = link.replace(/\..+$/, '')
json.abe_meta.cleanFilename = links.join('/').replace(/\..+$/, '')
}

// HOOKS beforeEditorFormBlocks
Expand Down
5 changes: 3 additions & 2 deletions src/server/helpers/page.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mkdirp from 'mkdirp'
import path from 'path'
import {
cmsData,
FileParser,
Expand All @@ -11,7 +12,7 @@ import {

var page = function (req, res, next) {
var filePath = coreUtils.slug.clean(req.query.filePath)
filePath = fileUtils.getFilePath(filePath)
filePath = path.join(config.root, config.draft.url, filePath.replace(config.root))
var html = (req.query.html) ? true : false
var json = null
var editor = false
Expand Down Expand Up @@ -57,7 +58,7 @@ var page = function (req, res, next) {

if (!editor) {

cmsData.source.getDataList(fileUtils.removeLast(linkPath), text, json)
cmsData.source.getDataList(path.dirname(linkPath), text, json)
.then(() => {
var page = new Page(template, text, json, html)
res.set('Content-Type', 'text/html')
Expand Down
2 changes: 1 addition & 1 deletion src/server/routes/get-delete-logs.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ var route = function(req, res, next){
html += '<ul>'
Array.prototype.forEach.call(files, (item) => {
html += '<li>'
html += '<a href="/abe/delete-logs/' + fileUtils.removeExtension(item.cleanPath) + '">' + item.name + '</a><br />'
html += '<a href="/abe/delete-logs/' + item.cleanPath.replace(/\..+$/, '') + '">' + item.name + '</a><br />'
html += '</li>'
})
html += '</ul>'
Expand Down
2 changes: 1 addition & 1 deletion src/server/routes/get-logs.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ var route = function(req, res, next){
html += '<ul>'
Array.prototype.forEach.call(files, (item) => {
html += '<li>'
html += '<a href="/abe/logs/' + fileUtils.removeExtension(item.cleanPath) + '">' + item.name + '</a><br />'
html += '<a href="/abe/logs/' + item.cleanPath.replace(/\..+$/, '') + '">' + item.name + '</a><br />'
html += '</li>'
})
html += '</ul>'
Expand Down
7 changes: 4 additions & 3 deletions src/server/routes/get-main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import xss from 'xss'
import path from 'path'
import pkg from '../../../package'

import {
Expand Down Expand Up @@ -34,7 +35,7 @@ var route = function(req, res, next) {
if(typeof res._header !== 'undefined' && res._header !== null) return

var templatePath = fileUtils.getTemplatePath(req.params[0])
var filePath = fileUtils.getFilePath(req.query.filePath)
var filePath = path.join(config.root, config.draft.url, req.query.filePath.replace(config.root))
var debugJson = (req.query.debugJson && req.query.debugJson == 'true' ) ? true : false
var debugJsonKey = (req.query.key) ? req.query.key : false
var debugHtml = (req.query.debugHtml && req.query.debugHtml == 'true' ) ? true : false
Expand Down Expand Up @@ -68,15 +69,15 @@ var route = function(req, res, next) {
FileParser.getAssets()

var revisionFilePath = FileParser.changePathEnv(filePath, config.draft.url)
var dirPath = fileUtils.removeLast(revisionFilePath)
var dirPath = path.dirname(revisionFilePath)
var allDraft = FileParser.getFiles(dirPath, true, 99, new RegExp('\\.' + config.files.templates.extension))

allDraft = FileParser.getMetas(allDraft, 'draft')
var breadcrumb = req.params[0].split('/')
manager.file = {
revision: cmsData.revision.getFilesRevision(allDraft, cmsData.fileAttr.delete(revisionFilePath))
,template: breadcrumb
,path: (req.query.filePath) ? fileUtils.cleanTplName(req.query.filePath) : ''
,path: (req.query.filePath) ? path.resolve(req.query.filePath).replace(/^\//, '') : ''
}
if(manager.file.revision.length > 0){
var publishPath = cmsData.fileAttr.delete(manager.file.revision[0].path.replace(new RegExp(`/${config.draft.url}/`), `/${config.publish.url}/`))
Expand Down
Loading

0 comments on commit cf6f6f0

Please sign in to comment.