forked from AurelioDeRosa/upload-files-github.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
101 lines (85 loc) · 2.96 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
'use strict';
var GitHub = require('./github');
var config = {
username: 'cutting-edge-visionaries',
password: '3fc35144f7ea4f69d6b4f1b645f0e83ac4dacbde', // Either your password or an authentication token if two-factor authentication is enabled
auth: 'basic',
repository: 'AryavartaResources',
branchName: 'master'
};
var gitHub = new GitHub(config);
// var reposi = GitHub.getRepo('cutting-edge-visionaries', 'IoT');
console.log(GitHub);
/**
* Reads the content of the file provided. Returns a promise whose resolved value is an object literal containing the
* name (<code>filename</code> property) and the content (<code>content</code> property) of the file.
*
* @param {File} file The file to read
*
* @returns {Promise}
*/
function readFile(file) {
return new Promise(function (resolve, reject) {
var fileReader = new FileReader();
fileReader.addEventListener('load', function (event) {
var content = event.target.result;
// Strip out the information about the mime type of the file and the encoding
// at the beginning of the file (e.g. data:image/gif;base64,).
content = atob(content.replace(/^(.+,)/, ''));
resolve({
filename: file.name,
content: content
});
});
fileReader.addEventListener('error', function (error) {
reject(error);
});
fileReader.readAsDataURL(file);
});
}
/**
* Save the files provided on the repository with the commit title specified. Each file will be saved with
* a different commit.
*
* @param {FileList} files The files to save
* @param {string} commitTitle The commit title
*
* @returns {Promise}
*/
function uploadFiles(files, commitTitle) {
// Creates an array of Promises resolved when the content
// of the file provided is read successfully.
var filesPromises = [].map.call(files, readFile);
return Promise
.all(filesPromises)
.then(function(files) {
return files.reduce(
function(promise, file) {
return promise.then(function() {
// Upload the file on GitHub
return gitHub.saveFile({
repository: gitHub.repository,
branchName: config.branchName,
filename: file.filename,
content: file.content,
commitTitle: commitTitle
});
});
},
Promise.resolve()
);
});
}
document.querySelector('form').addEventListener('submit', function (event) {
event.preventDefault();
var files = document.getElementById('file').files;
var commitTitle = document.getElementById('commit-title').value;
uploadFiles(files, commitTitle)
.then(function() {
alert('Your file has been saved correctly.');
})
.catch(function(err) {
console.error(err);
alert('Something went wrong. Please, try again.');
});
});