1
0

AmberCli.st 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  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. fork: (self npmScriptForModule: 'bower' named: 'bower')
  875. args: #('install').
  876. child
  877. on: 'error' do: aBlock;
  878. on: 'close' do: [ :code |
  879. aBlock value: (code = 0 ifTrue: [ nil ] ifFalse: [ code ]) ]
  880. !
  881. finishMessage
  882. console log: (#(
  883. ' '
  884. 'The project should now be set up.'
  885. ' '
  886. ' '
  887. 'To manage project from cli (run tests, recompile),'
  888. 'the `grunt` command-line tool needs to be installed.'
  889. 'If not present, it can be installed with:'
  890. ' (sudo) npm install -g grunt-cli'
  891. ' '
  892. 'To manage project dependencies,'
  893. 'the `bower` command-line tool needs to be installed.'
  894. 'If not present, it can be installed with:'
  895. ' (sudo) npm install -g bower'
  896. ' '
  897. ) join: String lf).
  898. [] valueWithTimeout: 600
  899. !
  900. gruntInitThenDo: aBlock
  901. | child sanitizedTemplatePath |
  902. sanitizedTemplatePath := ((path join: nmPath with: 'grunt-init-amber')
  903. replace: '\\' with: '\\') replace: ':' with: '\:'.
  904. child := childProcess
  905. fork: (self npmScriptForModule: 'grunt-init' named: 'grunt-init')
  906. args: {sanitizedTemplatePath}.
  907. child
  908. on: 'error' do: aBlock;
  909. on: 'close' do: [ :code |
  910. aBlock value: (code = 0 ifTrue: [ nil ] ifFalse: [ code ]) ]
  911. !
  912. gruntThenDo: aBlock
  913. | child |
  914. child := childProcess
  915. fork: (self npmScriptForModule: 'grunt-cli' named: 'grunt')
  916. args: #('default' 'devel').
  917. child
  918. on: 'error' do: aBlock;
  919. on: 'close' do: [ :code |
  920. aBlock value: (code = 0 ifTrue: [ nil ] ifFalse: [ code ]) ]
  921. !
  922. npmInstallThenDo: aBlock
  923. | child |
  924. child := childProcess
  925. exec: 'npm install'
  926. thenDo: aBlock.
  927. child stdout pipe: process stdout options: #{ 'end' -> false }
  928. !
  929. start
  930. self gruntInitThenDo: [ :error | error
  931. ifNotNil: [
  932. console log: 'grunt-init exec error:'; log: error.
  933. process exit: 101 ]
  934. ifNil: [
  935. self bowerInstallThenDo: [ :error2 | error2
  936. ifNotNil: [
  937. console log: 'bower install exec error:'; log: error2.
  938. process exit: 102 ]
  939. ifNil: [
  940. self npmInstallThenDo: [ :error3 | error3
  941. ifNotNil: [
  942. console log: 'npm install exec error:'; log: error3.
  943. process exit: 103 ]
  944. ifNil: [
  945. self gruntThenDo: [ :error4 | error4
  946. ifNotNil: [
  947. console log: 'grunt exec error:'; log: error4.
  948. process exit: 104 ]
  949. ifNil: [
  950. self finishMessage.
  951. process exit ]]]]]]]]
  952. ! !
  953. !Initer methodsFor: 'initialization'!
  954. initialize
  955. super initialize.
  956. childProcess := require value: 'child_process'.
  957. nmPath := path join: self rootDirname with: 'node_modules'
  958. ! !
  959. !Initer methodsFor: 'npm'!
  960. npmScriptForModule: aString named: anotherString
  961. | modulePath packageJson binSection scriptPath |
  962. modulePath := path dirname: (
  963. (JSObjectProxy on: require)
  964. resolve: aString, '/package.json').
  965. packageJson := Smalltalk readJSObject: (
  966. require value: aString, '/package.json').
  967. binSection := packageJson at: 'bin'.
  968. scriptPath := binSection isString
  969. ifTrue: [ binSection ]
  970. ifFalse: [ binSection at: anotherString ].
  971. ^ path join: modulePath with: scriptPath
  972. ! !
  973. Object subclass: #Repl
  974. instanceVariableNames: 'readline interface util session resultCount commands'
  975. package: 'AmberCli'!
  976. !Repl commentStamp!
  977. I am a class representing a REPL (Read Evaluate Print Loop) and provide a command line interface to Amber Smalltalk.
  978. On the prompt you can type Amber statements which will be evaluated after pressing <Enter>.
  979. The evaluation is comparable with executing a 'DoIt' in a workspace.
  980. My runtime requirement is a functional Node.js executable with working Readline support.!
  981. !Repl methodsFor: 'accessing'!
  982. commands
  983. ^ commands
  984. !
  985. prompt
  986. ^ 'amber >> '
  987. ! !
  988. !Repl methodsFor: 'actions'!
  989. clearScreen
  990. | esc cls |
  991. esc := String fromCharCode: 27.
  992. cls := esc, '[2J', esc, '[0;0f'.
  993. process stdout write: cls.
  994. interface prompt
  995. !
  996. close
  997. process stdin destroy
  998. !
  999. createInterface
  1000. interface := readline createInterface: process stdin stdout: process stdout.
  1001. interface on: 'line' do: [:buffer | self processLine: buffer].
  1002. interface on: 'close' do: [self close].
  1003. self printWelcome; setupHotkeys; setPrompt.
  1004. interface prompt
  1005. !
  1006. eval: buffer
  1007. ^ self eval: buffer on: DoIt new.
  1008. !
  1009. eval: buffer on: anObject
  1010. | result |
  1011. buffer isEmpty ifFalse: [
  1012. [result := Compiler new evaluateExpression: buffer on: anObject]
  1013. tryCatch: [:e |
  1014. e isSmalltalkError
  1015. ifTrue: [ e resignal ]
  1016. ifFalse: [ process stdout write: e jsStack ]]].
  1017. ^ result
  1018. !
  1019. printWelcome
  1020. Transcript show: 'Type :q to exit.'; cr.
  1021. !
  1022. setPrompt
  1023. interface setPrompt: self prompt
  1024. ! !
  1025. !Repl methodsFor: 'initialization'!
  1026. initialize
  1027. super initialize.
  1028. session := DoIt new.
  1029. readline := require value: 'readline'.
  1030. util := require value: 'util'.
  1031. self setupCommands
  1032. !
  1033. setupCommands
  1034. commands := Dictionary from: {
  1035. {':q'} -> [process exit].
  1036. {''} -> [interface prompt]}
  1037. !
  1038. setupHotkeys
  1039. process stdin on: 'keypress' do: [:s :key | key ifNotNil: [self onKeyPress: key]].
  1040. ! !
  1041. !Repl methodsFor: 'private'!
  1042. addVariableNamed: aString to: anObject
  1043. | newClass newObject |
  1044. newClass := self subclass: anObject class withVariable: aString.
  1045. self encapsulateVariable: aString withValue: anObject in: newClass.
  1046. newObject := newClass new.
  1047. self setPreviousVariablesFor: newObject from: anObject.
  1048. ^ newObject
  1049. !
  1050. assignNewVariable: buffer do: aBlock
  1051. "Assigns a new variable and calls the given block with the variable's name and value
  1052. if buffer contains an assignment expression. If it doesn't the block is called with nil for
  1053. both arguments."
  1054. ^ self parseAssignment: buffer do: [ :name :expr || varName value |
  1055. varName := name ifNil: [self nextResultName].
  1056. session := self addVariableNamed: varName to: session.
  1057. [ value := self eval: varName, ' := ', (expr ifNil: [buffer]) on: session ]
  1058. on: Error
  1059. do: [ :e | ConsoleErrorHandler new logError: e. value := nil].
  1060. aBlock value: varName value: value]
  1061. !
  1062. encapsulateVariable: aString withValue: anObject in: aClass
  1063. "Add getter and setter for given variable to session."
  1064. | compiler |
  1065. compiler := Compiler new.
  1066. compiler install: aString, ': anObject ^ ', aString, ' := anObject' forClass: aClass protocol: 'session'.
  1067. compiler install: aString, ' ^ ', aString forClass: aClass protocol: 'session'.
  1068. !
  1069. executeCommand: aString
  1070. "Tries to process the given string as a command. Returns true if it was a command, false if not."
  1071. self commands keysAndValuesDo: [:names :cmd |
  1072. (names includes: aString) ifTrue: [
  1073. cmd value.
  1074. ^ true]].
  1075. ^ false
  1076. !
  1077. instanceVariableNamesFor: aClass
  1078. "Yields all instance variable names for the given class, including inherited ones."
  1079. ^ aClass superclass
  1080. ifNotNil: [
  1081. aClass instanceVariableNames copyWithAll: (self instanceVariableNamesFor: aClass superclass)]
  1082. ifNil: [
  1083. aClass instanceVariableNames]
  1084. !
  1085. isIdentifier: aString
  1086. ^ aString match: '^[a-z_]\w*$' asRegexp
  1087. !
  1088. isVariableDefined: aString
  1089. ^ (self instanceVariableNamesFor: session class) includes: aString
  1090. !
  1091. nextResultName
  1092. resultCount := resultCount
  1093. ifNotNil: [resultCount + 1]
  1094. ifNil: [1].
  1095. ^ 'res', resultCount asString
  1096. !
  1097. onKeyPress: key
  1098. (key ctrl and: [key name = 'l'])
  1099. ifTrue: [self clearScreen]
  1100. !
  1101. parseAssignment: aString do: aBlock
  1102. "Assigns a new variable if the given string is an assignment expression. Calls the given block with name and value.
  1103. If the string is not one no variable will be assigned and the block will be called with nil for both arguments."
  1104. | assignment |
  1105. assignment := (aString tokenize: ':=') collect: [:s | s trimBoth].
  1106. ^ (assignment size = 2 and: [self isIdentifier: assignment first])
  1107. ifTrue: [ aBlock value: assignment first value: assignment last ]
  1108. ifFalse: [ aBlock value: nil value: nil ]
  1109. !
  1110. presentResultNamed: varName withValue: value
  1111. Transcript show: varName, ': ', value class name, ' = ', value asString; cr.
  1112. interface prompt
  1113. !
  1114. processLine: buffer
  1115. "Processes lines entered through the readline interface."
  1116. | show |
  1117. show := [:varName :value | self presentResultNamed: varName withValue: value].
  1118. (self executeCommand: buffer) ifFalse: [
  1119. (self isVariableDefined: buffer)
  1120. ifTrue: [show value: buffer value: (session perform: buffer)]
  1121. ifFalse: [self assignNewVariable: buffer do: show]]
  1122. !
  1123. setPreviousVariablesFor: newObject from: oldObject
  1124. (self instanceVariableNamesFor: oldObject class) do: [:each |
  1125. newObject perform: each, ':' withArguments: {oldObject perform: each}].
  1126. !
  1127. subclass: aClass withVariable: varName
  1128. "Create subclass with new variable."
  1129. ^ ClassBuilder new
  1130. addSubclassOf: aClass
  1131. named: (self subclassNameFor: aClass) asSymbol
  1132. instanceVariableNames: {varName}
  1133. package: 'Compiler-Core'
  1134. !
  1135. subclassNameFor: aClass
  1136. ^ (aClass name matchesOf: '\d+$')
  1137. ifNotNil: [ | counter |
  1138. counter := (aClass name matchesOf: '\d+$') first asNumber + 1.
  1139. aClass name replaceRegexp: '\d+$' asRegexp with: counter asString]
  1140. ifNil: [
  1141. aClass name, '2'].
  1142. ! !
  1143. !Repl class methodsFor: 'initialization'!
  1144. main
  1145. self new createInterface
  1146. ! !