Skip to content

Instantly share code, notes, and snippets.

@lodestone
Forked from chmanie/nvgist.js
Created March 17, 2016 04:42
Show Gist options
  • Save lodestone/8cf5ab7288ee38b439c2 to your computer and use it in GitHub Desktop.
Save lodestone/8cf5ab7288ee38b439c2 to your computer and use it in GitHub Desktop.
backup your nvAlt file to github as gists
// backup your nvAlt file to github as gists
// uses openmeta (https://code.google.com/p/openmeta/)
'use strict';
var ChildProcess = require('child_process');
var gaze = require('gaze');
var GitHubApi = require('github');
var fs = require('fs');
var _ = require('lodash');
var github = new GitHubApi({
// required
version: '3.0.0'
});
github.authenticate({
type: 'oauth',
token: YOUR_ACCESS_TOKEN
});
gaze('*.txt', function(err, watcher) {
this.on('changed', _.debounce(handleFile, 60000));
this.on('added', _.debounce(handleFile, 60000));
});
function handleFile(filepath) {
readTags(filepath, function (tags) {
var filename = filepath.match(/^\/.*\/(.*\..*)$/);
if (filename && filename[1]) filename = filename[1];
var file = fs.readFileSync(filepath).toString();
var lines = file.split('\n');
var description = lines.shift();
var contents = lines.join('\n') || '';
tags = tags.filter(function (tag) {
if (tag.match(/^[a-f0-9]{16,}$/)) return true;
});
if (tags.length) {
return updateGist(tags[0], filename, description, contents, function (err, result) {
if (err) return console.log(err);
console.log('Gist ' + result.id + ' updated!');
});
}
createGist(filename, description, contents, function (err, result) {
if (err) return console.log(err);
addTag(filepath, result.id, function () {
console.log('Gist ' + result.id + ' created!');
});
});
});
}
function createGist(filename, description, contents, cb) {
var gist = {
description: description,
public: false,
files: {}
};
gist.files[filename] = {
content: contents
};
console.log(gist.files);
github.gists.create(gist, cb);
}
function updateGist(id, filename, description, contents, cb) {
var gist = {
id: id,
description: description,
public: false,
files: {}
};
gist.files[filename] = {
content: contents
};
github.gists.edit(gist, cb);
}
function addTag(filepath, tag, cb) {
var openmeta = ChildProcess.spawn('./openmeta', ['-a', tag, '-p', filepath]);
openmeta.stdout.on('data', function () {
cb();
});
}
function readTags(filepath, cb) {
var openmeta = ChildProcess.spawn('./openmeta', ['-t', '-p', filepath]);
openmeta.on('error', function (err) {
console.log(err);
});
openmeta.stderr.on('data', function (data) {
console.log('stdout: ' + data);
});
openmeta.stdout.on('data', function (data) {
data = data.toString();
var tags = data.match(/^(.*)\s\/.*/);
if (tags && tags[1]) return cb(tags[1].split(' '));
return cb([]);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment