AmberCli.st 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  1. Smalltalk createPackage: 'AmberCli'!
  2. Object subclass: #AmberCli
  3. instanceVariableNames: ''
  4. package: 'AmberCli'!
  5. !AmberCli commentStamp!
  6. I am the Amber CLI (CommandLine Interface) tool which runs on Node.js.
  7. My responsibility is to start different Amber programs like the FileServer or the Repl.
  8. Which program to start is determined by the first commandline parameters passed to the AmberCli executable.
  9. Use `help` to get a list of all available options.
  10. Any further commandline parameters are passed to the specific program.
  11. ## Commands
  12. New commands can be added by creating a class side method in the `commands` protocol which takes one parameter.
  13. This parameter is an array of all commandline options + values passed on to the program.
  14. Any `camelCaseCommand` is transformed into a commandline parameter of the form `camel-case-command` and vice versa.!
  15. !AmberCli class methodsFor: 'commandline'!
  16. commandLineSwitches
  17. "Collect all methodnames from the 'commands' protocol of the class
  18. and select the ones with only one parameter.
  19. Then remove the ':' at the end of the name.
  20. Additionally all uppercase letters are made lowercase and preceded by a '-'.
  21. Example: fallbackPage: becomes --fallback-page.
  22. Return the Array containing the commandline switches."
  23. | switches |
  24. switches := ((self class methodsInProtocol: 'commands') collect: [ :each | each selector]).
  25. switches := switches select: [ :each | each match: '^[^:]*:$'].
  26. switches :=switches collect: [ :each |
  27. (each allButLast replace: '([A-Z])' with: '-$1') asLowercase].
  28. ^ switches
  29. !
  30. handleArguments: args
  31. | selector |
  32. selector := self selectorForCommandLineSwitch: (args first).
  33. args remove: args first.
  34. self perform: selector withArguments: (Array with: args)
  35. !
  36. selectorForCommandLineSwitch: aSwitch
  37. "Add ':' at the end and replace all occurences of a lowercase letter preceded by a '-' with the Uppercase letter.
  38. Example: fallback-page becomes fallbackPage:.
  39. If no correct selector is found return 'help:'"
  40. | command selector |
  41. (self commandLineSwitches includes: aSwitch)
  42. ifTrue: [ selector := (aSwitch replace: '-[a-z]' with: [ :each | each second asUppercase ]), ':']
  43. ifFalse: [ selector := 'help:' ].
  44. ^ selector
  45. ! !
  46. !AmberCli class methodsFor: 'commands'!
  47. config: args
  48. Configurator new start
  49. !
  50. help: args
  51. Transcript show: 'Available commands'.
  52. self commandLineSwitches do: [ :each | console log: each ]
  53. !
  54. init: args
  55. Initer new start
  56. !
  57. repl: args
  58. ^ Repl new createInterface
  59. !
  60. serve: args
  61. ^ (FileServer createServerWithArguments: args) start
  62. !
  63. tests: arguments
  64. ^ NodeTestRunner runTestSuite
  65. !
  66. version: arguments
  67. ! !
  68. !AmberCli class methodsFor: 'startup'!
  69. main
  70. "Main entry point for Amber applications.
  71. Parses commandline arguments and starts the according subprogram."
  72. | args nodeMinorVersion |
  73. Transcript show: 'Welcome to Amber version ', Smalltalk version, ' (NodeJS ', process versions node, ').'.
  74. nodeMinorVersion := ((process version) tokenize: '.') second asNumber.
  75. nodeMinorVersion < 8 ifTrue: [
  76. Transcript show: 'You are currently using Node.js ', (process version).
  77. Transcript show: 'Required is at least Node.js v0.8.x or greater.'.
  78. ^ -1.
  79. ].
  80. args := process argv.
  81. "Remove the first args which contain the path to the node executable and the script file."
  82. args removeFrom: 1 to: 2.
  83. (args isEmpty)
  84. ifTrue: [self help: nil]
  85. ifFalse: [^self handleArguments: args]
  86. ! !
  87. Object subclass: #BaseFileManipulator
  88. instanceVariableNames: 'path fs'
  89. package: 'AmberCli'!
  90. !BaseFileManipulator methodsFor: 'initialization'!
  91. initialize
  92. super initialize.
  93. path := require value: 'path'.
  94. fs := require value: 'fs'
  95. ! !
  96. !BaseFileManipulator methodsFor: 'private'!
  97. dirname
  98. <return __dirname>
  99. !
  100. rootDirname
  101. ^ path join: self dirname with: '..'
  102. ! !
  103. BaseFileManipulator subclass: #Configurator
  104. instanceVariableNames: ''
  105. package: 'AmberCli'!
  106. !Configurator methodsFor: 'action'!
  107. start
  108. ! !
  109. !Configurator methodsFor: 'initialization'!
  110. initialize
  111. super initialize
  112. ! !
  113. BaseFileManipulator subclass: #FileServer
  114. instanceVariableNames: 'http url host port basePath util username password fallbackPage'
  115. package: 'AmberCli'!
  116. !FileServer commentStamp!
  117. I am the Amber Smalltalk FileServer.
  118. My runtime requirement is a functional Node.js executable.
  119. To start a FileServer instance on port `4000` use the following code:
  120. FileServer new start
  121. A parameterized instance can be created with the following code:
  122. FileServer createServerWithArguments: options
  123. Here, `options` is an array of commandline style strings each followed by a value e.g. `#('--port', '6000', '--host', '0.0.0.0')`.
  124. A list of all available parameters can be printed to the commandline by passing `--help` as parameter.
  125. See the `Options` section for further details on how options are mapped to instance methods.
  126. After startup FileServer checks if the directory layout required by Amber is present and logs a warning on absence.
  127. ## Options
  128. Each option is of the form `--some-option-string` which is transformed into a selector of the format `someOptionString:`.
  129. The trailing `--` gets removed, each `-[a-z]` gets transformed into the according uppercase letter, and a `:` is appended to create a selector which takes a single argument.
  130. Afterwards, the selector gets executed on the `FileServer` instance with the value following in the options array as parameter.
  131. ## Adding new commandline parameters
  132. Adding new commandline parameters to `FileServer` is as easy as adding a new single parameter method to the `accessing` protocol.!
  133. !FileServer methodsFor: 'accessing'!
  134. basePath
  135. ^ basePath ifNil: [self class defaultBasePath]
  136. !
  137. basePath: aString
  138. basePath := aString.
  139. self validateBasePath.
  140. !
  141. fallbackPage
  142. ^ fallbackPage
  143. !
  144. fallbackPage: aString
  145. fallbackPage := aString
  146. !
  147. host
  148. ^ host
  149. !
  150. host: hostname
  151. host := hostname
  152. !
  153. password: aPassword
  154. password := aPassword.
  155. !
  156. port
  157. ^ port
  158. !
  159. port: aNumber
  160. port := aNumber
  161. !
  162. username: aUsername
  163. username := aUsername.
  164. ! !
  165. !FileServer methodsFor: 'initialization'!
  166. checkDirectoryLayout
  167. (fs existsSync: (self withBasePath: 'index.html')) ifFalse: [
  168. console warn: 'Warning: project directory does not contain index.html.'.
  169. console warn: ' You can specify the directory containing index.html with --base-path.'.
  170. console warn: ' You can also specify a page to be served by default,'.
  171. console warn: ' for all paths that do not map to a file, with --fallback-page.'].
  172. !
  173. initialize
  174. super initialize.
  175. http := self require: 'http'.
  176. util := self require: 'util'.
  177. url := self require: 'url'.
  178. host := self class defaultHost.
  179. port := self class defaultPort.
  180. username := nil.
  181. password := nil.
  182. fallbackPage := nil.
  183. ! !
  184. !FileServer methodsFor: 'private'!
  185. base64Decode: aString
  186. <return (new Buffer(aString, 'base64').toString())>
  187. !
  188. isAuthenticated: aRequest
  189. "Basic HTTP Auth: http://stackoverflow.com/a/5957629/293175
  190. and https://gist.github.com/1686663"
  191. | header token auth parts|
  192. (username isNil and: [password isNil]) ifTrue: [^ true].
  193. "get authentication header"
  194. header := (aRequest headers at: 'authorization') ifNil:[''].
  195. (header isEmpty)
  196. ifTrue: [^ false]
  197. ifFalse: [
  198. "get authentication token"
  199. token := (header tokenize: ' ') ifNil:[''].
  200. "convert back from base64"
  201. auth := self base64Decode: (token at: 2).
  202. "split token at colon"
  203. parts := auth tokenize: ':'.
  204. ((username = (parts at: 1)) and: [password = (parts at: 2)])
  205. ifTrue: [^ true]
  206. ifFalse: [^ false]
  207. ].
  208. !
  209. require: aModuleString
  210. "call to the require function"
  211. ^require value: aModuleString
  212. !
  213. validateBasePath
  214. "The basePath must be an existing directory. "
  215. fs stat: self basePath then: [ :err :stat | err
  216. ifNil: [ stat isDirectory ifFalse: [ console warn: 'Warning: --base-path parameter ' , self basePath , ' is not a directory.' ]]
  217. ifNotNil: [ console warn: 'Warning: path at --base-path parameter ' , self basePath , ' does not exist.' ]].
  218. !
  219. withBasePath: aBaseRelativePath
  220. "return a file path which is relative to the basePath."
  221. ^ path join: self basePath with: aBaseRelativePath
  222. !
  223. writeData: data toFileNamed: aFilename
  224. console log: aFilename
  225. ! !
  226. !FileServer methodsFor: 'request handling'!
  227. handleGETRequest: aRequest respondTo: aResponse
  228. | uri filename |
  229. uri := url parse: aRequest url.
  230. filename := path join: self basePath with: uri pathname.
  231. fs exists: filename do: [:aBoolean |
  232. aBoolean
  233. ifFalse: [self respondNotFoundTo: aResponse]
  234. ifTrue: [(fs statSync: filename) isDirectory
  235. ifTrue: [self respondDirectoryNamed: filename from: uri to: aResponse]
  236. ifFalse: [self respondFileNamed: filename to: aResponse]]]
  237. !
  238. handleOPTIONSRequest: aRequest respondTo: aResponse
  239. aResponse writeHead: 200 options: #{'Access-Control-Allow-Origin' -> '*'.
  240. 'Access-Control-Allow-Methods' -> 'GET, PUT, POST, DELETE, OPTIONS'.
  241. 'Access-Control-Allow-Headers' -> 'Content-Type, Accept'.
  242. 'Content-Length' -> 0.
  243. 'Access-Control-Max-Age' -> 10}.
  244. aResponse end
  245. !
  246. handlePUTRequest: aRequest respondTo: aResponse
  247. | file stream |
  248. (self isAuthenticated: aRequest)
  249. ifFalse: [self respondAuthenticationRequiredTo: aResponse. ^ nil].
  250. file := '.', aRequest url.
  251. stream := fs createWriteStream: file.
  252. stream on: 'error' do: [:error |
  253. console warn: 'Error creating WriteStream for file ', file.
  254. console warn: ' Did you forget to create the necessary directory in your project (often /src)?'.
  255. console warn: ' The exact error is: ', error.
  256. self respondNotCreatedTo: aResponse].
  257. stream on: 'close' do: [
  258. self respondCreatedTo: aResponse].
  259. aRequest setEncoding: 'utf8'.
  260. aRequest on: 'data' do: [:data |
  261. stream write: data].
  262. aRequest on: 'end' do: [
  263. stream writable ifTrue: [stream end]]
  264. !
  265. handleRequest: aRequest respondTo: aResponse
  266. aRequest method = 'PUT'
  267. ifTrue: [self handlePUTRequest: aRequest respondTo: aResponse].
  268. aRequest method = 'GET'
  269. ifTrue:[self handleGETRequest: aRequest respondTo: aResponse].
  270. aRequest method = 'OPTIONS'
  271. ifTrue:[self handleOPTIONSRequest: aRequest respondTo: aResponse]
  272. !
  273. respondAuthenticationRequiredTo: aResponse
  274. aResponse
  275. writeHead: 401 options: #{'WWW-Authenticate' -> 'Basic realm="Secured Developer Area"'};
  276. write: '<html><body>Authentication needed</body></html>';
  277. end.
  278. !
  279. respondCreatedTo: aResponse
  280. aResponse
  281. writeHead: 201 options: #{'Content-Type' -> 'text/plain'. 'Access-Control-Allow-Origin' -> '*'};
  282. end.
  283. !
  284. respondDirectoryNamed: aDirname from: aUrl to: aResponse
  285. (aUrl pathname endsWith: '/')
  286. ifTrue: [self respondFileNamed: aDirname, 'index.html' to: aResponse]
  287. ifFalse: [self respondRedirect: aUrl pathname, '/', (aUrl search ifNil: ['']) to: aResponse]
  288. !
  289. respondFileNamed: aFilename to: aResponse
  290. | type filename |
  291. filename := aFilename.
  292. fs readFile: filename do: [:ex :file |
  293. ex notNil
  294. ifTrue: [
  295. console log: filename, ' does not exist'.
  296. self respondNotFoundTo: aResponse]
  297. ifFalse: [
  298. type := self class mimeTypeFor: filename.
  299. type = 'application/javascript'
  300. ifTrue: [ type:=type,';charset=utf-8' ].
  301. aResponse
  302. writeHead: 200 options: #{'Content-Type' -> type};
  303. write: file encoding: 'binary';
  304. end]]
  305. !
  306. respondInternalErrorTo: aResponse
  307. aResponse
  308. writeHead: 500 options: #{'Content-Type' -> 'text/plain'};
  309. write: '500 Internal server error';
  310. end
  311. !
  312. respondNotCreatedTo: aResponse
  313. aResponse
  314. writeHead: 400 options: #{'Content-Type' -> 'text/plain'};
  315. write: 'File could not be created. Did you forget to create the src directory on the server?';
  316. end.
  317. !
  318. respondNotFoundTo: aResponse
  319. self fallbackPage isNil ifFalse: [^self respondFileNamed: self fallbackPage to: aResponse].
  320. aResponse
  321. writeHead: 404 options: #{'Content-Type' -> 'text/html'};
  322. write: '<html><body><p>404 Not found</p>';
  323. write: '<p>Did you forget to put an index.html file into the directory which is served by "bin/amber serve"? To solve this you can:<ul>';
  324. write: '<li>create an index.html in the served directory.</li>';
  325. write: '<li>can also specify the location of a page to be served whenever path does not resolve to a file with the "--fallback-page" option.</li>';
  326. write: '<li>change the directory to be served with the "--base-path" option.</li>';
  327. write: '</ul></p></body></html>';
  328. end
  329. !
  330. respondOKTo: aResponse
  331. aResponse
  332. writeHead: 200 options: #{'Content-Type' -> 'text/plain'. 'Access-Control-Allow-Origin' -> '*'};
  333. end.
  334. !
  335. respondRedirect: aString to: aResponse
  336. aResponse
  337. writeHead: 303 options: #{'Location' -> aString};
  338. end.
  339. ! !
  340. !FileServer methodsFor: 'starting'!
  341. start
  342. "Checks if required directory layout is present (issue warning if not).
  343. Afterwards start the server."
  344. self checkDirectoryLayout.
  345. (http createServer: [:request :response |
  346. self handleRequest: request respondTo: response])
  347. on: 'error' do: [:error | console log: 'Error starting server: ', error];
  348. on: 'listening' do: [console log: 'Starting file server on http://', self host, ':', self port asString];
  349. listen: self port host: self host.
  350. !
  351. startOn: aPort
  352. self port: aPort.
  353. self start
  354. ! !
  355. FileServer class instanceVariableNames: 'mimeTypes'!
  356. !FileServer class methodsFor: 'accessing'!
  357. commandLineSwitches
  358. "Collect all methodnames from the 'accessing' protocol
  359. and select the ones with only one parameter.
  360. Then remove the ':' at the end of the name
  361. and add a '--' at the beginning.
  362. Additionally all uppercase letters are made lowercase and preceded by a '-'.
  363. Example: fallbackPage: becomes --fallback-page.
  364. Return the Array containing the commandline switches."
  365. | switches |
  366. switches := ((self methodsInProtocol: 'accessing') collect: [ :each | each selector]).
  367. switches := switches select: [ :each | each match: '^[^:]*:$'].
  368. switches :=switches collect: [ :each |
  369. (each allButLast replace: '([A-Z])' with: '-$1') asLowercase replace: '^([a-z])' with: '--$1' ].
  370. ^ switches
  371. !
  372. defaultBasePath
  373. ^ './'
  374. !
  375. defaultHost
  376. ^ '127.0.0.1'
  377. !
  378. defaultMimeTypes
  379. ^ #{
  380. '%' -> 'application/x-trash'.
  381. '323' -> 'text/h323'.
  382. 'abw' -> 'application/x-abiword'.
  383. 'ai' -> 'application/postscript'.
  384. 'aif' -> 'audio/x-aiff'.
  385. 'aifc' -> 'audio/x-aiff'.
  386. 'aiff' -> 'audio/x-aiff'.
  387. 'alc' -> 'chemical/x-alchemy'.
  388. 'art' -> 'image/x-jg'.
  389. 'asc' -> 'text/plain'.
  390. 'asf' -> 'video/x-ms-asf'.
  391. 'asn' -> 'chemical/x-ncbi-asn1-spec'.
  392. 'aso' -> 'chemical/x-ncbi-asn1-binary'.
  393. 'asx' -> 'video/x-ms-asf'.
  394. 'au' -> 'audio/basic'.
  395. 'avi' -> 'video/x-msvideo'.
  396. 'b' -> 'chemical/x-molconn-Z'.
  397. 'bak' -> 'application/x-trash'.
  398. 'bat' -> 'application/x-msdos-program'.
  399. 'bcpio' -> 'application/x-bcpio'.
  400. 'bib' -> 'text/x-bibtex'.
  401. 'bin' -> 'application/octet-stream'.
  402. 'bmp' -> 'image/x-ms-bmp'.
  403. 'book' -> 'application/x-maker'.
  404. 'bsd' -> 'chemical/x-crossfire'.
  405. 'c' -> 'text/x-csrc'.
  406. 'c++' -> 'text/x-c++src'.
  407. 'c3d' -> 'chemical/x-chem3d'.
  408. 'cac' -> 'chemical/x-cache'.
  409. 'cache' -> 'chemical/x-cache'.
  410. 'cascii' -> 'chemical/x-cactvs-binary'.
  411. 'cat' -> 'application/vnd.ms-pki.seccat'.
  412. 'cbin' -> 'chemical/x-cactvs-binary'.
  413. 'cc' -> 'text/x-c++src'.
  414. 'cdf' -> 'application/x-cdf'.
  415. 'cdr' -> 'image/x-coreldraw'.
  416. 'cdt' -> 'image/x-coreldrawtemplate'.
  417. 'cdx' -> 'chemical/x-cdx'.
  418. 'cdy' -> 'application/vnd.cinderella'.
  419. 'cef' -> 'chemical/x-cxf'.
  420. 'cer' -> 'chemical/x-cerius'.
  421. 'chm' -> 'chemical/x-chemdraw'.
  422. 'chrt' -> 'application/x-kchart'.
  423. 'cif' -> 'chemical/x-cif'.
  424. 'class' -> 'application/java-vm'.
  425. 'cls' -> 'text/x-tex'.
  426. 'cmdf' -> 'chemical/x-cmdf'.
  427. 'cml' -> 'chemical/x-cml'.
  428. 'cod' -> 'application/vnd.rim.cod'.
  429. 'com' -> 'application/x-msdos-program'.
  430. 'cpa' -> 'chemical/x-compass'.
  431. 'cpio' -> 'application/x-cpio'.
  432. 'cpp' -> 'text/x-c++src'.
  433. 'cpt' -> 'image/x-corelphotopaint'.
  434. 'crl' -> 'application/x-pkcs7-crl'.
  435. 'crt' -> 'application/x-x509-ca-cert'.
  436. 'csf' -> 'chemical/x-cache-csf'.
  437. 'csh' -> 'text/x-csh'.
  438. 'csm' -> 'chemical/x-csml'.
  439. 'csml' -> 'chemical/x-csml'.
  440. 'css' -> 'text/css'.
  441. 'csv' -> 'text/comma-separated-values'.
  442. 'ctab' -> 'chemical/x-cactvs-binary'.
  443. 'ctx' -> 'chemical/x-ctx'.
  444. 'cu' -> 'application/cu-seeme'.
  445. 'cub' -> 'chemical/x-gaussian-cube'.
  446. 'cxf' -> 'chemical/x-cxf'.
  447. 'cxx' -> 'text/x-c++src'.
  448. 'dat' -> 'chemical/x-mopac-input'.
  449. 'dcr' -> 'application/x-director'.
  450. 'deb' -> 'application/x-debian-package'.
  451. 'dif' -> 'video/dv'.
  452. 'diff' -> 'text/plain'.
  453. 'dir' -> 'application/x-director'.
  454. 'djv' -> 'image/vnd.djvu'.
  455. 'djvu' -> 'image/vnd.djvu'.
  456. 'dl' -> 'video/dl'.
  457. 'dll' -> 'application/x-msdos-program'.
  458. 'dmg' -> 'application/x-apple-diskimage'.
  459. 'dms' -> 'application/x-dms'.
  460. 'doc' -> 'application/msword'.
  461. 'dot' -> 'application/msword'.
  462. 'dv' -> 'video/dv'.
  463. 'dvi' -> 'application/x-dvi'.
  464. 'dx' -> 'chemical/x-jcamp-dx'.
  465. 'dxr' -> 'application/x-director'.
  466. 'emb' -> 'chemical/x-embl-dl-nucleotide'.
  467. 'embl' -> 'chemical/x-embl-dl-nucleotide'.
  468. 'ent' -> 'chemical/x-pdb'.
  469. 'eps' -> 'application/postscript'.
  470. 'etx' -> 'text/x-setext'.
  471. 'exe' -> 'application/x-msdos-program'.
  472. 'ez' -> 'application/andrew-inset'.
  473. 'fb' -> 'application/x-maker'.
  474. 'fbdoc' -> 'application/x-maker'.
  475. 'fch' -> 'chemical/x-gaussian-checkpoint'.
  476. 'fchk' -> 'chemical/x-gaussian-checkpoint'.
  477. 'fig' -> 'application/x-xfig'.
  478. 'flac' -> 'application/x-flac'.
  479. 'fli' -> 'video/fli'.
  480. 'fm' -> 'application/x-maker'.
  481. 'frame' -> 'application/x-maker'.
  482. 'frm' -> 'application/x-maker'.
  483. 'gal' -> 'chemical/x-gaussian-log'.
  484. 'gam' -> 'chemical/x-gamess-input'.
  485. 'gamin' -> 'chemical/x-gamess-input'.
  486. 'gau' -> 'chemical/x-gaussian-input'.
  487. 'gcd' -> 'text/x-pcs-gcd'.
  488. 'gcf' -> 'application/x-graphing-calculator'.
  489. 'gcg' -> 'chemical/x-gcg8-sequence'.
  490. 'gen' -> 'chemical/x-genbank'.
  491. 'gf' -> 'application/x-tex-gf'.
  492. 'gif' -> 'image/gif'.
  493. 'gjc' -> 'chemical/x-gaussian-input'.
  494. 'gjf' -> 'chemical/x-gaussian-input'.
  495. 'gl' -> 'video/gl'.
  496. 'gnumeric' -> 'application/x-gnumeric'.
  497. 'gpt' -> 'chemical/x-mopac-graph'.
  498. 'gsf' -> 'application/x-font'.
  499. 'gsm' -> 'audio/x-gsm'.
  500. 'gtar' -> 'application/x-gtar'.
  501. 'h' -> 'text/x-chdr'.
  502. 'h++' -> 'text/x-c++hdr'.
  503. 'hdf' -> 'application/x-hdf'.
  504. 'hh' -> 'text/x-c++hdr'.
  505. 'hin' -> 'chemical/x-hin'.
  506. 'hpp' -> 'text/x-c++hdr'.
  507. 'hqx' -> 'application/mac-binhex40'.
  508. 'hs' -> 'text/x-haskell'.
  509. 'hta' -> 'application/hta'.
  510. 'htc' -> 'text/x-component'.
  511. 'htm' -> 'text/html'.
  512. 'html' -> 'text/html'.
  513. 'hxx' -> 'text/x-c++hdr'.
  514. 'ica' -> 'application/x-ica'.
  515. 'ice' -> 'x-conference/x-cooltalk'.
  516. 'ico' -> 'image/x-icon'.
  517. 'ics' -> 'text/calendar'.
  518. 'icz' -> 'text/calendar'.
  519. 'ief' -> 'image/ief'.
  520. 'iges' -> 'model/iges'.
  521. 'igs' -> 'model/iges'.
  522. 'iii' -> 'application/x-iphone'.
  523. 'inp' -> 'chemical/x-gamess-input'.
  524. 'ins' -> 'application/x-internet-signup'.
  525. 'iso' -> 'application/x-iso9660-image'.
  526. 'isp' -> 'application/x-internet-signup'.
  527. 'ist' -> 'chemical/x-isostar'.
  528. 'istr' -> 'chemical/x-isostar'.
  529. 'jad' -> 'text/vnd.sun.j2me.app-descriptor'.
  530. 'jar' -> 'application/java-archive'.
  531. 'java' -> 'text/x-java'.
  532. 'jdx' -> 'chemical/x-jcamp-dx'.
  533. 'jmz' -> 'application/x-jmol'.
  534. 'jng' -> 'image/x-jng'.
  535. 'jnlp' -> 'application/x-java-jnlp-file'.
  536. 'jpe' -> 'image/jpeg'.
  537. 'jpeg' -> 'image/jpeg'.
  538. 'jpg' -> 'image/jpeg'.
  539. 'js' -> 'application/javascript'.
  540. 'kar' -> 'audio/midi'.
  541. 'key' -> 'application/pgp-keys'.
  542. 'kil' -> 'application/x-killustrator'.
  543. 'kin' -> 'chemical/x-kinemage'.
  544. 'kpr' -> 'application/x-kpresenter'.
  545. 'kpt' -> 'application/x-kpresenter'.
  546. 'ksp' -> 'application/x-kspread'.
  547. 'kwd' -> 'application/x-kword'.
  548. 'kwt' -> 'application/x-kword'.
  549. 'latex' -> 'application/x-latex'.
  550. 'lha' -> 'application/x-lha'.
  551. 'lhs' -> 'text/x-literate-haskell'.
  552. 'lsf' -> 'video/x-la-asf'.
  553. 'lsx' -> 'video/x-la-asf'.
  554. 'ltx' -> 'text/x-tex'.
  555. 'lzh' -> 'application/x-lzh'.
  556. 'lzx' -> 'application/x-lzx'.
  557. 'm3u' -> 'audio/x-mpegurl'.
  558. 'm4a' -> 'audio/mpeg'.
  559. 'maker' -> 'application/x-maker'.
  560. 'man' -> 'application/x-troff-man'.
  561. 'mcif' -> 'chemical/x-mmcif'.
  562. 'mcm' -> 'chemical/x-macmolecule'.
  563. 'mdb' -> 'application/msaccess'.
  564. 'me' -> 'application/x-troff-me'.
  565. 'mesh' -> 'model/mesh'.
  566. 'mid' -> 'audio/midi'.
  567. 'midi' -> 'audio/midi'.
  568. 'mif' -> 'application/x-mif'.
  569. 'mm' -> 'application/x-freemind'.
  570. 'mmd' -> 'chemical/x-macromodel-input'.
  571. 'mmf' -> 'application/vnd.smaf'.
  572. 'mml' -> 'text/mathml'.
  573. 'mmod' -> 'chemical/x-macromodel-input'.
  574. 'mng' -> 'video/x-mng'.
  575. 'moc' -> 'text/x-moc'.
  576. 'mol' -> 'chemical/x-mdl-molfile'.
  577. 'mol2' -> 'chemical/x-mol2'.
  578. 'moo' -> 'chemical/x-mopac-out'.
  579. 'mop' -> 'chemical/x-mopac-input'.
  580. 'mopcrt' -> 'chemical/x-mopac-input'.
  581. 'mov' -> 'video/quicktime'.
  582. 'movie' -> 'video/x-sgi-movie'.
  583. 'mp2' -> 'audio/mpeg'.
  584. 'mp3' -> 'audio/mpeg'.
  585. 'mp4' -> 'video/mp4'.
  586. 'mpc' -> 'chemical/x-mopac-input'.
  587. 'mpe' -> 'video/mpeg'.
  588. 'mpeg' -> 'video/mpeg'.
  589. 'mpega' -> 'audio/mpeg'.
  590. 'mpg' -> 'video/mpeg'.
  591. 'mpga' -> 'audio/mpeg'.
  592. 'ms' -> 'application/x-troff-ms'.
  593. 'msh' -> 'model/mesh'.
  594. 'msi' -> 'application/x-msi'.
  595. 'mvb' -> 'chemical/x-mopac-vib'.
  596. 'mxu' -> 'video/vnd.mpegurl'.
  597. 'nb' -> 'application/mathematica'.
  598. 'nc' -> 'application/x-netcdf'.
  599. 'nwc' -> 'application/x-nwc'.
  600. 'o' -> 'application/x-object'.
  601. 'oda' -> 'application/oda'.
  602. 'odb' -> 'application/vnd.oasis.opendocument.database'.
  603. 'odc' -> 'application/vnd.oasis.opendocument.chart'.
  604. 'odf' -> 'application/vnd.oasis.opendocument.formula'.
  605. 'odg' -> 'application/vnd.oasis.opendocument.graphics'.
  606. 'odi' -> 'application/vnd.oasis.opendocument.image'.
  607. 'odm' -> 'application/vnd.oasis.opendocument.text-master'.
  608. 'odp' -> 'application/vnd.oasis.opendocument.presentation'.
  609. 'ods' -> 'application/vnd.oasis.opendocument.spreadsheet'.
  610. 'odt' -> 'application/vnd.oasis.opendocument.text'.
  611. 'ogg' -> 'application/ogg'.
  612. 'old' -> 'application/x-trash'.
  613. 'oth' -> 'application/vnd.oasis.opendocument.text-web'.
  614. 'oza' -> 'application/x-oz-application'.
  615. 'p' -> 'text/x-pascal'.
  616. 'p7r' -> 'application/x-pkcs7-certreqresp'.
  617. 'pac' -> 'application/x-ns-proxy-autoconfig'.
  618. 'pas' -> 'text/x-pascal'.
  619. 'pat' -> 'image/x-coreldrawpattern'.
  620. 'pbm' -> 'image/x-portable-bitmap'.
  621. 'pcf' -> 'application/x-font'.
  622. 'pcf.Z' -> 'application/x-font'.
  623. 'pcx' -> 'image/pcx'.
  624. 'pdb' -> 'chemical/x-pdb'.
  625. 'pdf' -> 'application/pdf'.
  626. 'pfa' -> 'application/x-font'.
  627. 'pfb' -> 'application/x-font'.
  628. 'pgm' -> 'image/x-portable-graymap'.
  629. 'pgn' -> 'application/x-chess-pgn'.
  630. 'pgp' -> 'application/pgp-signature'.
  631. 'pk' -> 'application/x-tex-pk'.
  632. 'pl' -> 'text/x-perl'.
  633. 'pls' -> 'audio/x-scpls'.
  634. 'pm' -> 'text/x-perl'.
  635. 'png' -> 'image/png'.
  636. 'pnm' -> 'image/x-portable-anymap'.
  637. 'pot' -> 'text/plain'.
  638. 'ppm' -> 'image/x-portable-pixmap'.
  639. 'pps' -> 'application/vnd.ms-powerpoint'.
  640. 'ppt' -> 'application/vnd.ms-powerpoint'.
  641. 'prf' -> 'application/pics-rules'.
  642. 'prt' -> 'chemical/x-ncbi-asn1-ascii'.
  643. 'ps' -> 'application/postscript'.
  644. 'psd' -> 'image/x-photoshop'.
  645. 'psp' -> 'text/x-psp'.
  646. 'py' -> 'text/x-python'.
  647. 'pyc' -> 'application/x-python-code'.
  648. 'pyo' -> 'application/x-python-code'.
  649. 'qt' -> 'video/quicktime'.
  650. 'qtl' -> 'application/x-quicktimeplayer'.
  651. 'ra' -> 'audio/x-realaudio'.
  652. 'ram' -> 'audio/x-pn-realaudio'.
  653. 'rar' -> 'application/rar'.
  654. 'ras' -> 'image/x-cmu-raster'.
  655. 'rd' -> 'chemical/x-mdl-rdfile'.
  656. 'rdf' -> 'application/rdf+xml'.
  657. 'rgb' -> 'image/x-rgb'.
  658. 'rm' -> 'audio/x-pn-realaudio'.
  659. 'roff' -> 'application/x-troff'.
  660. 'ros' -> 'chemical/x-rosdal'.
  661. 'rpm' -> 'application/x-redhat-package-manager'.
  662. 'rss' -> 'application/rss+xml'.
  663. 'rtf' -> 'text/rtf'.
  664. 'rtx' -> 'text/richtext'.
  665. 'rxn' -> 'chemical/x-mdl-rxnfile'.
  666. 'sct' -> 'text/scriptlet'.
  667. 'sd' -> 'chemical/x-mdl-sdfile'.
  668. 'sd2' -> 'audio/x-sd2'.
  669. 'sda' -> 'application/vnd.stardivision.draw'.
  670. 'sdc' -> 'application/vnd.stardivision.calc'.
  671. 'sdd' -> 'application/vnd.stardivision.impress'.
  672. 'sdf' -> 'chemical/x-mdl-sdfile'.
  673. 'sdp' -> 'application/vnd.stardivision.impress'.
  674. 'sdw' -> 'application/vnd.stardivision.writer'.
  675. 'ser' -> 'application/java-serialized-object'.
  676. 'sgf' -> 'application/x-go-sgf'.
  677. 'sgl' -> 'application/vnd.stardivision.writer-global'.
  678. 'sh' -> 'text/x-sh'.
  679. 'shar' -> 'application/x-shar'.
  680. 'shtml' -> 'text/html'.
  681. 'sid' -> 'audio/prs.sid'.
  682. 'sik' -> 'application/x-trash'.
  683. 'silo' -> 'model/mesh'.
  684. 'sis' -> 'application/vnd.symbian.install'.
  685. 'sit' -> 'application/x-stuffit'.
  686. 'skd' -> 'application/x-koan'.
  687. 'skm' -> 'application/x-koan'.
  688. 'skp' -> 'application/x-koan'.
  689. 'skt' -> 'application/x-koan'.
  690. 'smf' -> 'application/vnd.stardivision.math'.
  691. 'smi' -> 'application/smil'.
  692. 'smil' -> 'application/smil'.
  693. 'snd' -> 'audio/basic'.
  694. 'spc' -> 'chemical/x-galactic-spc'.
  695. 'spl' -> 'application/x-futuresplash'.
  696. 'src' -> 'application/x-wais-source'.
  697. 'stc' -> 'application/vnd.sun.xml.calc.template'.
  698. 'std' -> 'application/vnd.sun.xml.draw.template'.
  699. 'sti' -> 'application/vnd.sun.xml.impress.template'.
  700. 'stl' -> 'application/vnd.ms-pki.stl'.
  701. 'stw' -> 'application/vnd.sun.xml.writer.template'.
  702. 'sty' -> 'text/x-tex'.
  703. 'sv4cpio' -> 'application/x-sv4cpio'.
  704. 'sv4crc' -> 'application/x-sv4crc'.
  705. 'svg' -> 'image/svg+xml'.
  706. 'svgz' -> 'image/svg+xml'.
  707. 'sw' -> 'chemical/x-swissprot'.
  708. 'swf' -> 'application/x-shockwave-flash'.
  709. 'swfl' -> 'application/x-shockwave-flash'.
  710. 'sxc' -> 'application/vnd.sun.xml.calc'.
  711. 'sxd' -> 'application/vnd.sun.xml.draw'.
  712. 'sxg' -> 'application/vnd.sun.xml.writer.global'.
  713. 'sxi' -> 'application/vnd.sun.xml.impress'.
  714. 'sxm' -> 'application/vnd.sun.xml.math'.
  715. 'sxw' -> 'application/vnd.sun.xml.writer'.
  716. 't' -> 'application/x-troff'.
  717. 'tar' -> 'application/x-tar'.
  718. 'taz' -> 'application/x-gtar'.
  719. 'tcl' -> 'text/x-tcl'.
  720. 'tex' -> 'text/x-tex'.
  721. 'texi' -> 'application/x-texinfo'.
  722. 'texinfo' -> 'application/x-texinfo'.
  723. 'text' -> 'text/plain'.
  724. 'tgf' -> 'chemical/x-mdl-tgf'.
  725. 'tgz' -> 'application/x-gtar'.
  726. 'tif' -> 'image/tiff'.
  727. 'tiff' -> 'image/tiff'.
  728. 'tk' -> 'text/x-tcl'.
  729. 'tm' -> 'text/texmacs'.
  730. 'torrent' -> 'application/x-bittorrent'.
  731. 'tr' -> 'application/x-troff'.
  732. 'ts' -> 'text/texmacs'.
  733. 'tsp' -> 'application/dsptype'.
  734. 'tsv' -> 'text/tab-separated-values'.
  735. 'txt' -> 'text/plain'.
  736. 'udeb' -> 'application/x-debian-package'.
  737. 'uls' -> 'text/iuls'.
  738. 'ustar' -> 'application/x-ustar'.
  739. 'val' -> 'chemical/x-ncbi-asn1-binary'.
  740. 'vcd' -> 'application/x-cdlink'.
  741. 'vcf' -> 'text/x-vcard'.
  742. 'vcs' -> 'text/x-vcalendar'.
  743. 'vmd' -> 'chemical/x-vmd'.
  744. 'vms' -> 'chemical/x-vamas-iso14976'.
  745. 'vor' -> 'application/vnd.stardivision.writer'.
  746. 'vrm' -> 'x-world/x-vrml'.
  747. 'vrml' -> 'x-world/x-vrml'.
  748. 'vsd' -> 'application/vnd.visio'.
  749. 'wad' -> 'application/x-doom'.
  750. 'wav' -> 'audio/x-wav'.
  751. 'wax' -> 'audio/x-ms-wax'.
  752. 'wbmp' -> 'image/vnd.wap.wbmp'.
  753. 'wbxml' -> 'application/vnd.wap.wbxml'.
  754. 'wk' -> 'application/x-123'.
  755. 'wm' -> 'video/x-ms-wm'.
  756. 'wma' -> 'audio/x-ms-wma'.
  757. 'wmd' -> 'application/x-ms-wmd'.
  758. 'wml' -> 'text/vnd.wap.wml'.
  759. 'wmlc' -> 'application/vnd.wap.wmlc'.
  760. 'wmls' -> 'text/vnd.wap.wmlscript'.
  761. 'wmlsc' -> 'application/vnd.wap.wmlscriptc'.
  762. 'wmv' -> 'video/x-ms-wmv'.
  763. 'wmx' -> 'video/x-ms-wmx'.
  764. 'wmz' -> 'application/x-ms-wmz'.
  765. 'wp5' -> 'application/wordperfect5.1'.
  766. 'wpd' -> 'application/wordperfect'.
  767. 'wrl' -> 'x-world/x-vrml'.
  768. 'wsc' -> 'text/scriptlet'.
  769. 'wvx' -> 'video/x-ms-wvx'.
  770. 'wz' -> 'application/x-wingz'.
  771. 'xbm' -> 'image/x-xbitmap'.
  772. 'xcf' -> 'application/x-xcf'.
  773. 'xht' -> 'application/xhtml+xml'.
  774. 'xhtml' -> 'application/xhtml+xml'.
  775. 'xlb' -> 'application/vnd.ms-excel'.
  776. 'xls' -> 'application/vnd.ms-excel'.
  777. 'xlt' -> 'application/vnd.ms-excel'.
  778. 'xml' -> 'application/xml'.
  779. 'xpi' -> 'application/x-xpinstall'.
  780. 'xpm' -> 'image/x-xpixmap'.
  781. 'xsl' -> 'application/xml'.
  782. 'xtel' -> 'chemical/x-xtel'.
  783. 'xul' -> 'application/vnd.mozilla.xul+xml'.
  784. 'xwd' -> 'image/x-xwindowdump'.
  785. 'xyz' -> 'chemical/x-xyz'.
  786. 'zip' -> 'application/zip'.
  787. 'zmt' -> 'chemical/x-mopac-input'.
  788. '~' -> 'application/x-trash'
  789. }
  790. !
  791. defaultPort
  792. ^ 4000
  793. !
  794. mimeTypeFor: aString
  795. ^ self mimeTypes at: (aString replace: '.*[\.]' with: '') ifAbsent: ['text/plain']
  796. !
  797. mimeTypes
  798. ^ mimeTypes ifNil: [mimeTypes := self defaultMimeTypes]
  799. !
  800. printHelp
  801. console log: 'Available commandline options are:'.
  802. console log: '--help'.
  803. self commandLineSwitches do: [ :each |
  804. console log: each, ' <parameter>']
  805. !
  806. selectorForCommandLineSwitch: aSwitch
  807. "Remove the trailing '--', add ':' at the end
  808. and replace all occurences of a lowercase letter preceded by a '-' with
  809. the Uppercase letter.
  810. Example: --fallback-page becomes fallbackPage:"
  811. ^ ((aSwitch replace: '^--' with: '')
  812. replace: '-[a-z]' with: [ :each | each second asUppercase ]), ':'
  813. ! !
  814. !FileServer class methodsFor: 'initialization'!
  815. createServerWithArguments: options
  816. "If options are empty return a default FileServer instance.
  817. If options are given loop through them and set the passed in values
  818. on the FileServer instance.
  819. Commanline options map directly to methods in the 'accessing' protocol
  820. taking one parameter.
  821. Adding a method to this protocol makes it directly settable through
  822. command line options.
  823. "
  824. | server popFront front optionName optionValue switches |
  825. switches := self commandLineSwitches.
  826. server := self new.
  827. options ifEmpty: [^server].
  828. (options size even) ifFalse: [
  829. console log: 'Using default parameters.'.
  830. console log: 'Wrong commandline options or not enough arguments for: ' , options.
  831. console log: 'Use any of the following ones: ', switches.
  832. ^server].
  833. popFront := [:args |
  834. front := args first.
  835. args remove: front.
  836. front].
  837. [options notEmpty] whileTrue: [
  838. optionName := popFront value: options.
  839. optionValue := popFront value: options.
  840. (switches includes: optionName) ifTrue: [
  841. optionName := self selectorForCommandLineSwitch: optionName.
  842. server perform: optionName withArguments: (Array with: optionValue)]
  843. ifFalse: [
  844. console log: optionName, ' is not a valid commandline option'.
  845. console log: 'Use any of the following ones: ', switches ]].
  846. ^ server.
  847. !
  848. main
  849. "Main entry point for Amber applications.
  850. Creates and starts a FileServer instance."
  851. | fileServer args |
  852. args := process argv.
  853. "Remove the first args which contain the path to the node executable and the script file."
  854. args removeFrom: 1 to: 3.
  855. args detect: [ :each |
  856. (each = '--help') ifTrue: [FileServer printHelp]]
  857. ifNone: [
  858. fileServer := FileServer createServerWithArguments: args.
  859. ^ fileServer start]
  860. ! !
  861. BaseFileManipulator subclass: #Initer
  862. instanceVariableNames: 'childProcess nmPath'
  863. package: 'AmberCli'!
  864. !Initer methodsFor: 'action'!
  865. bowerInstallThenDo: aBlock
  866. | child |
  867. child := childProcess
  868. exec: (path join: nmPath with: '.bin' with: 'bower'), ' install'
  869. thenDo: aBlock.
  870. child stdout pipe: process stdout options: #{ 'end' -> false }
  871. !
  872. finishMessage
  873. console log: (#(
  874. ' '
  875. 'The project should now be set up.'
  876. ' '
  877. ' '
  878. 'To manage project from cli (run tests, recompile),'
  879. 'the `grunt` command-line tool needs to be installed.'
  880. 'If not present, it can be installed with:'
  881. ' (sudo) npm install -g grunt-cli'
  882. ' '
  883. 'To manage project dependencies,'
  884. 'the `bower` command-line tool needs to be installed.'
  885. 'If not present, it can be installed with:'
  886. ' (sudo) npm install -g bower'
  887. ' '
  888. ) join: String lf).
  889. [] valueWithTimeout: 600
  890. !
  891. gruntInitThenDo: aBlock
  892. | child |
  893. child := childProcess
  894. exec: (path join: nmPath with: '.bin' with: 'grunt-init'), ' ', (((path join: nmPath with: 'grunt-init-amber') replace: '\\' with: '\\') replace: ':' with: '\:')
  895. thenDo: aBlock.
  896. child stdout pipe: process stdout options: #{ 'end' -> false }.
  897. process stdin resume.
  898. process stdin pipe: child stdin options: #{ 'end' -> false }
  899. !
  900. gruntThenDo: aBlock
  901. | child |
  902. child := childProcess
  903. exec: (path join: nmPath with: '.bin' with: 'grunt')
  904. thenDo: aBlock.
  905. child stdout pipe: process stdout options: #{ 'end' -> false }
  906. !
  907. npmInstallThenDo: aBlock
  908. | child |
  909. child := childProcess
  910. exec: 'npm install'
  911. thenDo: aBlock.
  912. child stdout pipe: process stdout options: #{ 'end' -> false }
  913. !
  914. start
  915. self gruntInitThenDo: [ :error | error
  916. ifNotNil: [
  917. console log: 'grunt-init exec error:'; log: error.
  918. process exit ]
  919. ifNil: [
  920. self bowerInstallThenDo: [ :error2 | error2
  921. ifNotNil: [
  922. console log: 'bower install exec error:'; log: error2.
  923. process exit ]
  924. ifNil: [
  925. self npmInstallThenDo: [ :error3 | error3
  926. ifNotNil: [
  927. console log: 'npm install exec error:'; log: error3.
  928. process exit ]
  929. ifNil: [
  930. self gruntThenDo: [ :error4 | error4
  931. ifNotNil: [
  932. console log: 'grunt exec error:'; log: error4.
  933. process exit ]
  934. ifNil: [
  935. self finishMessage.
  936. process exit ]]]]]]]]
  937. ! !
  938. !Initer methodsFor: 'initialization'!
  939. initialize
  940. super initialize.
  941. childProcess := require value: 'child_process'.
  942. nmPath := path join: self rootDirname with: 'node_modules'
  943. ! !
  944. Object subclass: #NodeTestRunner
  945. instanceVariableNames: ''
  946. package: 'AmberCli'!
  947. !NodeTestRunner class methodsFor: 'not yet classified'!
  948. runTestSuite
  949. | suite worker |
  950. suite := OrderedCollection new.
  951. (TestCase allSubclasses select: [ :each | each isAbstract not ])
  952. do: [ :each | suite addAll: each buildSuite ].
  953. worker := TestSuiteRunner on: suite.
  954. worker announcer on: ResultAnnouncement do:
  955. [ :ann | | result |
  956. result := ann result.
  957. result runs = result total ifTrue: [
  958. console log: result runs asString, ' tests run, ', result failures size asString, ' failures, ', result errors size asString, ' errors.'.
  959. result failures isEmpty ifFalse: [
  960. result failures first runCase.
  961. "the line above should throw, normally, but just in case I leave the line below"
  962. self throw: result failures first class name, ' >> ', result failures first selector, ' is failing!!!!' ].
  963. result errors isEmpty ifFalse: [
  964. result errors first runCase.
  965. "the line above should throw, normally, but just in case I leave the line below"
  966. self throw: result errors first class name, ' >> ', result errors first selector, ' has errors!!!!' ].
  967. ]].
  968. worker run
  969. ! !
  970. Object subclass: #Repl
  971. instanceVariableNames: 'readline interface util session resultCount commands'
  972. package: 'AmberCli'!
  973. !Repl commentStamp!
  974. I am a class representing a REPL (Read Evaluate Print Loop) and provide a command line interface to Amber Smalltalk.
  975. On the prompt you can type Amber statements which will be evaluated after pressing <Enter>.
  976. The evaluation is comparable with executing a 'DoIt' in a workspace.
  977. My runtime requirement is a functional Node.js executable with working Readline support.!
  978. !Repl methodsFor: 'accessing'!
  979. commands
  980. ^ commands
  981. !
  982. prompt
  983. ^ 'amber >> '
  984. ! !
  985. !Repl methodsFor: 'actions'!
  986. clearScreen
  987. | esc cls |
  988. esc := String fromCharCode: 27.
  989. cls := esc, '[2J', esc, '[0;0f'.
  990. process stdout write: cls.
  991. interface prompt
  992. !
  993. close
  994. process stdin destroy
  995. !
  996. createInterface
  997. interface := readline createInterface: process stdin stdout: process stdout.
  998. interface on: 'line' do: [:buffer | self processLine: buffer].
  999. interface on: 'close' do: [self close].
  1000. self printWelcome; setupHotkeys; setPrompt.
  1001. interface prompt
  1002. !
  1003. eval: buffer
  1004. ^ self eval: buffer on: DoIt new.
  1005. !
  1006. eval: buffer on: anObject
  1007. | result |
  1008. buffer isEmpty ifFalse: [
  1009. [result := Compiler new evaluateExpression: buffer on: anObject]
  1010. tryCatch: [:e |
  1011. e isSmalltalkError
  1012. ifTrue: [ e resignal ]
  1013. ifFalse: [ process stdout write: e jsStack ]]].
  1014. ^ result
  1015. !
  1016. printWelcome
  1017. Transcript show: 'Type :q to exit.'; cr.
  1018. !
  1019. setPrompt
  1020. interface setPrompt: self prompt
  1021. ! !
  1022. !Repl methodsFor: 'initialization'!
  1023. initialize
  1024. super initialize.
  1025. session := DoIt new.
  1026. readline := require value: 'readline'.
  1027. util := require value: 'util'.
  1028. self setupCommands
  1029. !
  1030. setupCommands
  1031. commands := Dictionary from: {
  1032. {':q'} -> [process exit].
  1033. {''} -> [interface prompt]}
  1034. !
  1035. setupHotkeys
  1036. process stdin on: 'keypress' do: [:s :key | key ifNotNil: [self onKeyPress: key]].
  1037. ! !
  1038. !Repl methodsFor: 'private'!
  1039. addVariableNamed: aString to: anObject
  1040. | newClass newObject |
  1041. newClass := self subclass: anObject class withVariable: aString.
  1042. self encapsulateVariable: aString withValue: anObject in: newClass.
  1043. newObject := newClass new.
  1044. self setPreviousVariablesFor: newObject from: anObject.
  1045. ^ newObject
  1046. !
  1047. assignNewVariable: buffer do: aBlock
  1048. "Assigns a new variable and calls the given block with the variable's name and value
  1049. if buffer contains an assignment expression. If it doesn't the block is called with nil for
  1050. both arguments."
  1051. ^ self parseAssignment: buffer do: [ :name :expr || varName value |
  1052. varName := name ifNil: [self nextResultName].
  1053. session := self addVariableNamed: varName to: session.
  1054. [ value := self eval: varName, ' := ', (expr ifNil: [buffer]) on: session ]
  1055. on: Error
  1056. do: [ :e | ConsoleErrorHandler new logError: e. value := nil].
  1057. aBlock value: varName value: value]
  1058. !
  1059. encapsulateVariable: aString withValue: anObject in: aClass
  1060. "Add getter and setter for given variable to session."
  1061. | compiler |
  1062. compiler := Compiler new.
  1063. compiler install: aString, ': anObject ^ ', aString, ' := anObject' forClass: aClass protocol: 'session'.
  1064. compiler install: aString, ' ^ ', aString forClass: aClass protocol: 'session'.
  1065. !
  1066. executeCommand: aString
  1067. "Tries to process the given string as a command. Returns true if it was a command, false if not."
  1068. self commands keysAndValuesDo: [:names :cmd |
  1069. (names includes: aString) ifTrue: [
  1070. cmd value.
  1071. ^ true]].
  1072. ^ false
  1073. !
  1074. instanceVariableNamesFor: aClass
  1075. "Yields all instance variable names for the given class, including inherited ones."
  1076. ^ aClass superclass
  1077. ifNotNil: [
  1078. aClass instanceVariableNames copyWithAll: (self instanceVariableNamesFor: aClass superclass)]
  1079. ifNil: [
  1080. aClass instanceVariableNames]
  1081. !
  1082. isIdentifier: aString
  1083. ^ aString match: '^[a-z_]\w*$' asRegexp
  1084. !
  1085. isVariableDefined: aString
  1086. ^ (self instanceVariableNamesFor: session class) includes: aString
  1087. !
  1088. nextResultName
  1089. resultCount := resultCount
  1090. ifNotNil: [resultCount + 1]
  1091. ifNil: [1].
  1092. ^ 'res', resultCount asString
  1093. !
  1094. onKeyPress: key
  1095. (key ctrl and: [key name = 'l'])
  1096. ifTrue: [self clearScreen]
  1097. !
  1098. parseAssignment: aString do: aBlock
  1099. "Assigns a new variable if the given string is an assignment expression. Calls the given block with name and value.
  1100. If the string is not one no variable will be assigned and the block will be called with nil for both arguments."
  1101. | assignment |
  1102. assignment := (aString tokenize: ':=') collect: [:s | s trimBoth].
  1103. ^ (assignment size = 2 and: [self isIdentifier: assignment first])
  1104. ifTrue: [ aBlock value: assignment first value: assignment last ]
  1105. ifFalse: [ aBlock value: nil value: nil ]
  1106. !
  1107. presentResultNamed: varName withValue: value
  1108. Transcript show: varName, ': ', value class name, ' = ', value asString; cr.
  1109. interface prompt
  1110. !
  1111. processLine: buffer
  1112. "Processes lines entered through the readline interface."
  1113. | show |
  1114. show := [:varName :value | self presentResultNamed: varName withValue: value].
  1115. (self executeCommand: buffer) ifFalse: [
  1116. (self isVariableDefined: buffer)
  1117. ifTrue: [show value: buffer value: (session perform: buffer)]
  1118. ifFalse: [self assignNewVariable: buffer do: show]]
  1119. !
  1120. setPreviousVariablesFor: newObject from: oldObject
  1121. (self instanceVariableNamesFor: oldObject class) do: [:each |
  1122. newObject perform: each, ':' withArguments: {oldObject perform: each}].
  1123. !
  1124. subclass: aClass withVariable: varName
  1125. "Create subclass with new variable."
  1126. ^ ClassBuilder new
  1127. addSubclassOf: aClass
  1128. named: (self subclassNameFor: aClass) asSymbol
  1129. instanceVariableNames: {varName}
  1130. package: 'Compiler-Core'
  1131. !
  1132. subclassNameFor: aClass
  1133. ^ (aClass name matchesOf: '\d+$')
  1134. ifNotNil: [ | counter |
  1135. counter := (aClass name matchesOf: '\d+$') first asNumber + 1.
  1136. aClass name replaceRegexp: '\d+$' asRegexp with: counter asString]
  1137. ifNil: [
  1138. aClass name, '2'].
  1139. ! !
  1140. !Repl class methodsFor: 'initialization'!
  1141. main
  1142. self new createInterface
  1143. ! !