AmberCli.st 38 KB

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