AmberCli.st 38 KB

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