-
Notifications
You must be signed in to change notification settings - Fork 10
/
editor.coffee
252 lines (190 loc) · 6.29 KB
/
editor.coffee
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
Runners = require "./runners"
Actions = require "./actions"
Builder = require "./source/builder"
Packager = require "./packager"
Filetree = require "./models/filetree"
File = require "./models/file"
TokenStorage = require("./lib/token-storage")
{processDirectory} = require "./source/util"
loadedPackage = Observable null
initBuilder = (self) ->
builder = Builder()
# Add editor's metadata
builder.addPostProcessor (pkg) ->
pkg.progenitor =
url: document.location.href
# Add metadata from our config
builder.addPostProcessor (pkg) ->
config = readSourceConfig(pkg)
pkg.config = config
pkg.version = config.version
pkg.entryPoint = config.entryPoint or "main"
pkg.remoteDependencies = config.remoteDependencies
# Attach repo metadata to package
builder.addPostProcessor (pkg) ->
repository = self.repository()
# TODO: Track commit SHA as well
pkg.repository = cleanRepositoryData repository.toJSON()
# Add publish branch
pkg.repository.publishBranch = self.config().publishBranch or repository.publishBranch()
return builder
module.exports = (I={}, self=Model(I)) ->
builder = initBuilder(self)
filetree = Filetree()
notifications = require("notifications")()
{classicError, notify, errors} = notifications
self.extend
classicError: classicError
notify: notify
errors: errors
notifications: notifications
errorCatcher: (e) ->
if e.status and e.statusText
editor.errors ["#{e.status} - #{e.statusText}"]
else if e.stack
editor.errors [e.stack]
else
editor.errors [e]
findRegex: Observable "regex"
repository: Observable()
confirmUnsaved: ->
Promise.resolve()
.then ->
if filetree.hasUnsavedChanges()
throw "Cancelled" unless window.confirm "You will lose unsaved changes in your current branch, continue?"
publish: (message) ->
self.build()
.then (pkg) ->
# If the project defines a custom publish script execute it
# TODO: Security :P
# We'll want to prompt to ask if we can run untrusted code
# though this requires a user taking action to save anyway.
# We can sandbox this with an iframe to mitigate.
publishScript = pkg.distribution._publish
if publishScript
code = require.packageWrapper(pkg, 'return require("./_publish")').replace(/^;/, "return ")
publisher = Function(code)()
else
# Use the editor's default publish script
publisher = require "./_publish"
publisher(pkg, self)
# TODO: Revist docs
load: (repository) ->
repository.latestContent()
.then (results) ->
self.loadPackage
repository: cleanRepositoryData repository.toJSON()
source: processDirectory results
# Build the project, returning a promise that will be fulfilled with
# the `pkg` when complete.
build: ->
data = filetree.data()
builder.build(data)
.then (pkg) ->
config = readSourceConfig(pkg)
dependencies = config.dependencies or {}
Packager.collectDependencies(dependencies)
.then (dependencies) ->
pkg.dependencies = dependencies
return pkg
loadedPackage: loadedPackage
save: (message) ->
self.repository().commitTree
tree: filetree.data()
message: message
dependencies: ->
loadedPackage().dependencies
exploreDependency: (name) ->
loadPackage: (pkg) ->
loadedPackage pkg
filetree.load pkg.source
pkg
loadFiles: (fileData) ->
filetree.load fileData
filetree: ->
filetree
files: ->
filetree.files()
fileAt: (path) ->
self.files().select (file) ->
file.path() is path
.first()
fileContents: (path) ->
self.fileAt(path)?.content()
filesMatching: (expr) ->
self.files().select (file) ->
file.path().match expr
findInFiles: (expr) ->
regexp = new RegExp(expr, "ig")
matches = []
totalMatches = 0
maxMatches = 100
self.files().forEach (file) ->
return if totalMatches >= maxMatches
content = file.content()
while result = regexp.exec(content)
totalMatches += 1
match = result[0]
location = regexp.lastIndex - match.length
line = lineFromPosition(content, location)
matches.push [file, match, line]
return if totalMatches >= maxMatches
return
return matches
writeFile: (path, content) ->
if existingFile = self.fileAt(path)
existingFile.content(content)
return existingFile
else
file = File
path: path
content: content
filetree.files.push(file)
return file
builder: ->
builder
config: ->
readSourceConfig(source: arrayToHash(filetree.data()))
plugin: (pluginJSON) ->
self.include require(pluginJSON)
initGitHubToken: ->
tokenKey = "GITHUB_TOKEN"
if code = window.location.href.match(/\?code=(.*)/)?[1]
fetch("https://hamljr-auth.herokuapp.com/authenticate/#{code}")
.then (response) ->
response.json()
.then (data) ->
if token = data.token
editor.setToken tokenKey, token
.then -> token
else
editor.getToken tokenKey
.then (token) ->
throw "Failed to get authorization from server and no token in local storage" unless token
return token
else
self.getToken tokenKey
.then (token) ->
throw "No token in local storage" unless token
return token
ready: ->
self.initGitHubToken()
.then (token) ->
github.token token
github.api('rate_limit')
.catch console.warn
self.include Runners, Actions, TokenStorage
return self
# Helpers
{readSourceConfig, arrayToHash} = require("./source/util")
pick = (object, keys...) ->
result = {}
keys.forEach (key) ->
if key of object
result[key] = object[key]
return result
cleanRepositoryData = (data) ->
pick data, "branch", "default_branch", "full_name", "homepage", "description", "html_url", "url"
lineFromPosition = (str, pos) ->
lines = str.substr(0, pos).match(/[\n\r]/g)
lines?.length or 0