FIX: full spec block support for MAKE on error!.

Red/System [
	Title:   "Error! datatype runtime functions"
	Author:  "Nenad Rakocevic"
	File: 	 %error.reds
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: {
		Distributed under the Boost Software License, Version 1.0.
		See https://github.com/dockimbel/Red/blob/master/BSL-License.txt
	}
]

error: context [
	verbose: 0

	#enum field! [
		field-code
		field-type
		field-id
		field-arg1
		field-arg2
		field-arg3
		field-near
		field-where
		field-stack
	]

	set-where: func [
		error [red-object!]
		value [red-value!]
		/local
			base [red-value!]
	][
		base: object/get-values error
		copy-cell value base + field-where
	]

	get-stack-id: func [return: [integer!]][field-stack]

	get-call-argument: func [
		idx		[integer!]
		return: [red-word!]
		/local
			cnt   [integer!]
			fun   [red-function!]
			value [red-value!]
			end	  [red-value!]
			s	  [series!]
	][
		fun:   as red-function! _context/get stack/get-call
		s:	   as series! fun/spec/value
		value: s/offset
		end:   s/tail

		cnt: 0
		while [value < end][
			switch TYPE_OF(value) [
				TYPE_WORD
				TYPE_GET_WORD
				TYPE_LIT_WORD [
					if cnt = idx [return as red-word! value]
					cnt: cnt + 1
				]
				default [0]
			]
			value: value + 1
		]
		words/_anon										;-- return anonymous name
	]

	create: func [
		cat		[red-word!]
		id		[red-word!]
		arg1 	[red-value!]
		arg2 	[red-value!]
		arg3 	[red-value!]
		return: [red-object!]
		/local
			err  [red-object!]
			base [red-value!]
			blk	 [red-block!]
	][
		blk: block/push* 2
		block/rs-append blk as red-value! cat
		block/rs-append blk as red-value! id

		err:  make null as red-value! blk
		base: object/get-values err

		unless null? arg1 [copy-cell arg1 base + field-arg1]
		unless null? arg2 [copy-cell arg2 base + field-arg2]
		unless null? arg3 [copy-cell arg3 base + field-arg3]
		err
	]

	reduce: func [
		blk		[red-block!]
		obj		[red-object!]
		return: [red-block!]
		/local
			value [red-value!]
			tail  [red-value!]
			type  [integer!]
	][
		value: block/rs-head blk
		tail:  block/rs-tail blk

		while [value < tail][
			type: TYPE_OF(value)
			if any [
				type = TYPE_WORD
				type = TYPE_GET_WORD
			][
				copy-cell
					object/rs-select obj value
					value
			]
			value: value + 1
		]
		blk
	]

	;-- Actions --

	make: func [
		proto	 [red-value!]
		spec	 [red-value!]
		return:	 [red-object!]
		/local
			new		[red-object!]
			obj		[red-object!]
			series	[red-series!]
			errors	[red-object!]
			base	[red-value!]
			value	[red-value!]
			blk		[red-block!]
			int		[red-integer!]
			sym		[red-word!]
			w		[red-word!]
			cat		[integer!]
	][
		#if debug? = yes [if verbose > 0 [print-line "error/make"]]

		new: as red-object! stack/push*

		object/copy
			as red-object! #get system/standard/error
			as red-object! new
			null
			no
			null

		series: as red-series! spec
		new/header: TYPE_ERROR							;-- implicit reset of all header flags
		new/class:  0
		new/on-set: null

		base:	object/get-values new
		errors: as red-object! #get system/catalog/errors
		sym:	as red-word! object/get-words errors

		switch TYPE_OF(spec) [
			TYPE_INTEGER [
				copy-cell spec base						;-- set 'code field
				int: as red-integer! spec

				cat: int/value / 100
				w: sym + cat

				if any [
					int/value <= 0
					(sym + object/get-size errors) <= as red-value! w
				][
					fire [TO_ERROR(script out-of-range) spec]
				]
				word/make-at w/symbol base + field-type	;-- set 'type field

				errors: (as red-object! object/get-values errors) + cat
				sym: as red-word! object/get-words errors

				w: sym + (int/value // 100)
				if (sym + object/get-size errors) <= as red-value! w [
					fire [TO_ERROR(script out-of-range) spec]
				]
				word/make-at w/symbol base + field-id	;-- set 'id field
			]
			TYPE_BLOCK [
				blk: as red-block! spec
				value: block/rs-head blk

				switch TYPE_OF(value) [
					TYPE_WORD [
						cat: object/rs-find errors value

						if cat = -1 [
							fire [TO_ERROR(script invalid-spec-field) words/_type]
						]
						copy-cell value base + field-type

						errors: (as red-object! object/get-values errors) + cat
						value: value + 1
						if value < block/rs-tail blk [
							cat: object/rs-find errors value
							if cat = -1 [
								fire [TO_ERROR(script invalid-spec-field) words/_id]
							]
							copy-cell value base + field-id
						]
					]
					TYPE_SET_WORD [
						value: block/select-word blk words/_type
						if TYPE_OF(value) = TYPE_NONE [
							fire [TO_ERROR(script missing-spec-field) words/_type]
						]
						value: block/select-word blk words/_id
						if TYPE_OF(value) = TYPE_NONE [
							fire [TO_ERROR(script missing-spec-field) words/_id]
						]
						_context/bind blk GET_CTX(new) new/ctx yes
						interpreter/eval blk no
					]
					default [
						fire [TO_ERROR(internal invalid-error)]
					]
				]
			]
			default [
				--NOT_IMPLEMENTED--
			]
		]
		new
	]

	form: func [
		obj		[red-object!]
		buffer	[red-string!]
		arg		[red-value!]
		part	[integer!]
		return: [integer!]
		/local
			base	[red-value!]
			errors	[red-object!]
			value	[red-value!]
			str		[red-string!]
			blk		[red-block!]
	][
		#if debug? = yes [if verbose > 0 [print-line "error/form"]]

		base: object/get-values obj
		string/concatenate-literal buffer "*** "
		part: part - 4

		errors: as red-object! #get system/catalog/errors
		errors: as red-object! object/rs-select errors base + field-type

		str: as red-string! object/rs-select errors as red-value! words/_type
		assert TYPE_OF(str) = TYPE_STRING
		string/concatenate buffer str -1 0 yes no
		part: part - string/rs-length? str
		string/concatenate-literal buffer ": "
		part: part - 2

		value: object/rs-select errors base + field-id

		either TYPE_OF(value) = TYPE_STRING [
			str: as red-string! value
			string/concatenate buffer str -1 0 yes no
			part: part - string/rs-length? str
		][
			blk: block/clone as red-block! value no
			blk: reduce blk obj
			part: block/form blk buffer arg part
		]

		string/concatenate-literal buffer "^/*** Where: "
		part: part - 12
		value: base + field-where

		either TYPE_OF(value) = TYPE_WORD [
			part: word/form as red-word! value buffer arg part
		][
			string/concatenate-literal buffer "???"
			part: part - 3
		]

		value: #get system/console
		if TYPE_OF(value) = TYPE_NONE [
			value: base + field-stack
			if TYPE_OF(value) = TYPE_INTEGER [
				string/concatenate-literal buffer "^/*** Stack: "
				part: stack/trace as red-integer! value buffer part - 12
			]
		]
		part
	]

	mold: func [
		obj		[red-object!]
		buffer	[red-string!]
		only?	[logic!]
		all?	[logic!]
		flat?	[logic!]
		arg		[red-value!]
		part	[integer!]
		indent	[integer!]
		return: [integer!]
	][
		#if debug? = yes [if verbose > 0 [print-line "error/mold"]]

		string/concatenate-literal buffer "make error! ["
		part: object/serialize obj buffer only? all? flat? arg part - 13 yes indent + 1 yes
		if indent > 0 [part: object/do-indent buffer indent part]
		string/append-char GET_BUFFER(buffer) as-integer #"]"
		part - 1
	]

	init: does [
		datatype/register [
			TYPE_ERROR
			TYPE_OBJECT
			"error!"
			;-- General actions --
			:make
			null			;random
			INHERIT_ACTION	;reflect
			null			;to
			:form
			:mold
			INHERIT_ACTION	;eval-path
			null			;set-path
			INHERIT_ACTION	;compare
			;-- Scalar actions --
			null			;absolute
			null			;add
			null			;divide
			null			;multiply
			null			;negate
			null			;power
			null			;remainder
			null			;round
			null			;subtract
			null			;even?
			null			;odd?
			;-- Bitwise actions --
			null			;and~
			null			;complement
			null			;or~
			null			;xor~
			;-- Series actions --
			null			;append
			null			;at
			null			;back
			null			;change
			null			;clear
			INHERIT_ACTION	;copy
			INHERIT_ACTION	;find
			null			;head
			null			;head?
			null			;index?
			null			;insert
			null			;length?
			null			;next
			null			;pick
			null			;poke
			null			;remove
			null			;reverse
			INHERIT_ACTION	;select
			null			;sort
			null			;skip
			null			;swap
			null			;tail
			null			;tail?
			null			;take
			null			;trim
			;-- I/O actions --
			null			;create
			null			;close
			null			;delete
			null			;modify
			null			;open
			null			;open?
			null			;query
			null			;read
			null			;rename
			null			;update
			null			;write
		]
	]
]

Red/System [
	Title:   "Error! datatype runtime functions"
	Author:  "Nenad Rakocevic"
	File: 	 %error.reds
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2012 Nenad Rakocevic. All rights reserved."
	License: {
		Distributed under the Boost Software License, Version 1.0.
		See https://github.com/dockimbel/Red/blob/master/BSL-License.txt
	}
]

error: context [
	verbose: 0

	#enum field! [
		field-code
		field-type
		field-id
		field-arg1
		field-arg2
		field-arg3
		field-near
		field-where
		field-stack
	]

	set-where: func [
		error [red-object!]
		value [red-value!]
		/local
			base [red-value!]
	][
		base: object/get-values error
		copy-cell value base + field-where
	]

	get-stack-id: func [return: [integer!]][field-stack]

	get-call-argument: func [
		idx		[integer!]
		return: [red-word!]
		/local
			cnt   [integer!]
			fun   [red-function!]
			value [red-value!]
			end	  [red-value!]
			s	  [series!]
	][
		fun:   as red-function! _context/get stack/get-call
		s:	   as series! fun/spec/value
		value: s/offset
		end:   s/tail

		cnt: 0
		while [value < end][
			switch TYPE_OF(value) [
				TYPE_WORD
				TYPE_GET_WORD
				TYPE_LIT_WORD [
					if cnt = idx [return as red-word! value]
					cnt: cnt + 1
				]
				default [0]
			]
			value: value + 1
		]
		words/_anon										;-- return anonymous name
	]

	create: func [
		cat		[red-word!]
		id		[red-word!]
		arg1 	[red-value!]
		arg2 	[red-value!]
		arg3 	[red-value!]
		return: [red-object!]
		/local
			err  [red-object!]
			base [red-value!]
			blk	 [red-block!]
	][
		blk: block/push* 2
		block/rs-append blk as red-value! cat
		block/rs-append blk as red-value! id

		err:  make null as red-value! blk
		base: object/get-values err

		unless null? arg1 [copy-cell arg1 base + field-arg1]
		unless null? arg2 [copy-cell arg2 base + field-arg2]
		unless null? arg3 [copy-cell arg3 base + field-arg3]
		err
	]

	reduce: func [
		blk		[red-block!]
		obj		[red-object!]
		return: [red-block!]
		/local
			value [red-value!]
			tail  [red-value!]
			type  [integer!]
	][
		value: block/rs-head blk
		tail:  block/rs-tail blk

		while [value < tail][
			type: TYPE_OF(value)
			if any [
				type = TYPE_WORD
				type = TYPE_GET_WORD
			][
				copy-cell
					object/rs-select obj value
					value
			]
			value: value + 1
		]
		blk
	]

	;-- Actions --

	make: func [
		proto	 [red-value!]
		spec	 [red-value!]
		return:	 [red-object!]
		/local
			new		[red-object!]
			obj		[red-object!]
			series	[red-series!]
			errors	[red-object!]
			base	[red-value!]
			value	[red-value!]
			blk		[red-block!]
			int		[red-integer!]
			sym		[red-word!]
			w		[red-word!]
			cat		[integer!]
	][
		#if debug? = yes [if verbose > 0 [print-line "error/make"]]

		new: as red-object! stack/push*

		object/copy
			as red-object! #get system/standard/error
			as red-object! new
			null
			no
			null

		series: as red-series! spec
		new/header: TYPE_ERROR							;-- implicit reset of all header flags
		new/class:  0
		new/on-set: null

		base:	object/get-values new
		errors: as red-object! #get system/catalog/errors
		sym:	as red-word! object/get-words errors

		switch TYPE_OF(spec) [
			TYPE_INTEGER [
				copy-cell spec base						;-- set 'code field
				int: as red-integer! spec

				cat: int/value / 100
				w: sym + cat

				if any [
					int/value <= 0
					(sym + object/get-size errors) <= as red-value! w
				][
					fire [TO_ERROR(script out-of-range) spec]
				]
				word/make-at w/symbol base + field-type	;-- set 'type field

				errors: (as red-object! object/get-values errors) + cat
				sym: as red-word! object/get-words errors

				w: sym + (int/value // 100)
				if (sym + object/get-size errors) <= as red-value! w [
					fire [TO_ERROR(script out-of-range) spec]
				]
				word/make-at w/symbol base + field-id	;-- set 'id field
			]
			TYPE_BLOCK [
				blk: as red-block! spec
				value: block/rs-head blk

				switch TYPE_OF(value) [
					TYPE_WORD [
						cat: object/rs-find errors value

						if cat = -1 [
							fire [TO_ERROR(script invalid-spec-field) words/_type]
						]
						copy-cell value base + field-type

						errors: (as red-object! object/get-values errors) + cat
						value: value + 1
						if value < block/rs-tail blk [
							cat: object/rs-find errors value
							if cat = -1 [
								fire [TO_ERROR(script invalid-spec-field) words/_id]
							]
							copy-cell value base + field-id
						]
					]
					TYPE_SET_WORD [
						value: block/select-word blk words/_type
						if TYPE_OF(value) = TYPE_NONE [
							fire [TO_ERROR(script missing-spec-field) words/_type]
						]
						copy-cell value base + field-type

						value: block/select-word blk words/_id
						if TYPE_OF(value) = TYPE_NONE [
							fire [TO_ERROR(script missing-spec-field) words/_id]
						]
						copy-cell value base + field-id
					]
					default [
						fire [TO_ERROR(internal invalid-error)]
					]
				]
			]
			default [
				--NOT_IMPLEMENTED--
			]
		]
		new
	]

	form: func [
		obj		[red-object!]
		buffer	[red-string!]
		arg		[red-value!]
		part	[integer!]
		return: [integer!]
		/local
			base	[red-value!]
			errors	[red-object!]
			value	[red-value!]
			str		[red-string!]
			blk		[red-block!]
	][
		#if debug? = yes [if verbose > 0 [print-line "error/form"]]

		base: object/get-values obj
		string/concatenate-literal buffer "*** "
		part: part - 4

		errors: as red-object! #get system/catalog/errors
		errors: as red-object! object/rs-select errors base + field-type

		str: as red-string! object/rs-select errors as red-value! words/_type
		assert TYPE_OF(str) = TYPE_STRING
		string/concatenate buffer str -1 0 yes no
		part: part - string/rs-length? str
		string/concatenate-literal buffer ": "
		part: part - 2

		value: object/rs-select errors base + field-id

		either TYPE_OF(value) = TYPE_STRING [
			str: as red-string! value
			string/concatenate buffer str -1 0 yes no
			part: part - string/rs-length? str
		][
			blk: block/clone as red-block! value no
			blk: reduce blk obj
			part: block/form blk buffer arg part
		]

		string/concatenate-literal buffer "^/*** Where: "
		part: part - 12
		value: base + field-where

		either TYPE_OF(value) = TYPE_WORD [
			part: word/form as red-word! value buffer arg part
		][
			string/concatenate-literal buffer "???"
			part: part - 3
		]

		value: #get system/console
		if TYPE_OF(value) = TYPE_NONE [
			value: base + field-stack
			if TYPE_OF(value) = TYPE_INTEGER [
				string/concatenate-literal buffer "^/*** Stack: "
				part: stack/trace as red-integer! value buffer part - 12
			]
		]
		part
	]

	mold: func [
		obj		[red-object!]
		buffer	[red-string!]
		only?	[logic!]
		all?	[logic!]
		flat?	[logic!]
		arg		[red-value!]
		part	[integer!]
		indent	[integer!]
		return: [integer!]
	][
		#if debug? = yes [if verbose > 0 [print-line "error/mold"]]

		string/concatenate-literal buffer "make error! ["
		part: object/serialize obj buffer only? all? flat? arg part - 13 yes indent + 1 yes
		if indent > 0 [part: object/do-indent buffer indent part]
		string/append-char GET_BUFFER(buffer) as-integer #"]"
		part - 1
	]

	init: does [
		datatype/register [
			TYPE_ERROR
			TYPE_OBJECT
			"error!"
			;-- General actions --
			:make
			null			;random
			INHERIT_ACTION	;reflect
			null			;to
			:form
			:mold
			INHERIT_ACTION	;eval-path
			null			;set-path
			INHERIT_ACTION	;compare
			;-- Scalar actions --
			null			;absolute
			null			;add
			null			;divide
			null			;multiply
			null			;negate
			null			;power
			null			;remainder
			null			;round
			null			;subtract
			null			;even?
			null			;odd?
			;-- Bitwise actions --
			null			;and~
			null			;complement
			null			;or~
			null			;xor~
			;-- Series actions --
			null			;append
			null			;at
			null			;back
			null			;change
			null			;clear
			INHERIT_ACTION	;copy
			INHERIT_ACTION	;find
			null			;head
			null			;head?
			null			;index?
			null			;insert
			null			;length?
			null			;next
			null			;pick
			null			;poke
			null			;remove
			null			;reverse
			INHERIT_ACTION	;select
			null			;sort
			null			;skip
			null			;swap
			null			;tail
			null			;tail?
			null			;take
			null			;trim
			;-- I/O actions --
			null			;create
			null			;close
			null			;delete
			null			;modify
			null			;open
			null			;open?
			null			;query
			null			;read
			null			;rename
			null			;update
			null			;write
		]
	]
]


TESTS: added simple red/part tests

TESTS: added simple red/part tests

Red [
	Title:   "Red find test script"
	Author:  "Nenad Rakocevic & Peter W A Wood"
	File: 	 %find-test.red
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2013 Nenad Rakocevic & Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/origin/BSD-3-License.txt"
]

#include  %../../../../quick-test/quick-test.red

~~~start-file~~~ "find"

===start-group=== "find"
	--test-- "find-1"
	--assert [1 2 3 4] = find [1 2 3 4] 1
	--test-- "find-2"
	--assert [2 3 4] = find [1 2 3 4] 2
	--test-- "find-3"
	--assert [4] = find [1 2 3 4] 4
	--test-- "find-4"
	--assert none = find [1 2 3 4] 0
	--test-- "find-5"
	--assert none = find [1 2 3 4] 5
	--test-- "find-6"
	--assert none = find [1 2 3 4] "1"
	--test-- "find-7"
	--assert "12345" = find "12345" #"1"
	--test-- "find-8"
	--assert "12345" = find "12345" 1
	--test-- "find-9"
	--assert "12345" = find "12345" "1"
	--test-- "find-10"
	--assert "12345" = find "12345" "12"
	--test-- "find-11"
	--assert "2345" = find "12345" #"2"
	--test-- "find-12"
	--assert "5" = find "12345" #"5"
	--test-- "find-13"
	--assert none = find "12345" #"0"
	--test-- "find-14"
	--assert none = find "12345" #"6"
	--test-- "find-15"
	--assert [2 3] = find [1 2 3] [2 3]
	--test-- "find-16"
	--assert none = find [1 2 3] [3 2]
	--test-- "find-17"
	--assert [2 3] = find [1 2 2 3] [2 3]
	--test-- "find-18"
	--assert none = find [1 2] [2 3]
	--test-- "find-19"
	--assert "é" = find "abcdeé" "é"
	--test-- "find-20"
	--assert "eé" = find "abcdeé" "eé"
	--test-- "find-21"
	--assert none = find "abcdeé" "ée"
	--test-- "find-22"
	--assert "✐" = "abcde✐" "✐"            ;; code point 10000 (decimal)
	--test-- "find-23"
	--assert none = "abcde✐" "ed✐"
	--test-- "find-24"
	--assert "^(010000)" = find "abcde^(010000)" "^(010000)"
===end-group===

===start-group=== "find/part"
	--test-- "find/part-1"
	--assert none = find/part "1234" "1" 0
	--test-- "find/part-2"
	--assert "1234" = find/part "1234" "1" 1
	--test-- "find/part-3"
	--assert "234" = find/part "1234" "2" 2
	--test-- "find/part-4"
	--assert "234" = find/part "1234" "2" 4
	--test-- "find/part-5"
	--assert "234" = find/part "1234" "2" 5
===end-group===

~~~end-file~~~

Red [
	Title:   "Red find test script"
	Author:  "Nenad Rakocevic & Peter W A Wood"
	File: 	 %find-test.red
	Tabs:	 4
	Rights:  "Copyright (C) 2011-2013 Nenad Rakocevic & Peter W A Wood. All rights reserved."
	License: "BSD-3 - https://github.com/dockimbel/Red/blob/origin/BSD-3-License.txt"
]

#include  %../../../../quick-test/quick-test.red

~~~start-file~~~ "find"

===start-group=== "find"
	--test-- "find-1"
	--assert [1 2 3 4] = find [1 2 3 4] 1
	--test-- "find-2"
	--assert [2 3 4] = find [1 2 3 4] 2
	--test-- "find-3"
	--assert [4] = find [1 2 3 4] 4
	--test-- "find-4"
	--assert none = find [1 2 3 4] 0
	--test-- "find-5"
	--assert none = find [1 2 3 4] 5
	--test-- "find-6"
	--assert none = find [1 2 3 4] "1"
	--test-- "find-7"
	--assert "12345" = find "12345" #"1"
	--test-- "find-8"
	--assert "12345" = find "12345" 1
	--test-- "find-9"
	--assert "12345" = find "12345" "1"
	--test-- "find-10"
	--assert "12345" = find "12345" "12"
	--test-- "find-11"
	--assert "2345" = find "12345" #"2"
	--test-- "find-12"
	--assert "5" = find "12345" #"5"
	--test-- "find-13"
	--assert none = find "12345" #"0"
	--test-- "find-14"
	--assert none = find "12345" #"6"
	--test-- "find-15"
	--assert [2 3] = find [1 2 3] [2 3]
	--test-- "find-16"
	--assert none = find [1 2 3] [3 2]
	--test-- "find-17"
	--assert [2 3] = find [1 2 2 3] [2 3]
	--test-- "find-18"
	--assert none = find [1 2] [2 3]
	--test-- "find-19"
	--assert "é" = find "abcdeé" "é"
	--test-- "find-20"
	--assert "eé" = find "abcdeé" "eé"
	--test-- "find-21"
	--assert none = find "abcdeé" "ée"
	--test-- "find-22"
	--assert "✐" = "abcde✐" "✐"            ;; code point 10000 (decimal)
	--test-- "find-23"
	--assert none = "abcde✐" "ed✐"
	--test-- "find-24"
	--assert "^(010000)" = find "abcde^(010000)" "^(010000)"
===end-group===

~~~end-file~~~


FIX: missing local definition in collect-deep. Fixes a crash in GTK-text-editor.red.

Red/System [
	Title:   "Function! datatype runtime functions"
	Author:  "Nenad Rakocevic"
	File: 	 %function.reds
	Tabs:	 4
	Rights:  "Copyright (C) 2012 Nenad Rakocevic. All rights reserved."
	License: {
		Distributed under the Boost Software License, Version 1.0.
		See https://github.com/dockimbel/Red/blob/master/BSL-License.txt
	}
]

_function: context [
	verbose: 0

	collect-deep: func [
		list   [red-block!]
		ignore [red-block!]
		blk    [red-block!]
		/local
			value  [red-value!]
			tail   [red-value!]
			end	   [red-value!]
			result [red-value!]
			word   [red-value!]
	][
		value: block/rs-head blk
		tail:  block/rs-tail blk

		while [value < tail][
			switch TYPE_OF(value) [
				TYPE_SET_WORD [
					word: stack/push value
					word/header: TYPE_WORD				;-- convert the set-word! into a word!

					result: block/find ignore word null no no no null null no no no no

					if TYPE_OF(result) = TYPE_NONE [
						block/rs-append list word
						block/rs-append ignore word
					]
					stack/pop 2							;-- remove word and FIND result from stack
				]
				TYPE_BLOCK
				TYPE_PAREN [
					collect-deep list ignore as red-block! value
				]
				default [0]
			]
			value: value + 1
		]
	]

	collect-words: func [
		spec	[red-block!]
		body	[red-block!]
		return: [red-block!]
		/local
			list	[red-block!]
			ignore	[red-block!]
			extern	[red-block!]
			value	[red-value!]
			tail	[red-value!]
			s		[series!]
			extern? [logic!]
	][
		list: block/push* 8
		block/rs-append list as red-value! refinements/local

		ignore: block/clone spec no
		block/rs-append ignore as red-value! refinements/local

		value:  as red-value! refinements/extern		;-- process optional /extern
		extern: as red-block! block/find spec value null no no no null null no no no no
		extern?: TYPE_OF(extern) <> TYPE_NONE

		if extern? [
			s: GET_BUFFER(spec)
			s/tail: s/offset + extern/head				;-- cut /extern and extern words out
		]
		stack/pop 1										;-- remove FIND result from stack

		value:  block/rs-head ignore
		tail:	block/rs-tail ignore

		while [value < tail][
			switch TYPE_OF(value) [
				TYPE_WORD 	  [0]						;-- do nothing
				TYPE_REFINEMENT
				TYPE_GET_WORD
				TYPE_SET_WORD [
					value/header: TYPE_WORD				;-- convert it to a word!
				]
				default [
					if extern? [
						print-line ["*** Error: invalid /extern values"]
						halt
					]
				]
			]
			value: value + 1
		]

		collect-deep list ignore body

		if 1 < block/rs-length? list [
			block/rs-append-block spec list
		]
		list
	]

	validate: func [									;-- temporary mimalist spec checking
		spec [red-block!]
		/local
			value  [red-value!]
			end	   [red-value!]
			next   [red-value!]
			block? [logic!]
	][
		value: block/rs-head spec
		end:   block/rs-tail spec

		while [value < end][
			switch TYPE_OF(value) [
				TYPE_WORD
				TYPE_GET_WORD [
					next: value + 1
					block?: all [
						next < end
						TYPE_OF(next) = TYPE_BLOCK
					]
					value: value + either block? [2][1]
				]
				TYPE_SET_WORD [
					next: value + 1
					unless all [
						next < end
						TYPE_OF(next) = TYPE_BLOCK
					][
						print-line "*** Error: return: not followed by type in function spec"
						halt
					]
					value: next
				]
				TYPE_LIT_WORD
				TYPE_REFINEMENT
				TYPE_BLOCK
				TYPE_STRING [
					value: value + 1
				]
				default [
					print-line "*** Error: invalid value in function spec"
					halt
				]
			]
		]
	]

	bind: func [
		body [red-block!]
		ctx	 [red-context!]
		/local
			value [red-value!]
			end	  [red-value!]
			w	  [red-word!]
			idx	  [integer!]
			type  [integer!]
	][
		value: block/rs-head body
		end:   block/rs-tail body

		while [value < end][
			switch TYPE_OF(value) [
				TYPE_WORD
				TYPE_GET_WORD
				TYPE_SET_WORD
				TYPE_REFINEMENT [
					w: as red-word! value
					idx: _context/find-word ctx w/symbol
					if idx >= 0 [
						w/ctx:   ctx
						w/index: idx
					]
				]
				TYPE_BLOCK 					;@@ replace with TYPE_ANY_BLOCK
				TYPE_PAREN
				TYPE_PATH
				TYPE_LIT_PATH
				TYPE_SET_PATH
				TYPE_GET_PATH	[
					bind as red-block! value ctx
				]
				default [0]
			]
			value: value + 1
		]
	]

	init-locals: func [
		nb 	   [integer!]
		/local
			p  [red-value!]
	][
		until [
			p: stack/push*
			p/header: TYPE_NONE
			nb: nb - 1
			zero? nb
		]
	]

	push: func [
		spec	 [red-block!]
		body	 [red-block!]
		code	 [integer!]
		return:	 [red-context!]							;-- return function's local context
		/local
			cell   [red-function!]
			native [red-native!]
			more   [series!]
	][
		#if debug? = yes [if verbose > 0 [print-line "_function/push"]]

		cell: as red-function! stack/push*
		cell/header: TYPE_FUNCTION						;-- implicit reset of all header flags
		cell/spec:	 spec/node
		cell/ctx:	 _context/make spec yes
		cell/more:	 alloc-cells 3

		more: as series! cell/more/value
		copy-cell
			as cell! body
			alloc-tail more

		alloc-tail more									;-- reserved place for "symbols"

		native: as red-native! alloc-tail more
		native/header: TYPE_NATIVE
		native/code: code

		bind body cell/ctx
		cell/ctx
	]

	;-- Actions --

	reflect: func [
		fun		[red-function!]
		field	[integer!]
		return:	[red-block!]
		/local
			blk [red-block!]
			s	[series!]
	][
		case [
			field = words/spec [
				blk: as red-block! stack/arguments		;-- overwrite the function slot on stack
				blk/header: TYPE_BLOCK
				blk/node: fun/spec						;-- order of assignments matters
				blk/head: 0
			]
			field = words/body [
				s: as series! fun/more/value
				blk: as red-block! s/offset
				stack/set-last as red-value! blk
			]
			field = words/words [
				--NOT_IMPLEMENTED--						;@@ build the words block from spec
			]
			true [
				--NOT_IMPLEMENTED--						;@@ raise error
			]
		]
		blk												;@@ TBD: remove it when all cases implemented
	]

	form: func [
		value	[red-function!]
		buffer	[red-string!]
		arg		[red-value!]
		part	[integer!]
		return: [integer!]
	][
		#if debug? = yes [if verbose > 0 [print-line "function/form"]]

		string/concatenate-literal buffer "?function?"
		part - 10
	]

	mold: func [
		fun		[red-function!]
		buffer	[red-string!]
		only?	[logic!]
		all?	[logic!]
		flat?	[logic!]
		arg		[red-value!]
		part	[integer!]
		return: [integer!]
		/local
			s	[series!]
			blk [red-block!]
	][
		#if debug? = yes [if verbose > 0 [print-line "function/mold"]]

		string/concatenate-literal buffer "func "

		blk: as red-block! stack/push*
		blk/header: TYPE_BLOCK
		blk/head: 0
		blk/node: fun/spec
		part: block/mold blk buffer only? all? flat? arg part - 5			;-- spec

		s: as series! fun/more/value
		block/mold as red-block! s/offset buffer only? all? flat? arg part	;-- body
	]

	datatype/register [
		TYPE_FUNCTION
		TYPE_CONTEXT
		"function!"
		;-- General actions --
		null			;make
		null			;random
		:reflect
		null			;to
		:form
		:mold
		null			;get-path
		null			;set-path
		null			;compare
		;-- Scalar actions --
		null			;absolute
		null			;add
		null			;divide
		null			;multiply
		null			;negate
		null			;power
		null			;remainder
		null			;round
		null			;subtract
		null			;even?
		null			;odd?
		;-- Bitwise actions --
		null			;and~
		null			;complement
		null			;or~
		null			;xor~
		;-- Series actions --
		null			;append
		null			;at
		null			;back
		null			;change
		null			;clear
		null			;copy
		null			;find
		null			;head
		null			;head?
		null			;index?
		null			;insert
		null			;length?
		null			;next
		null			;pick
		null			;poke
		null			;remove
		null			;reverse
		null			;select
		null			;sort
		null			;skip
		null			;swap
		null			;tail
		null			;tail?
		null			;take
		null			;trim
		;-- I/O actions --
		null			;create
		null			;close
		null			;delete
		null			;modify
		null			;open
		null			;open?
		null			;query
		null			;read
		null			;rename
		null			;update
		null			;write
	]
]

Red/System [
	Title:   "Function! datatype runtime functions"
	Author:  "Nenad Rakocevic"
	File: 	 %function.reds
	Tabs:	 4
	Rights:  "Copyright (C) 2012 Nenad Rakocevic. All rights reserved."
	License: {
		Distributed under the Boost Software License, Version 1.0.
		See https://github.com/dockimbel/Red/blob/master/BSL-License.txt
	}
]

_function: context [
	verbose: 0

	collect-deep: func [
		list   [red-block!]
		ignore [red-block!]
		blk    [red-block!]
		/local
			value  [red-value!]
			end	   [red-value!]
			result [red-value!]
			word   [red-value!]
	][
		value: block/rs-head blk
		tail:  block/rs-tail blk

		while [value < tail][
			switch TYPE_OF(value) [
				TYPE_SET_WORD [
					word: stack/push value
					word/header: TYPE_WORD				;-- convert the set-word! into a word!

					result: block/find ignore word null no no no null null no no no no

					if TYPE_OF(result) = TYPE_NONE [
						block/rs-append list word
						block/rs-append ignore word
					]
					stack/pop 2							;-- remove word and FIND result from stack
				]
				TYPE_BLOCK
				TYPE_PAREN [
					collect-deep list ignore as red-block! value
				]
				default [0]
			]
			value: value + 1
		]
	]

	collect-words: func [
		spec	[red-block!]
		body	[red-block!]
		return: [red-block!]
		/local
			list	[red-block!]
			ignore	[red-block!]
			extern	[red-block!]
			value	[red-value!]
			tail	[red-value!]
			s		[series!]
			extern? [logic!]
	][
		list: block/push* 8
		block/rs-append list as red-value! refinements/local

		ignore: block/clone spec no
		block/rs-append ignore as red-value! refinements/local

		value:  as red-value! refinements/extern		;-- process optional /extern
		extern: as red-block! block/find spec value null no no no null null no no no no
		extern?: TYPE_OF(extern) <> TYPE_NONE

		if extern? [
			s: GET_BUFFER(spec)
			s/tail: s/offset + extern/head				;-- cut /extern and extern words out
		]
		stack/pop 1										;-- remove FIND result from stack

		value:  block/rs-head ignore
		tail:	block/rs-tail ignore

		while [value < tail][
			switch TYPE_OF(value) [
				TYPE_WORD 	  [0]						;-- do nothing
				TYPE_REFINEMENT
				TYPE_GET_WORD
				TYPE_SET_WORD [
					value/header: TYPE_WORD				;-- convert it to a word!
				]
				default [
					if extern? [
						print-line ["*** Error: invalid /extern values"]
						halt
					]
				]
			]
			value: value + 1
		]

		collect-deep list ignore body

		if 1 < block/rs-length? list [
			block/rs-append-block spec list
		]
		list
	]

	validate: func [									;-- temporary mimalist spec checking
		spec [red-block!]
		/local
			value  [red-value!]
			end	   [red-value!]
			next   [red-value!]
			block? [logic!]
	][
		value: block/rs-head spec
		end:   block/rs-tail spec

		while [value < end][
			switch TYPE_OF(value) [
				TYPE_WORD
				TYPE_GET_WORD [
					next: value + 1
					block?: all [
						next < end
						TYPE_OF(next) = TYPE_BLOCK
					]
					value: value + either block? [2][1]
				]
				TYPE_SET_WORD [
					next: value + 1
					unless all [
						next < end
						TYPE_OF(next) = TYPE_BLOCK
					][
						print-line "*** Error: return: not followed by type in function spec"
						halt
					]
					value: next
				]
				TYPE_LIT_WORD
				TYPE_REFINEMENT
				TYPE_BLOCK
				TYPE_STRING [
					value: value + 1
				]
				default [
					print-line "*** Error: invalid value in function spec"
					halt
				]
			]
		]
	]

	bind: func [
		body [red-block!]
		ctx	 [red-context!]
		/local
			value [red-value!]
			end	  [red-value!]
			w	  [red-word!]
			idx	  [integer!]
			type  [integer!]
	][
		value: block/rs-head body
		end:   block/rs-tail body

		while [value < end][
			switch TYPE_OF(value) [
				TYPE_WORD
				TYPE_GET_WORD
				TYPE_SET_WORD
				TYPE_REFINEMENT [
					w: as red-word! value
					idx: _context/find-word ctx w/symbol
					if idx >= 0 [
						w/ctx:   ctx
						w/index: idx
					]
				]
				TYPE_BLOCK 					;@@ replace with TYPE_ANY_BLOCK
				TYPE_PAREN
				TYPE_PATH
				TYPE_LIT_PATH
				TYPE_SET_PATH
				TYPE_GET_PATH	[
					bind as red-block! value ctx
				]
				default [0]
			]
			value: value + 1
		]
	]

	init-locals: func [
		nb 	   [integer!]
		/local
			p  [red-value!]
	][
		until [
			p: stack/push*
			p/header: TYPE_NONE
			nb: nb - 1
			zero? nb
		]
	]

	push: func [
		spec	 [red-block!]
		body	 [red-block!]
		code	 [integer!]
		return:	 [red-context!]							;-- return function's local context
		/local
			cell   [red-function!]
			native [red-native!]
			more   [series!]
	][
		#if debug? = yes [if verbose > 0 [print-line "_function/push"]]

		cell: as red-function! stack/push*
		cell/header: TYPE_FUNCTION						;-- implicit reset of all header flags
		cell/spec:	 spec/node
		cell/ctx:	 _context/make spec yes
		cell/more:	 alloc-cells 3

		more: as series! cell/more/value
		copy-cell
			as cell! body
			alloc-tail more

		alloc-tail more									;-- reserved place for "symbols"

		native: as red-native! alloc-tail more
		native/header: TYPE_NATIVE
		native/code: code

		bind body cell/ctx
		cell/ctx
	]

	;-- Actions --

	reflect: func [
		fun		[red-function!]
		field	[integer!]
		return:	[red-block!]
		/local
			blk [red-block!]
			s	[series!]
	][
		case [
			field = words/spec [
				blk: as red-block! stack/arguments		;-- overwrite the function slot on stack
				blk/header: TYPE_BLOCK
				blk/node: fun/spec						;-- order of assignments matters
				blk/head: 0
			]
			field = words/body [
				s: as series! fun/more/value
				blk: as red-block! s/offset
				stack/set-last as red-value! blk
			]
			field = words/words [
				--NOT_IMPLEMENTED--						;@@ build the words block from spec
			]
			true [
				--NOT_IMPLEMENTED--						;@@ raise error
			]
		]
		blk												;@@ TBD: remove it when all cases implemented
	]

	form: func [
		value	[red-function!]
		buffer	[red-string!]
		arg		[red-value!]
		part	[integer!]
		return: [integer!]
	][
		#if debug? = yes [if verbose > 0 [print-line "function/form"]]

		string/concatenate-literal buffer "?function?"
		part - 10
	]

	mold: func [
		fun		[red-function!]
		buffer	[red-string!]
		only?	[logic!]
		all?	[logic!]
		flat?	[logic!]
		arg		[red-value!]
		part	[integer!]
		return: [integer!]
		/local
			s	[series!]
			blk [red-block!]
	][
		#if debug? = yes [if verbose > 0 [print-line "function/mold"]]

		string/concatenate-literal buffer "func "

		blk: as red-block! stack/push*
		blk/header: TYPE_BLOCK
		blk/head: 0
		blk/node: fun/spec
		part: block/mold blk buffer only? all? flat? arg part - 5			;-- spec

		s: as series! fun/more/value
		block/mold as red-block! s/offset buffer only? all? flat? arg part	;-- body
	]

	datatype/register [
		TYPE_FUNCTION
		TYPE_CONTEXT
		"function!"
		;-- General actions --
		null			;make
		null			;random
		:reflect
		null			;to
		:form
		:mold
		null			;get-path
		null			;set-path
		null			;compare
		;-- Scalar actions --
		null			;absolute
		null			;add
		null			;divide
		null			;multiply
		null			;negate
		null			;power
		null			;remainder
		null			;round
		null			;subtract
		null			;even?
		null			;odd?
		;-- Bitwise actions --
		null			;and~
		null			;complement
		null			;or~
		null			;xor~
		;-- Series actions --
		null			;append
		null			;at
		null			;back
		null			;change
		null			;clear
		null			;copy
		null			;find
		null			;head
		null			;head?
		null			;index?
		null			;insert
		null			;length?
		null			;next
		null			;pick
		null			;poke
		null			;remove
		null			;reverse
		null			;select
		null			;sort
		null			;skip
		null			;swap
		null			;tail
		null			;tail?
		null			;take
		null			;trim
		;-- I/O actions --
		null			;create
		null			;close
		null			;delete
		null			;modify
		null			;open
		null			;open?
		null			;query
		null			;read
		null			;rename
		null			;update
		null			;write
	]
]


r547: documenting BUILD LABEL & REVISION

h1. Manual

This is the CruiseControl.rb manual. If you can't find what you're looking for here, make sure to look at the docs
for "plugins":/documentation/plugins or just "contact us":/documentation/contact_us

h1. Files and folders

If CC.rb is unpacked into [cruise] directory , then:

* [cruise]/projects/ is the projects directory.

* [cruise]/projects/your_project/ is a directory for the project called "your_project".

* [cruise]/projects/your_project/work/ is a local copy of your_project's source code. Builder keeps it up to date
  with the source control repository and runs builds against it.

* [cruise]/projects/your_project/build-123/ contains build status file, list of changed files,
  and other "build artifacts" created while building revision 123.

* [cruise]/projects/your_project/cruise_config.rb is builder configuration for your_project.

* [cruise]/config/site_config.rb is the file where you can make centralized changes to the configuration of dashboard
  and all builders.

h1. Site configuration

CruiseControl.rb package includes a file called [cruise]/config/site_config.rb.example. By copying it to
[cruise]/config/site_config.rb, and uncommenting some lines you can change a number of parameters not related to
a specific project. In normal life, your only reason to do it would be configuring SMTP connection, for sending
email notices. See the section on "Build monitoring via email" below.

h1. Project builder configuration

When you add a project to it, CruiseControl.rb will try to do something reasonable without any configuration.

However, there are things that builder cannot know in advance. For example, who needs to receive an email notice
when the build is broken? The default answer is "nobody", and it may be good enough if you use
"CCTray":http://ccnet.sourceforge.net/CCNET/CCTray.html or have an LCD panel displaying the dashboard on the wall of
your office to monitor the build status.

What if it's not good enough? To make the builder aware of all these other things that you want it to do, you will
have to write them down in a project configuration file.

Rolling your eyes already? Hold on, this is not J2EE deployment descriptors we are talking about. No two pages of
hand-crafted angled brackets just to get started here. A typical project configuration is about 3 to 5 lines of very
simple Ruby. Yes, the configuration language of CC.rb is Ruby.

As you add a project, a configuration file is created for you in [cruise]/projects/your_project/ directory. It's named
cruise_config.rb and almost everything in it is initially commented out. In fact, you can delete it and this will not
change anything. There are two lines not commented out:

Project.configure do |project|
end

Every cruise_config.rb must have these two lines. All your other configuration goes between them.

You can move cruise_config.rb to [cruise]/projects/your_project/work/ directory. In other words, check it into
Subversion, in the root directory of your project. Storing your CruiseControl.rb configuration in your project's version control
is usually a smart thing to do.

It is also possible to have two cruise_config.rb files for a project, one in the [cruise]/projects/your_project/
directory, and the other in version control. CruiseControl.rb loads both files, but settings from cruise_config.rb in
[cruise]/projects/your_project/ override those stored in version control. This can be useful when you want to see the
effect of some configuration settings without checking them in, or have some local settings for this installation.

p(hint). Hint: configuration examples below include lines that look like '...' This represents other
         configuration statements that may be in cruise_config.rb. You are not meant to copy-paste those dots into
         your configuration file. If you do, ./cruise start will fail to start, saying something about
         syntax error (SyntaxError). Understandably, ... is not a valid Ruby expression.

Since configuration files are written in a real programming language (Ruby), you can modularize them, use
logical statements, and generally do whatever makes sense. For example, consider the following snippet:

Project.configure do |project|
  case project.name
  when 'MyProject.Quick' then project.rake_task = 'test:units'
  when 'MyProject.BigBertha' then project.rake_task = 'cruise:all_tests'
  else raise "Don't know what to build for project #{project.name.inspect}"
  end
end

p(hint). Use code like above to source-control configuration of multiple CruiseControl.rb projects building the same codebase.

h1. What will it build by default?

Unless told otherwise, CruiseControl.rb will search for "Rake":http://rake.rubyforge.org/ build file in your project. Then
it will try to execute cruise task and stop right there, if cruise task is defined in your
build.

p(hint). If you don't want to leave the question "how to build this project?" to CruiseControl's best guesses
         just define cruise task in your build explicitly.

If there is no cruise task anywhere in sight, CruiseControl.rb will try to perform standard
Rails tasks that prepare a test database by deleting everything from it and executing
"migration":http://www.rubyonrails.org/api/classes/ActiveRecord/Migration.html scripts from your_project/db/migrate.
Finally, it will run all your automated tests.

p(hint). WARNING: with Rails projects, it is important that RAILS_ENV does not default to 'production'.
         Unless you want your migration scripts and unit tests to hit your production database, of course.
         CruiseControl.reb leaves this variable unchanged when invoking 'cruise' or other custom Rake task, and sets
         it to 'test' before invoking the defaults.

h1. How can I change what the build does?

cruise may be the task for a quick build, but you may also want to run a long build with all acceptance
tests included. This can be done by assigning the project.rake_task attribute in cruise_config.rb:

Project.configure do |project|
  ...
  project.rake_task = 'Big_Bertha_build'
  ...
end

p(hint). Hint: When you have two builds for the same projects, and want to run them on the same build server, it
         actually takes more than just a different Rake task. At the very least, you want to have separate databases
         for those two builds. You can achieve this by creating a separate environment and setting RAILS_ENV to it in
         your Rakefile. Copy config/environments/test.rb to config/environments/big_bertha.rb, add a :Big_Bertha_init
         Rake task with ENV['RAILS_ENV'] = 'big_bertha' in it, and put it in the beginning of
         :Big_Bertha_build list of depenedencies.

p(hint). Hint: Ideally, you'd also want some way to chain builds so that the long build for a new checkin is only
         launched once the short build has finished succesfully. For now, you can achieve something like this with a
         custom scheduler. CruiseControl.rb team intends to provide built-in support for this scenario in some future
         version.

Or you may not want to deal with Rake at all, but build your project by "make":http://www.gnu.org/software/make/,
"Ant":http://ant.apache.org/ or "MSBuild":http://msdn2.microsoft.com/en-us/library/wea2sca5.aspx.
Yes, CC.rb can deal with non-Ruby projects! We are running "JBehave":http://jbehave.org/ build on
our "demo site":http://cruisecontrolrb.thoughtworks.com/builds/JBehave to prove the point.

A custom build command can be set in project.build_command attribute. Modify cruise_config.rb file like
this:

Project.configure do |project|
  ...
  project.build_command = 'my_build_script.sh'
  ...
end

If project.build_command is set, CC.rb will change current working directory to
[cruise]/projects/your_project/work/, invoke specified command and look at the exit code to determine whether the
build passed or failed.

p(hint). You cannot specify both rake_task and build_command attributes in cruise_config.rb.
        It doesn't make sense, anyway.

h1. What should I do with custom build artifacts?

your_project may have a special build task, producing some output that you want to keep, and see on
the build page.

p(hint). Hint: Code coverage analysis is a good example of custom build output. CruiseControl.rb's own build uses
         "rcov":http://eigenclass.org/hiki.rb. If you drill down into a recent CC.rb build on
         "http://cruisecontrolrb.thoughtworks.com":http://cruisecontrolrb.thoughtworks.com, you can see links
         to test coverage reports.

Before running the build, CC.rb sets OS variable CC_BUILD_ARTIFACTS to the directory
where the build artifacts are collected. Make sure that your special task writes its output to that directory, or a
subdirectory under that directory.

The build page includes links to every file or subdirectory found in the build artifacts directory.

h1. Build scheduling

By default, the builder polls Subversion every 10 seconds for new revisions. This can be changed by adding the
following line to cruise_config.rb:

Project.configure do |project|
  ...
  project.scheduler.polling_interval = 5.minutes
  ...
end

What if you want a scheduler with some interesting logic? Well, a default scheduler can be substituted by placing
your own scheduler implementation intpo the plugins directory and writing in cruise_config.rb something like this:

Project.configure do |project|
  ...
  project.scheduler = MyCustomScheduler.new(project)
  ...
end

After initializing everything, and loading the project (this step includes evaluation of cruise_config.rb), the
builder invokes project.scheduler.run. A builder must be able to detect when its configuraton has changed, or when a
build is requested by user (pressing the Build Now button), so a custom scheduler needs to know how to recognize that situation.

Look at [cruise]/app/models/polling_scheduler.rb to understand how a scheduler interacts with a project.

h1. Deleting a project

To remove your_project from CruiseControl.rb, kill its builder process and then delete the [cruise]/projects/your_project/
directory.

h1. Build Chaining & Triggers

CC.rb uses triggers to tell it when to build a project.  Every project by default has a ChangeInSourceControl trigger, that tells it to build when (surprise) it detects a change in a project's source control.

However, you can add additional triggers or replace that trigger entirely.  For example, you can have one project's successful build trigger another project's build with our SuccessfulBuildTrigger.

  project.triggered_by SuccessfulBuildTrigger.new(project, 'indie')

or in short hand

  project.triggered_by 'indie'

Why would you want one build to trigger another?  In this instance, maybe our project depends on indie and we want to know if a change to indie breaks our project.

In these examples, *added* a SuccessfulBuildTrigger.  We could also *replace* the default trigger by writing

  project.triggered_by = "fast_build"

Why wouldn't we want our project to be triggered by a change to it's source code?  In this case, maybe we've separated our project into a fast and slow build.  We could use this to only trigger a slow build if the fast one passes.

In the future we expect to also support svn:external triggers.  However, the infrastructure is there for you to build your own.

h1. Environment Variables

CC.rb gives you some information to use inside your build.  It does this in the form of environment variables.  Currently, the list of environment variable is :
* CC_BUILD_REVISION - this is the revision number of the current build, it looks like "5" or "56236"
* CC_BUILD_LABEL - usually this is the same as CC_BUILD_REVISION, but if there is more than one build of a particular revision, it will have a ".n" after it, so it might look like "323", "323.2", "4236.20", etc.
* CC_BUILD_ARTIFACTS - this is the directory which the dashboard looks in.  Any files you copy into here will be available from the dashboard.

From within your build, CC.rb

h1. Remote Builds

CC.rb can run builds on remote servers.  This is done by sshing to the server in your build command.  For example:

  project.build_command = 'ssh user@server ./run_remotely.sh $CC_BUILD_REVISION'

run_remotely.sh might look something like:

  #/bin/bash
  svn up -r$1
  rake test:integration

Of course you will need to checkout the code on the remote server before running the first build.

Note that CC.rb will still maintain a checkout of the code on the local server, use it to check for modifications and store build results locally.

h1. Doing a Clean Checkout

CC.rb supports clean checkouts, though they are not the default.  To enable them, you must specify the subversion url in the cruise_config.rb and specify when they should happen.  It should look something like :

  project.source_control = Subversion.new(:url =>
                             'svn://rubyforge.org/var/svn/filesandbox/trunk')
  project.do_clean_checkout :every => 6.hours

you may also pass :always into do_clean_checkout, or any other time such as 2.days, 30.minutes, etc.

h1. Troubleshooting and support

Beware, at the time of this writing, CC.rb is quite young and may have some heinous bugs (although we do have several
thousand users, including some happy ones).  Good news is that CC.rb is simple (much, much
simpler than other CruiseControl incarnations). The dashboard is just a small Rails app, and the builder process is little
more than a dumb, single-threaded endless loop. No queues, relational databases, remoting, WS* web services or other such things.
Therefore, it's easy to debug. So, you are your own support hotline.  We do have some "tips":troubleshooting to help you get started, though :). Don't forget to send us patches, please!

OK, that was the pep talk. If you have an issue that you cannot fix on your own, subscribe to mail list
cruisecontrolrb-users@rubyforge.org and ask for help.

Should you require commercial support, training or consulting around this tool, "ThoughtWorks":http://thoughtworks.com/ can provide it to you.

h1. Documentation that we haven't written yet

We should write about ways to run CC.rb as a service on various platforms, write about various troubleshooting
techniques, document builder plugins etc.

p(hint). Hint to would-be contributors: documentation patches will be appreciated as highly as, if not higher than,
source patches.

h1. Manual

This is the CruiseControl.rb manual. If you can't find what you're looking for here, make sure to look at the docs
for "plugins":/documentation/plugins or just "contact us":/documentation/contact_us

h1. Files and folders

If CC.rb is unpacked into [cruise] directory , then:

* [cruise]/projects/ is the projects directory.

* [cruise]/projects/your_project/ is a directory for the project called "your_project".

* [cruise]/projects/your_project/work/ is a local copy of your_project's source code. Builder keeps it up to date
  with the source control repository and runs builds against it.

* [cruise]/projects/your_project/build-123/ contains build status file, list of changed files,
  and other "build artifacts" created while building revision 123.

* [cruise]/projects/your_project/cruise_config.rb is builder configuration for your_project.

* [cruise]/config/site_config.rb is the file where you can make centralized changes to the configuration of dashboard
  and all builders.

h1. Site configuration

CruiseControl.rb package includes a file called [cruise]/config/site_config.rb.example. By copying it to
[cruise]/config/site_config.rb, and uncommenting some lines you can change a number of parameters not related to
a specific project. In normal life, your only reason to do it would be configuring SMTP connection, for sending
email notices. See the section on "Build monitoring via email" below.

h1. Project builder configuration

When you add a project to it, CruiseControl.rb will try to do something reasonable without any configuration.

However, there are things that builder cannot know in advance. For example, who needs to receive an email notice
when the build is broken? The default answer is "nobody", and it may be good enough if you use
"CCTray":http://ccnet.sourceforge.net/CCNET/CCTray.html or have an LCD panel displaying the dashboard on the wall of
your office to monitor the build status.

What if it's not good enough? To make the builder aware of all these other things that you want it to do, you will
have to write them down in a project configuration file.

Rolling your eyes already? Hold on, this is not J2EE deployment descriptors we are talking about. No two pages of
hand-crafted angled brackets just to get started here. A typical project configuration is about 3 to 5 lines of very
simple Ruby. Yes, the configuration language of CC.rb is Ruby.

As you add a project, a configuration file is created for you in [cruise]/projects/your_project/ directory. It's named
cruise_config.rb and almost everything in it is initially commented out. In fact, you can delete it and this will not
change anything. There are two lines not commented out:

Project.configure do |project|
end

Every cruise_config.rb must have these two lines. All your other configuration goes between them.

You can move cruise_config.rb to [cruise]/projects/your_project/work/ directory. In other words, check it into
Subversion, in the root directory of your project. Storing your CruiseControl.rb configuration in your project's version control
is usually a smart thing to do.

It is also possible to have two cruise_config.rb files for a project, one in the [cruise]/projects/your_project/
directory, and the other in version control. CruiseControl.rb loads both files, but settings from cruise_config.rb in
[cruise]/projects/your_project/ override those stored in version control. This can be useful when you want to see the
effect of some configuration settings without checking them in, or have some local settings for this installation.

p(hint). Hint: configuration examples below include lines that look like '...' This represents other
         configuration statements that may be in cruise_config.rb. You are not meant to copy-paste those dots into
         your configuration file. If you do, ./cruise start will fail to start, saying something about
         syntax error (SyntaxError). Understandably, ... is not a valid Ruby expression.

Since configuration files are written in a real programming language (Ruby), you can modularize them, use
logical statements, and generally do whatever makes sense. For example, consider the following snippet:

Project.configure do |project|
  case project.name
  when 'MyProject.Quick' then project.rake_task = 'test:units'
  when 'MyProject.BigBertha' then project.rake_task = 'cruise:all_tests'
  else raise "Don't know what to build for project #{project.name.inspect}"
  end
end

p(hint). Use code like above to source-control configuration of multiple CruiseControl.rb projects building the same codebase.

h1. What will it build by default?

Unless told otherwise, CruiseControl.rb will search for "Rake":http://rake.rubyforge.org/ build file in your project. Then
it will try to execute cruise task and stop right there, if cruise task is defined in your
build.

p(hint). If you don't want to leave the question "how to build this project?" to CruiseControl's best guesses
         just define cruise task in your build explicitly.

If there is no cruise task anywhere in sight, CruiseControl.rb will try to perform standard
Rails tasks that prepare a test database by deleting everything from it and executing
"migration":http://www.rubyonrails.org/api/classes/ActiveRecord/Migration.html scripts from your_project/db/migrate.
Finally, it will run all your automated tests.

p(hint). WARNING: with Rails projects, it is important that RAILS_ENV does not default to 'production'.
         Unless you want your migration scripts and unit tests to hit your production database, of course.
         CruiseControl.reb leaves this variable unchanged when invoking 'cruise' or other custom Rake task, and sets
         it to 'test' before invoking the defaults.

h1. How can I change what the build does?

cruise may be the task for a quick build, but you may also want to run a long build with all acceptance
tests included. This can be done by assigning the project.rake_task attribute in cruise_config.rb:

Project.configure do |project|
  ...
  project.rake_task = 'Big_Bertha_build'
  ...
end

p(hint). Hint: When you have two builds for the same projects, and want to run them on the same build server, it
         actually takes more than just a different Rake task. At the very least, you want to have separate databases
         for those two builds. You can achieve this by creating a separate environment and setting RAILS_ENV to it in
         your Rakefile. Copy config/environments/test.rb to config/environments/big_bertha.rb, add a :Big_Bertha_init
         Rake task with ENV['RAILS_ENV'] = 'big_bertha' in it, and put it in the beginning of
         :Big_Bertha_build list of depenedencies.

p(hint). Hint: Ideally, you'd also want some way to chain builds so that the long build for a new checkin is only
         launched once the short build has finished succesfully. For now, you can achieve something like this with a
         custom scheduler. CruiseControl.rb team intends to provide built-in support for this scenario in some future
         version.

Or you may not want to deal with Rake at all, but build your project by "make":http://www.gnu.org/software/make/,
"Ant":http://ant.apache.org/ or "MSBuild":http://msdn2.microsoft.com/en-us/library/wea2sca5.aspx.
Yes, CC.rb can deal with non-Ruby projects! We are running "JBehave":http://jbehave.org/ build on
our "demo site":http://cruisecontrolrb.thoughtworks.com/builds/JBehave to prove the point.

A custom build command can be set in project.build_command attribute. Modify cruise_config.rb file like
this:

Project.configure do |project|
  ...
  project.build_command = 'my_build_script.sh'
  ...
end

If project.build_command is set, CC.rb will change current working directory to
[cruise]/projects/your_project/work/, invoke specified command and look at the exit code to determine whether the
build passed or failed.

p(hint). You cannot specify both rake_task and build_command attributes in cruise_config.rb.
        It doesn't make sense, anyway.

h1. What should I do with custom build artifacts?

your_project may have a special build task, producing some output that you want to keep, and see on
the build page.

p(hint). Hint: Code coverage analysis is a good example of custom build output. CruiseControl.rb's own build uses
         "rcov":http://eigenclass.org/hiki.rb. If you drill down into a recent CC.rb build on
         "http://cruisecontrolrb.thoughtworks.com":http://cruisecontrolrb.thoughtworks.com, you can see links
         to test coverage reports.

Before running the build, CC.rb sets OS variable CC_BUILD_ARTIFACTS to the directory
where the build artifacts are collected. Make sure that your special task writes its output to that directory, or a
subdirectory under that directory.

The build page includes links to every file or subdirectory found in the build artifacts directory.

h1. Build scheduling

By default, the builder polls Subversion every 10 seconds for new revisions. This can be changed by adding the
following line to cruise_config.rb:

Project.configure do |project|
  ...
  project.scheduler.polling_interval = 5.minutes
  ...
end

What if you want a scheduler with some interesting logic? Well, a default scheduler can be substituted by placing
your own scheduler implementation intpo the plugins directory and writing in cruise_config.rb something like this:

Project.configure do |project|
  ...
  project.scheduler = MyCustomScheduler.new(project)
  ...
end

After initializing everything, and loading the project (this step includes evaluation of cruise_config.rb), the
builder invokes project.scheduler.run. A builder must be able to detect when its configuraton has changed, or when a
build is requested by user (pressing the Build Now button), so a custom scheduler needs to know how to recognize that situation.

Look at [cruise]/app/models/polling_scheduler.rb to understand how a scheduler interacts with a project.

h1. Deleting a project

To remove your_project from CruiseControl.rb, kill its builder process and then delete the [cruise]/projects/your_project/
directory.

h1. Build Chaining & Triggers

CC.rb uses triggers to tell it when to build a project.  Every project by default has a ChangeInSourceControl trigger, that tells it to build when (surprise) it detects a change in a project's source control.

However, you can add additional triggers or replace that trigger entirely.  For example, you can have one project's successful build trigger another project's build with our SuccessfulBuildTrigger.

  project.triggered_by SuccessfulBuildTrigger.new(project, 'indie')

or in short hand

  project.triggered_by 'indie'

Why would you want one build to trigger another?  In this instance, maybe our project depends on indie and we want to know if a change to indie breaks our project.

In these examples, *added* a SuccessfulBuildTrigger.  We could also *replace* the default trigger by writing

  project.triggered_by = "fast_build"

Why wouldn't we want our project to be triggered by a change to it's source code?  In this case, maybe we've separated our project into a fast and slow build.  We could use this to only trigger a slow build if the fast one passes.

In the future we expect to also support svn:external triggers.  However, the infrastructure is there for you to build your own.

h1. Remote Builds

CC.rb can run builds on remote servers.  This is done by sshing to the server in your build command.  For example:

  project.build_command = 'ssh user@server ./run_remotely.sh $CC_BUILD_REVISION'

run_remotely.sh might look something like:

  #/bin/bash
  svn up -r$1
  rake test:integration

Of course you will need to checkout the code on the remote server before running the first build.

Note that CC.rb will still maintain a checkout of the code on the local server, use it to check for modifications and store build results locally.

h1. Doing a Clean Checkout

CC.rb supports clean checkouts, though they are not the default.  To enable them, you must specify the subversion url in the cruise_config.rb and specify when they should happen.  It should look something like :

  project.source_control = Subversion.new(:url =>
                             'svn://rubyforge.org/var/svn/filesandbox/trunk')
  project.do_clean_checkout :every => 6.hours

you may also pass :always into do_clean_checkout, or any other time such as 2.days, 30.minutes, etc.

h1. Troubleshooting and support

Beware, at the time of this writing, CC.rb is quite young and may have some heinous bugs (although we do have several
thousand users, including some happy ones).  Good news is that CC.rb is simple (much, much
simpler than other CruiseControl incarnations). The dashboard is just a small Rails app, and the builder process is little
more than a dumb, single-threaded endless loop. No queues, relational databases, remoting, WS* web services or other such things.
Therefore, it's easy to debug. So, you are your own support hotline.  We do have some "tips":troubleshooting to help you get started, though :). Don't forget to send us patches, please!

OK, that was the pep talk. If you have an issue that you cannot fix on your own, subscribe to mail list
cruisecontrolrb-users@rubyforge.org and ask for help.

Should you require commercial support, training or consulting around this tool, "ThoughtWorks":http://thoughtworks.com/ can provide it to you.

h1. Documentation that we haven't written yet

We should write about ways to run CC.rb as a service on various platforms, write about various troubleshooting
techniques, document builder plugins etc.

p(hint). Hint to would-be contributors: documentation patches will be appreciated as highly as, if not higher than,
source patches.