AmberCli.st 38 KB

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