repo
string
commit
string
message
string
diff
string
hugomaiavieira/batraquio
cfd5c525e936914696abc27806b09bcfb64428f5
Fix bug where the tool 'Open Method Definition' just search under deep folders. \nObs: Now search under deeper and shallower folders, till find a folder that has a file named '.this_is_the_root_folder'
diff --git a/tools/open-method-definition b/tools/open-method-definition index 2424ef5..96d4944 100755 --- a/tools/open-method-definition +++ b/tools/open-method-definition @@ -1,52 +1,81 @@ #!/usr/bin/env python # [Gedit Tool] # Name=Open Method Definition # Shortcut=<Shift><Control>e # Applicability=all # Output=nothing # Input=nothing # Save-files=nothing import os import re from subprocess import Popen, PIPE +def make_path(list): + result = os.path.sep + for pos, folder in enumerate(list): + result += list[pos] + if pos != len(list)-1: + result += os.path.sep + return result + +def find_paths(file_path): + folders = file_path.split(os.path.sep)[1:] + paths=[] + for pos, folder in enumerate(folders): + paths.append(os.path.join(folders[0:pos])) + paths.append(folders) #the last one combination + return paths[1:] #the first one is a empty list + +def find_root(path): + paths = find_paths(path) + paths.reverse() #to make recursively from the deeper directory to the shallowest + for path in paths: + result = make_path(path) + have_main = os.listdir(result).count('.this_is_the_root_folder') + if have_main: + return result + return False + #define file types that can be handled FILETYPE_DEF_METHODS = { 'py': 'def ', 'rb': 'def ', } +print os.getenv("GEDIT_CURRENT_DOCUMENT_DIR") #find file type current_file = os.getenv("GEDIT_CURRENT_DOCUMENT_PATH") match = re.search('\.(py|rb|html|htm|xml|feature)$', current_file) if match != None: file_type = match.group(1) #take the selected word (even the one before the first '(') function_name = os.getenv("GEDIT_SELECTED_TEXT").split('(')[0] function_definition = FILETYPE_DEF_METHODS[file_type] + function_name - file_path = os.getenv("GEDIT_CURRENT_DOCUMENT_DIR") + root_path = find_root(os.getenv("GEDIT_CURRENT_DOCUMENT_DIR")) cmd_sed = r'sed "s/\(.*\):\([0-9]\):.*/\1 +\2/"' #try to use ack-grep to search try: - cmd_grep = ["ack-grep", "--no-color", "--max-count=1", "--no-group", function_definition, file_path] + cmd_grep = ["ack-grep", "--no-color", "--max-count=1", "--no-group", function_definition, root_path] first_exec = Popen(cmd_grep,stdout=PIPE)#+ '|' + cmd_sed execution = Popen(cmd_sed, shell=True, stdin=first_exec.stdout, stdout=PIPE) except: #use grep instead - cmd_grep = cmd_grep = r'grep -R -n "' + function_definition + '" ' + file_path + cmd_grep = cmd_grep = r'grep -R -n "' + function_definition + '" ' + root_path execution = Popen(cmd_grep + '|' + cmd_sed,shell=True,stdout=PIPE) output = execution.stdout.read() + + if output != '': + #found some definition - #take the first file found - file_found_with_line = output.split('\n')[0] + #take the first file found + file_found_with_line = output.split('\n')[0] - #open file found on exact definition line with gedit - Popen('gedit ' + file_found_with_line,shell=True,stdin=PIPE,stdout=PIPE) + #open file found on exact definition line with gedit + Popen('gedit ' + file_found_with_line,shell=True,stdin=PIPE,stdout=PIPE) else: print "File type doesn't have a method definition specified." -
hugomaiavieira/batraquio
c428cd5e262c54db001c02e916ef53b599bdfc0f
Change 'Open Method Definition' shortcut to Shift+Control+E
diff --git a/README.md b/README.md index 5effba1..1f01184 100644 --- a/README.md +++ b/README.md @@ -1,263 +1,263 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Table alignment Let's say you are using Cucumber to use a BDD approach on your project. And let's say that you are working with table on your tests. So, if you digit: |ab|cdefg| |foo|bar| Select this text, and press SHIFT+CTRL+F, the result should be: | ab | cdefg | | foo | bar | instantly. ##Method Location Tool name: **Open Method Definition** -Shortcut=Shift+Control+D +Shortcut=Shift+Control+E Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir. The plugin "External Tools" also have to be enabled. I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that). If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing: [sudo] apt-get install ack-grep Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method. Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'. And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+D the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Next steps Add snippets for django template tags and most common licences text. diff --git a/tools/open-method-definition b/tools/open-method-definition index 87020f2..2424ef5 100755 --- a/tools/open-method-definition +++ b/tools/open-method-definition @@ -1,51 +1,52 @@ #!/usr/bin/env python # [Gedit Tool] # Name=Open Method Definition -# Shortcut=<Shift><Control>d +# Shortcut=<Shift><Control>e # Applicability=all # Output=nothing # Input=nothing # Save-files=nothing import os import re from subprocess import Popen, PIPE #define file types that can be handled FILETYPE_DEF_METHODS = { 'py': 'def ', 'rb': 'def ', } #find file type current_file = os.getenv("GEDIT_CURRENT_DOCUMENT_PATH") match = re.search('\.(py|rb|html|htm|xml|feature)$', current_file) if match != None: file_type = match.group(1) #take the selected word (even the one before the first '(') function_name = os.getenv("GEDIT_SELECTED_TEXT").split('(')[0] function_definition = FILETYPE_DEF_METHODS[file_type] + function_name file_path = os.getenv("GEDIT_CURRENT_DOCUMENT_DIR") cmd_sed = r'sed "s/\(.*\):\([0-9]\):.*/\1 +\2/"' #try to use ack-grep to search try: cmd_grep = ["ack-grep", "--no-color", "--max-count=1", "--no-group", function_definition, file_path] first_exec = Popen(cmd_grep,stdout=PIPE)#+ '|' + cmd_sed execution = Popen(cmd_sed, shell=True, stdin=first_exec.stdout, stdout=PIPE) except: #use grep instead cmd_grep = cmd_grep = r'grep -R -n "' + function_definition + '" ' + file_path execution = Popen(cmd_grep + '|' + cmd_sed,shell=True,stdout=PIPE) output = execution.stdout.read() #take the first file found file_found_with_line = output.split('\n')[0] #open file found on exact definition line with gedit Popen('gedit ' + file_found_with_line,shell=True,stdin=PIPE,stdout=PIPE) else: print "File type doesn't have a method definition specified." +
hugomaiavieira/batraquio
40c636b06ba3d7341c0db27fe8db518ea4e182e6
Add snippet 'Align Table' to align tables separated by '|'
diff --git a/README.md b/README.md index 32356b2..5effba1 100644 --- a/README.md +++ b/README.md @@ -1,245 +1,263 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. + +##Table alignment + +Let's say you are using Cucumber to use a BDD approach on your project. +And let's say that you are working with table on your tests. +So, if you digit: + + |ab|cdefg| + |foo|bar| + +Select this text, and press SHIFT+CTRL+F, the result should be: + + | ab | cdefg | + | foo | bar | + +instantly. + + ##Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+D Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir. The plugin "External Tools" also have to be enabled. I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that). If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing: [sudo] apt-get install ack-grep Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method. Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'. And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+D the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Next steps Add snippets for django template tags and most common licences text. diff --git a/install.sh b/install.sh index 05239b8..6496d63 100755 --- a/install.sh +++ b/install.sh @@ -1,55 +1,57 @@ # Black magic to get the folder where the script is running FOLDER=$(cd $(dirname $0); pwd -P) # Create the gedit config folder if [ ! -d $HOME/.gnome2/gedit ] then mkdir -p ~/.gnome2/gedit fi # Copy Snippets if [ ! -d $HOME/.gnome2/gedit/snippets ] then mkdir -p ~/.gnome2/gedit/snippets cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ else - if [ ! -e ~/.gnome2/gedit/snippets/python.xml ] - then - cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ - else - echo -n 'The file python.xml already exist, do you want to replace it (y/n)? ' - read option - if [ $option = 'y' ] + for FILE in $(ls $FOLDER/snippets/); do + if [ ! -e ~/.gnome2/gedit/snippets/$FILE ] then - cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ - echo 'File replaced.' + cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ else - echo 'File not replaced.' + echo -n 'The file ' $FILE ' already exist, do you want to replace it (y/n)? ' + read option + if [ $option = 'y' ] + then + cp $FOLDER/snippets/$FILE ~/.gnome2/gedit/snippets/ + echo 'File replaced.' + else + echo 'File not replaced.' + fi fi - fi + done fi # Copy Tools if [ ! -d $HOME/.gnome2/gedit/tools ] then mkdir -p ~/.gnome2/gedit/tools cp $FOLDER/tools/* ~/.gnome2/gedit/tools/ else for FILE in $(ls $FOLDER/tools/); do if [ ! -e ~/.gnome2/gedit/tools/$FILE ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ else echo -n 'The file ' $FILE ' already exist, do you want to replace it (y/n)? ' read option if [ $option = 'y' ] then cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ echo 'File replaced.' else echo 'File not replaced.' fi fi done fi diff --git a/snippets/global.xml b/snippets/global.xml new file mode 100644 index 0000000..d86b118 --- /dev/null +++ b/snippets/global.xml @@ -0,0 +1,58 @@ +<?xml version='1.0' encoding='utf-8'?> +<snippets> + <snippet> + <text><![CDATA[$< +def formata_linha(linha): + pos_pipe = linha.find('|') + linha = linha[pos_pipe:] + linha_split = linha.split('|') + if linha[0:1]== '|': + del linha_split[0] + if linha[-1:]== '|': + del linha_split[-1] + return linha_split + +def popula_matriz_e_max(matriz, max_coluna, linha): + linha = formata_linha(linha) + for coluna in linha: + coluna = coluna.strip() + matriz.append([coluna]) + max_coluna.append(len(coluna)) + +linhas = $GEDIT_SELECTED_TEXT.decode("utf-8").split('\n') + +if linhas[-1] == '': + del linhas[-1] + +matriz = [] +max_coluna = [] + +popula_matriz_e_max(matriz, max_coluna, linhas[0]) + +linhas = linhas[1:] +for linha_pos in range(len(linhas)): + linha = linhas[linha_pos] + linha = formata_linha(linha) + for coluna in range(len(linha)): + palavra = linha[coluna] + palavra = palavra.strip() + matriz[coluna].append(palavra) + if max_coluna[coluna] < len(palavra): + max_coluna[coluna] = len(palavra) + +tabela = '' +for linha_pos in range(len(matriz[0])): + tabela += '|' + for coluna_pos in range(len(matriz)): + tamanho_da_celula = max_coluna[coluna_pos]; + celula = ' ' + matriz[coluna_pos][linha_pos].ljust(tamanho_da_celula) + ' ' + tabela += celula + tabela += '|' + tabela += '\n' + +return tabela +>]]></text> + <accelerator><![CDATA[<Shift><Control>f]]></accelerator> + <description>Align Table</description> + </snippet> +</snippets>
hugomaiavieira/batraquio
e9ac9d32bb947b68fb91b916cd58768b2168806a
Fix text.
diff --git a/README.md b/README.md index bef2ad2..32356b2 100644 --- a/README.md +++ b/README.md @@ -1,245 +1,245 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Method Location Tool name: **Open Method Definition** Shortcut=Shift+Control+D Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir. The plugin "External Tools" also have to be enabled. I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that). If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing: [sudo] apt-get install ack-grep Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method. Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'. And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() -If select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut <Shift>+<Control>+D +If I select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut Shift+Control+D the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Next steps Add snippets for django template tags and most common licences text.
hugomaiavieira/batraquio
8578ead60a79a2be62e09f2297ae22248aac75ca
Fix shortcut definition.\nObs: I'm hating can't preview .md files
diff --git a/README.md b/README.md index bfc7111..bef2ad2 100644 --- a/README.md +++ b/README.md @@ -1,245 +1,245 @@ #Batraquio Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Method Location Tool name: **Open Method Definition** -Shortcut=<Shift>+<Control>+D +Shortcut=Shift+Control+D Applicability: Python files (.py), Ruby Files (.rb) Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir. The plugin "External Tools" also have to be enabled. I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that). If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing: [sudo] apt-get install ack-grep Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method. Example: I have a file named "extension.py", that defines a method like this: def foo(bar="hello"): #this definition is on line 5 of this file pass It's location is './product/modules/'. And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: from modules.extension import foo if __name__=="__main__": foo() If select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut <Shift>+<Control>+D the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Next steps Add snippets for django template tags and most common licences text.
hugomaiavieira/batraquio
c7bac464d5b675d51e03ebcb51598e28c5941788
Use new README
diff --git a/README.md b/README.md new file mode 100644 index 0000000..bfc7111 --- /dev/null +++ b/README.md @@ -0,0 +1,245 @@ +#Batraquio + +Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up +the development, mostly using BDD approach. + +I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) +and the package gedit-plugins. + +**Obs.:** I'm using *it* instead *test* in the methods because I use the +[Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can +write specifications instead mere tests. + +##Install + +To install, just do this on terminal: + + ./install.sh + +##Smart def + +The Smart def snippet speeds up the method definition. The activation is made +with **Ctrl + u**. The examples below show the ways to use: + +Type the line below and press Ctrl + u with the cursor on the line + + it should return the sum of two numbers + +and you will have this (the | represents the cursor): + + def it_should_return_the_sum_of_two_numbers(self): + | + +You can pass params too: + + it should return the sum of two numbers(number1, number2) + +And you will have this: + + def it_should_return_the_sum_of_two_numbers(self, number1, number2): + | + +----------------------------------------------------------------------- + +You can also do this... + + def it should return the sum of two numbers + +This... + + def it should return the sum of two numbers (): + +Or many combinations of fails syntax that you will have this: + + def it_should_return_the_sum_of_two_numbers(self): + | + + +##Unittest + +Type **ut** and then press **Tab** and you get this: + + import unittest + from should_dsl import * + + class ClassName(unittest.TestCase): + | + +You only have to write the class name and press tab again. + +I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) +that gives you a lot of matchers and turns your test/specs more readable. + + +##Step Definition + +This snippet is based on [freshen](http://github.com/rlisagor/freshen) step +definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) +and [lettuce](http://lettuce.it) too. The difference is that you should add +manually the parameter *context* or *step* respectively. + +Type **sd** and press **Tab** and you get this: + + @Given/When/Then(r'step definition with params (.*)') + def step_definition_with_params(var1): + | + +You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or +*step* for lettuce; press *Tab* and write the step definition; press *Tab* again +and the method will be created. The name for the method is created replacing +spaces for undescore on the step definition text. The params list is created +based on the regex finded in the step definition text. + +##Method Location + +Tool name: **Open Method Definition** + +Shortcut=<Shift>+<Control>+D + +Applicability: Python files (.py), Ruby Files (.rb) + +Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir. +The plugin "External Tools" also have to be enabled. +I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that). +If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing: +[sudo] apt-get install ack-grep + +Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method. +Example: I have a file named "extension.py", that defines a method like this: + + def foo(bar="hello"): #this definition is on line 5 of this file + pass + +It's location is './product/modules/'. +And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: + + from modules.extension import foo + + if __name__=="__main__": + foo() + +If select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut <Shift>+<Control>+D +the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" + + +##Should-dsl + +[Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package +that gives you a lot of matchers and turns your test/specs more readable. + +Batraquio has snippets for all matchers of should-dsl. What you have to do is +type the left part of the matcher, then type the abbreviation of the matcher and +press *Tab*. Doing this the rest of the matcher will appear just to you complete +de right part of the matcher. + +For example: + + [1,2,3] anyof # Press Tab + [1,2,3] |should| have_any_of(iterable) # Type the iterable + [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below + +Below the description of all snippets for the matchers. + +###Matcher (abbreviation) + +All of this have the not version, that you can get typing not before the +abbreviatio, like the *Should not be* example. To be succinct, the not version +will not be demonstrate. + +* Should be (be) + + `actual |should| be(expected)` + +* Should not be (notbe) + + `actual |should_not| be(expected)` + +* Should include (include) + + `collection |should| include(items)` + +* Should contain (contain) + + `collection |should| contain(items)` + +* Should be into (into) + + `item |should| be_into(collection)` + +* Should have (have) + + `collection |should| have(quantity).something` + +* Should have at most (atmost) + + `collection |should| have_at_most(quantity).something` + +* Should have at least (atleast) + + `collection |should| have_at_least(quantity).something` + +* Should be equal to (equal) + + `actual |should| be_equal_to(expect)` + +* Should have all of (allof) + + `collection |should| have_all_of(iterable)` + +* Should have any of (anyof) + + `collection |should| have_any_of(iterable)` + +* Should be ended with (ended) + + `string |should| be_ended_with(substring)` + +* Should be greater than (greater) + + `actual |should| be_greater_than(expected)` + +* Should be greater than or equal to (greaterequal) + + `actual |should| be_greater_than_or_equal_to(expected)` + +* Should be kind of (kind) + + `instance |should| be_kind_of(class)` + +* Should be less than (less) + + `actual |should| be_less_than(expected)` + +* Should be less than or equal to (lessequal) + + `actual |should| be_less_than_or_equal_to(expected)` + +* Should be equal to ignoring case (ignoring) + + `actual |should| be_equal_to_ignoring_case(expect)` + +* Should have in any order + + `collection |should| have_in_any_order(iterable)` + +* Should be like + + `string |should| be_like(regex)` + +* Should throw + + `call |should| throw(exception)` + +* Should be thrown by + + `exception |should| be_thrown_by(call)` + +* Should respond to + + `object |should| respond_to('method')` + + +##Next steps + +Add snippets for django template tags and most common licences text. +
hugomaiavieira/batraquio
438696e08a45e84e1e33b2cedb83ea7e90084768
Add tool 'Open Method Definition' to locate method definitions inside your project workspace.
diff --git a/README.md b/README.md index 1a8745a..2cb329c 100644 --- a/README.md +++ b/README.md @@ -1,214 +1,241 @@ #Batraquio -Batraquio is a set of gedit snippets for python. The goal is help and speed up +Batraquio is a set of gedit snippets and tools for python. The goal is help and speed up the development, mostly using BDD approach. -I strongly recommend the you install the [gmate](http://github.com/gmate/gmate) +I strongly recommend that you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. +##Method Location + +Tool name: **Open Method Definition** +Shortcut=<Shift>+<Control>+D +Applicability: Python files (.py), Ruby Files (.rb) +Dependency: To use this tool, the plugin "File Browser" in Gedit have to be enabled, and you have to be in your workspace dir. +I also strongly recommend that you install the package 'ack-grep', to improve accuracy of the search (because ack-grep will ignore unwanted folders used by some CVS systems or things like that). +If you doesn't have 'ack-grep' installed, you can install it in a Debian-like distribution doing: +[sudo] apt-get install ack-grep + +Description: Select a method name, press the shortcut specified, and gedit should open the file that specify this method. +Example: I have a file named "extension.py", that defines a method like this: + + def foo(bar="hello"): #this definition is on line 5 of this file + pass + +It's location is './product/modules/'. +And my Gedit is opened, editing only one file named "main.py", that is located on "./product/", and have this on it: + + from modules.extension import foo + + if __name__=="__main__": + foo() + +If select all the word 'foo' on this file (or even all the call 'foo()'), and press the shortcut <Shift>+<Control>+D +the file "extension.py" will be opened on the line 5, the exact location that defines the method "foo" + ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` * Should have (have) `collection |should| have(quantity).something` * Should have at most (atmost) `collection |should| have_at_most(quantity).something` * Should have at least (atleast) `collection |should| have_at_least(quantity).something` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` * Should respond to `object |should| respond_to('method')` ##Next steps Add snippets for django template tags and most common licences text. diff --git a/install.sh b/install.sh index dc001ab..05239b8 100755 --- a/install.sh +++ b/install.sh @@ -1,31 +1,55 @@ # Black magic to get the folder where the script is running FOLDER=$(cd $(dirname $0); pwd -P) # Create the gedit config folder if [ ! -d $HOME/.gnome2/gedit ] then mkdir -p ~/.gnome2/gedit fi # Copy Snippets if [ ! -d $HOME/.gnome2/gedit/snippets ] then mkdir -p ~/.gnome2/gedit/snippets cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ else if [ ! -e ~/.gnome2/gedit/snippets/python.xml ] then cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ else echo -n 'The file python.xml already exist, do you want to replace it (y/n)? ' read option if [ $option = 'y' ] then cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ echo 'File replaced.' else echo 'File not replaced.' fi fi fi +# Copy Tools +if [ ! -d $HOME/.gnome2/gedit/tools ] +then + mkdir -p ~/.gnome2/gedit/tools + cp $FOLDER/tools/* ~/.gnome2/gedit/tools/ +else + for FILE in $(ls $FOLDER/tools/); do + if [ ! -e ~/.gnome2/gedit/tools/$FILE ] + then + cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ + else + echo -n 'The file ' $FILE ' already exist, do you want to replace it (y/n)? ' + read option + if [ $option = 'y' ] + then + cp $FOLDER/tools/$FILE ~/.gnome2/gedit/tools/ + echo 'File replaced.' + else + echo 'File not replaced.' + fi + fi + done +fi + diff --git a/tools/open-method-definition b/tools/open-method-definition new file mode 100755 index 0000000..87020f2 --- /dev/null +++ b/tools/open-method-definition @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# [Gedit Tool] +# Name=Open Method Definition +# Shortcut=<Shift><Control>d +# Applicability=all +# Output=nothing +# Input=nothing +# Save-files=nothing + + +import os +import re +from subprocess import Popen, PIPE + +#define file types that can be handled +FILETYPE_DEF_METHODS = { + 'py': 'def ', + 'rb': 'def ', + } + +#find file type +current_file = os.getenv("GEDIT_CURRENT_DOCUMENT_PATH") +match = re.search('\.(py|rb|html|htm|xml|feature)$', current_file) + +if match != None: + file_type = match.group(1) + #take the selected word (even the one before the first '(') + function_name = os.getenv("GEDIT_SELECTED_TEXT").split('(')[0] + function_definition = FILETYPE_DEF_METHODS[file_type] + function_name + file_path = os.getenv("GEDIT_CURRENT_DOCUMENT_DIR") + + cmd_sed = r'sed "s/\(.*\):\([0-9]\):.*/\1 +\2/"' + #try to use ack-grep to search + try: + cmd_grep = ["ack-grep", "--no-color", "--max-count=1", "--no-group", function_definition, file_path] + first_exec = Popen(cmd_grep,stdout=PIPE)#+ '|' + cmd_sed + execution = Popen(cmd_sed, shell=True, stdin=first_exec.stdout, stdout=PIPE) + except: + #use grep instead + cmd_grep = cmd_grep = r'grep -R -n "' + function_definition + '" ' + file_path + execution = Popen(cmd_grep + '|' + cmd_sed,shell=True,stdout=PIPE) + + output = execution.stdout.read() + + #take the first file found + file_found_with_line = output.split('\n')[0] + + #open file found on exact definition line with gedit + Popen('gedit ' + file_found_with_line,shell=True,stdin=PIPE,stdout=PIPE) +else: + print "File type doesn't have a method definition specified."
hugomaiavieira/batraquio
ffc94911d978085a9b20b81e29660a993b68dd8e
Add matchers 'have', 'have_at_most', 'have_at_least' and 'respond_to'
diff --git a/README.md b/README.md index 23841ae..1a8745a 100644 --- a/README.md +++ b/README.md @@ -1,198 +1,214 @@ #Batraquio Batraquio is a set of gedit snippets for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend the you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` * Should contain (contain) `collection |should| contain(items)` * Should be into (into) `item |should| be_into(collection)` +* Should have (have) + + `collection |should| have(quantity).something` + +* Should have at most (atmost) + + `collection |should| have_at_most(quantity).something` + +* Should have at least (atleast) + + `collection |should| have_at_least(quantity).something` + * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` +* Should respond to + + `object |should| respond_to('method')` + ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/python.xml b/snippets/python.xml index 224a71e..1ef4352 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,275 +1,323 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| include(${1:items}) $0]]></text> <tag>include</tag> <description>Should include</description> </snippet> <snippet> <text><![CDATA[|should_not| include(${1:items}) $0]]></text> <tag>notinclude</tag> <description>Should not include</description> </snippet> <snippet> <text><![CDATA[|should| contain(${1:items}) $0]]></text> <tag>contain</tag> <description>Should contain</description> </snippet> <snippet> <text><![CDATA[|should_not| contain(${1:items}) $0]]></text> <tag>notcontain</tag> <description>Should not contain</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should be equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not be equal to</description> </snippet> <snippet> <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> <tag>thrownby</tag> <description>Should be thrown by</description> </snippet> <snippet> <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> <tag>notthrownby</tag> <description>Should not be thrown by</description> </snippet> + <snippet> + <text><![CDATA[|should| have(${1:quantity}).${2:something} +$0]]></text> + <tag>have</tag> + <description>Should have</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| have(${1:quantity}).${2:something} +$0]]></text> + <tag>nothave</tag> + <description>Should not have</description> + </snippet> + <snippet> + <text><![CDATA[|should| have_at_most(${1:quantity}).${2:something} +$0]]></text> + <tag>atmost</tag> + <description>Should have at most</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| have_at_most(${1:quantity}).${2:something} +$0]]></text> + <tag>notatmost</tag> + <description>Should not have at most</description> + </snippet> + <snippet> + <text><![CDATA[|should| have_at_least(${1:quantity}).${2:something} +$0]]></text> + <tag>atleast</tag> + <description>Should have at least</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| have_at_least(${1:quantity}).${2:something} +$0]]></text> + <tag>notatleast</tag> + <description>Should not have at least</description> + </snippet> + <snippet> + <text><![CDATA[|should| respond_to('${1:method}') +$0]]></text> + <tag>respond</tag> + <description>Should respond to</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| respond_to('${1:method}') +$0]]></text> + <tag>notrespond</tag> + <description>Should not respond to</description> + </snippet> </snippets>
hugomaiavieira/batraquio
07f8dde6c549044bf0471ee5291ddc0779a6a492
Add 'contain' matcher
diff --git a/README.md b/README.md index 485496c..23841ae 100644 --- a/README.md +++ b/README.md @@ -1,194 +1,198 @@ #Batraquio Batraquio is a set of gedit snippets for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend the you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should include (include) `collection |should| include(items)` +* Should contain (contain) + + `collection |should| contain(items)` + * Should be into (into) `item |should| be_into(collection)` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/python.xml b/snippets/python.xml index 60de0c0..224a71e 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,263 +1,275 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| include(${1:items}) $0]]></text> - <tag>have</tag> + <tag>include</tag> <description>Should include</description> </snippet> <snippet> <text><![CDATA[|should_not| include(${1:items}) $0]]></text> - <tag>nothave</tag> + <tag>notinclude</tag> <description>Should not include</description> </snippet> + <snippet> + <text><![CDATA[|should| contain(${1:items}) +$0]]></text> + <tag>contain</tag> + <description>Should contain</description> + </snippet> + <snippet> + <text><![CDATA[|should_not| contain(${1:items}) +$0]]></text> + <tag>notcontain</tag> + <description>Should not contain</description> + </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should be equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not be equal to</description> </snippet> <snippet> <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> <tag>thrownby</tag> <description>Should be thrown by</description> </snippet> <snippet> <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> <tag>notthrownby</tag> <description>Should not be thrown by</description> </snippet> </snippets>
hugomaiavieira/batraquio
ec61afd68af97d26ae23b3e6096a7010ec447b65
'have' matcher renamed to 'include'
diff --git a/README.md b/README.md index 1b9551d..485496c 100644 --- a/README.md +++ b/README.md @@ -1,194 +1,194 @@ #Batraquio Batraquio is a set of gedit snippets for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend the you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` -* Should have (have) +* Should include (include) - `collection |should| have(items)` + `collection |should| include(items)` * Should be into (into) `item |should| be_into(collection)` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be thrown by `exception |should| be_thrown_by(call)` ##Next steps Add snippets for django template tags and most common licences text. diff --git a/snippets/python.xml b/snippets/python.xml index 48b126f..60de0c0 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,263 +1,263 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> - <text><![CDATA[|should| have(${1:items}) + <text><![CDATA[|should| include(${1:items}) $0]]></text> <tag>have</tag> - <description>Should have</description> + <description>Should include</description> </snippet> <snippet> - <text><![CDATA[|should_not| have(${1:items}) + <text><![CDATA[|should_not| include(${1:items}) $0]]></text> <tag>nothave</tag> - <description>Should not have</description> + <description>Should not include</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should be equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not be equal to</description> </snippet> <snippet> <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> <tag>thrownby</tag> <description>Should be thrown by</description> </snippet> <snippet> <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> <tag>notthrownby</tag> <description>Should not be thrown by</description> </snippet> </snippets>
hugomaiavieira/batraquio
6a0ef35c7b95b3aae2e485f6b783bf4454f55788
Fixed be_thrown_by on README
diff --git a/README.md b/README.md index 8d4e1c8..1b9551d 100644 --- a/README.md +++ b/README.md @@ -1,194 +1,194 @@ #Batraquio Batraquio is a set of gedit snippets for python. The goal is help and speed up the development, mostly using BDD approach. I strongly recommend the you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. **Obs.:** I'm using *it* instead *test* in the methods because I use the [Specloud](http://github.com/hugobr/specloud) to run my specs. With that I can write specifications instead mere tests. ##Install To install, just do this on terminal: ./install.sh ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dsl](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should have (have) `collection |should| have(items)` * Should be into (into) `item |should| be_into(collection)` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` -* Should be throw by +* Should be thrown by - `exception |should| be_throw_by(call)` + `exception |should| be_thrown_by(call)` ##Next steps Add snippets for django template tags and most common licences text.
hugomaiavieira/batraquio
12c93b8acb03680c5de5da375d8b2e8bf3857215
fixed be_thrown_by snippet
diff --git a/snippets/python.xml b/snippets/python.xml index 7965e50..48b126f 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,263 +1,263 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| have(${1:items}) $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> <text><![CDATA[|should_not| have(${1:items}) $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should be equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not be equal to</description> </snippet> <snippet> <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> - <text><![CDATA[|should| be_throw_by(${1:call}) + <text><![CDATA[|should| be_thrown_by(${1:call}) $0]]></text> - <tag>throwby</tag> - <description>Should be throw by</description> + <tag>thrownby</tag> + <description>Should be thrown by</description> </snippet> <snippet> - <text><![CDATA[|should_not| be_throw_by(${1:call}) + <text><![CDATA[|should_not| be_thrown_by(${1:call}) $0]]></text> - <tag>notthrowby</tag> - <description>Should not be throw by</description> + <tag>notthrownby</tag> + <description>Should not be thrown by</description> </snippet> </snippets>
hugomaiavieira/batraquio
74019c91ddaf6512df690bd5c075d731f7c8b0b6
Improved install.
diff --git a/install.sh b/install.sh index d83f811..dc001ab 100755 --- a/install.sh +++ b/install.sh @@ -1,16 +1,31 @@ # Black magic to get the folder where the script is running FOLDER=$(cd $(dirname $0); pwd -P) # Create the gedit config folder if [ ! -d $HOME/.gnome2/gedit ] then mkdir -p ~/.gnome2/gedit fi # Copy Snippets if [ ! -d $HOME/.gnome2/gedit/snippets ] then mkdir -p ~/.gnome2/gedit/snippets + cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ +else + if [ ! -e ~/.gnome2/gedit/snippets/python.xml ] + then + cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ + else + echo -n 'The file python.xml already exist, do you want to replace it (y/n)? ' + read option + if [ $option = 'y' ] + then + cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ + echo 'File replaced.' + else + echo 'File not replaced.' + fi + fi fi -cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/
hugomaiavieira/batraquio
d0d756be677371ee4dce753d82594ac68b94daff
Add install instruction and next steps in README
diff --git a/README.md b/README.md index 485f31e..19b4f31 100644 --- a/README.md +++ b/README.md @@ -1,179 +1,190 @@ #Batraquio Batraquio is a set of gedit snippets for python. The goal of help and speed up the development, mostly using BDD approach. I strongly recommend the you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. +##Install + +To install, just do this on terminal: + + ./install.sh + ##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | ##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dls](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. ##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. ##Should-dsl [Should-dsl](http://github.com/hugobr/should-dsl) is an amazing python package that gives you a lot of matchers and turns your test/specs more readable. Batraquio has snippets for all matchers of should-dsl. What you have to do is type the left part of the matcher, then type the abbreviation of the matcher and press *Tab*. Doing this the rest of the matcher will appear just to you complete de right part of the matcher. For example: [1,2,3] anyof # Press Tab [1,2,3] |should| have_any_of(iterable) # Type the iterable [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below Below the description of all snippets for the matchers. ###Matcher (abbreviation) All of this have the not version, that you can get typing not before the abbreviatio, like the *Should not be* example. To be succinct, the not version will not be demonstrate. * Should be (be) `actual |should| be(expected)` * Should not be (notbe) `actual |should_not| be(expected)` * Should have (have) `collection |should| have(items)` * Should be into (into) `item |should| be_into(collection)` * Should be equal to (equal) `actual |should| be_equal_to(expect)` * Should have all of (allof) `collection |should| have_all_of(iterable)` * Should have any of (anyof) `collection |should| have_any_of(iterable)` * Should be ended with (ended) `string |should| be_ended_with(substring)` * Should be greater than (greater) `actual |should| be_greater_than(expected)` * Should be greater than or equal to (greaterequal) `actual |should| be_greater_than_or_equal_to(expected)` * Should be kind of (kind) `instance |should| be_kind_of(class)` * Should be less than (less) `actual |should| be_less_than(expected)` * Should be less than or equal to (lessequal) `actual |should| be_less_than_or_equal_to(expected)` * Should be equal to ignoring case (ignoring) `actual |should| be_equal_to_ignoring_case(expect)` * Should have in any order `collection |should| have_in_any_order(iterable)` * Should be like `string |should| be_like(regex)` * Should throw `call |should| throw(exception)` * Should be throw by `exception |should| be_throw_by(call)` + +##Next steps + +Add snippets for django template tags and most common licences text. +
hugomaiavieira/batraquio
efae2525a6af4b3bba3a52d29f28dc6a51251a50
Add should-dsl snippets in README
diff --git a/README.md b/README.md index 2249cc9..2e39aad 100644 --- a/README.md +++ b/README.md @@ -1,94 +1,187 @@ -Batraquio -======== +#Batraquio Batraquio is a set of gedit snippets for python. The goal of help and speed up the development, mostly using BDD approach. I strongly recommend the you install the [gmate](http://github.com/gmate/gmate) and the package gedit-plugins. -Smart def --------- +##Smart def The Smart def snippet speeds up the method definition. The activation is made with **Ctrl + u**. The examples below show the ways to use: Type the line below and press Ctrl + u with the cursor on the line it should return the sum of two numbers and you will have this (the | represents the cursor): def it_should_return_the_sum_of_two_numbers(self): | You can pass params too: it should return the sum of two numbers(number1, number2) And you will have this: def it_should_return_the_sum_of_two_numbers(self, number1, number2): | ----------------------------------------------------------------------- You can also do this... def it should return the sum of two numbers This... def it should return the sum of two numbers This... it should return the sum of two numbers: This... def it should return the sum of two numbers (): Or many combinations of fails syntax that you will have this: def it_should_return_the_sum_of_two_numbers(self): | -Unittest --------- +##Unittest Type **ut** and then press **Tab** and you get this: import unittest from should_dsl import * class ClassName(unittest.TestCase): | You only have to write the class name and press tab again. I assume that you use the amazing package [should-dls](http://github.com/hugobr/should-dsl) that gives you a lot of matchers and turns your test/specs more readable. -Step Definition ---------------- +##Step Definition This snippet is based on [freshen](http://github.com/rlisagor/freshen) step definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) and [lettuce](http://lettuce.it) too. The difference is that you should add manually the parameter *context* or *step* respectively. Type **sd** and press **Tab** and you get this: @Given/When/Then(r'step definition with params (.*)') def step_definition_with_params(var1): | You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or *step* for lettuce; press *Tab* and write the step definition; press *Tab* again and the method will be created. The name for the method is created replacing spaces for undescore on the step definition text. The params list is created based on the regex finded in the step definition text. + +##Should-dsl + +Should-dsl is an amazing python package [should-dls](http://github.com/hugobr/should-dsl) +that gives you a lot of matchers and turns your test/specs more readable. + +Batraquio has snippets for all matchers of should-dsl. What you have to do is +type the left part of the matcher, then type the abbreviation of the matcher and +press *Tab*. Doing this the rest of the matcher will appear just to you complete +de right part of the matcher. + +For example: + + [1,2,3] anyof # Press Tab + [1,2,3] |should| have_any_of(iterable) # Type the iterable + [1,2,3] |should| have_any_of([1]) # Press Tab again to go to a new line below + +Below the description of all snippets for the matchers. + +###Matcher (abbreviation) + +All of this have the not version, that you can get typing not before the +abbreviatio, like the *Should not be* example. To be succinct, the not version +will not be demonstrate. + +* Should be (be) + + actual |should| be(expected) + +* Should not be (notbe) + + actual |should_not| be(expected) + +* Should have (have) + + collection |should| have(items) + +* Should be into (into) + + item |should| be_into(collection) + +* Should be equal to (equal) + + actual |should| be_equal_to(expect) + +* Should have all of (allof) + + collection |should| have_all_of(iterable) + +* Should have any of (anyof) + + collection |should| have_any_of(iterable) + +* Should be ended with (ended) + + string |should| be_ended_with(substring) + +* Should be greater than (greater) + + actual |should| be_greater_than(expected) + +* Should be greater than or equal to (greaterequal) + + actual |should| be_greater_than_or_equal_to(expected) + +* Should be kind of (kind) + + instance |should| be_kind_of(class) + +* Should be less than (less) + + actual |should| be_less_than(expected) + +* Should be less than or equal to (lessequal) + + actual |should| be_less_than_or_equal_to(expected) + +* Should be equal to ignoring case (ignoring) + + actual |should| be_equal_to_ignoring_case(expect) + +* Should have in any order + + collection |should| have_in_any_order(iterable) + +* Should be like + + string |should| be_like(regex) + +* Should throw + + call |should| throw(exception) + +* Should be throw by + + exception |should| be_throw_by(call) + diff --git a/snippets/python.xml b/snippets/python.xml index 61d9037..7965e50 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,263 +1,263 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> <text><![CDATA[|should| have(${1:items}) $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> <text><![CDATA[|should_not| have(${1:items}) $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should be equal to</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not be equal to</description> </snippet> <snippet> - <text><![CDATA[|should| have_all_of(${1:items}) + <text><![CDATA[|should| have_all_of(${1:iterable}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> - <text><![CDATA[|should_not| have_all_of(${1:items}) + <text><![CDATA[|should_not| have_all_of(${1:iterable}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> - <text><![CDATA[|should| have_any_of(${1:items}) + <text><![CDATA[|should| have_any_of(${1:iterable}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> - <text><![CDATA[|should_not| have_any_of(${1:items}) + <text><![CDATA[|should_not| have_any_of(${1:iterable}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> - <text><![CDATA[|should| be_greater_than(${1:smaller}) + <text><![CDATA[|should| be_greater_than(${1:expected}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> - <text><![CDATA[|should_not| be_greater_than(${1:smaller}) + <text><![CDATA[|should_not| be_greater_than(${1:expected}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> - <text><![CDATA[|should| be_greater_than_or_equal_to(${1:smaller}) + <text><![CDATA[|should| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> - <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:smaller}) + <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:expected}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> - <text><![CDATA[|should| be_less_than(${1:bigger}) + <text><![CDATA[|should| be_less_than(${1:expected}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> - <text><![CDATA[|should_not| be_less_than(${1:bigger}) + <text><![CDATA[|should_not| be_less_than(${1:expected}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> - <text><![CDATA[|should| be_less_than_or_equal_to(${1:bigger}) + <text><![CDATA[|should| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> - <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:bigger}) + <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:expected}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> - <text><![CDATA[|should| have_in_any_order(${1:items}) + <text><![CDATA[|should| have_in_any_order(${1:iterable}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> - <text><![CDATA[|should_not| have_in_any_order(${1:items}) + <text><![CDATA[|should_not| have_in_any_order(${1:iterable}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> - <text><![CDATA[|should| be_throw_by(${1:raiser}) + <text><![CDATA[|should| be_throw_by(${1:call}) $0]]></text> <tag>throwby</tag> <description>Should be throw by</description> </snippet> <snippet> - <text><![CDATA[|should_not| be_throw_by(${1:raiser}) + <text><![CDATA[|should_not| be_throw_by(${1:call}) $0]]></text> <tag>notthrowby</tag> <description>Should not be throw by</description> </snippet> </snippets>
hugomaiavieira/batraquio
72231c4722738052dc5422132d55df1a04e349fc
Removed the first parameter of should-dsl snippets
diff --git a/snippets/python.xml b/snippets/python.xml index 3164221..61d9037 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,263 +1,263 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should| be(${2:expected}) + <text><![CDATA[|should| be(${1:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_not| be(${2:expected}) + <text><![CDATA[|should_not| be(${1:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should| have(${2:items}) + <text><![CDATA[|should| have(${1:items}) $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_not| have(${2:items}) + <text><![CDATA[|should_not| have(${1:items}) $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> - <text><![CDATA[${1:items} |should| be_into(${2:collection}) + <text><![CDATA[|should| be_into(${1:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> - <text><![CDATA[${1:items} |should_not| be_into(${2:collection}) + <text><![CDATA[|should_not| be_into(${1:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should| be_equal_to(${2:expect}) + <text><![CDATA[|should| be_equal_to(${1:expect}) $0]]></text> <tag>equal</tag> <description>Should be equal to</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_not| be_equal_to(${2:expect}) + <text><![CDATA[|should_not| be_equal_to(${1:expect}) $0]]></text> <tag>notequal</tag> <description>Should not be equal to</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should| have_all_of(${2:items}) + <text><![CDATA[|should| have_all_of(${1:items}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_not| have_all_of(${2:items}) + <text><![CDATA[|should_not| have_all_of(${1:items}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should| have_any_of(${2:items}) + <text><![CDATA[|should| have_any_of(${1:items}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_not| have_any_of(${2:items}) + <text><![CDATA[|should_not| have_any_of(${1:items}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> - <text><![CDATA[${1:string} |should| be_ended_with(${2:substring}) + <text><![CDATA[|should| be_ended_with(${1:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> - <text><![CDATA[${1:string} |should_not| be_ended_with(${2:substring}) + <text><![CDATA[|should_not| be_ended_with(${1:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> - <text><![CDATA[${1:bigger} |should| be_greater_than(${2:smaller}) + <text><![CDATA[|should| be_greater_than(${1:smaller}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> - <text><![CDATA[${1:bigger} |should_not| be_greater_than(${2:smaller}) + <text><![CDATA[|should_not| be_greater_than(${1:smaller}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> - <text><![CDATA[${1:bigger} |should| be_greater_than_or_equal_to(${2:smaller}) + <text><![CDATA[|should| be_greater_than_or_equal_to(${1:smaller}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> - <text><![CDATA[${1:bigger} |should_not| be_greater_than_or_equal_to(${2:smaller}) + <text><![CDATA[|should_not| be_greater_than_or_equal_to(${1:smaller}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> - <text><![CDATA[${1:instance} |should| be_kind_of(${2:class}) + <text><![CDATA[|should| be_kind_of(${1:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> - <text><![CDATA[${1:instance} |should_not| be_kind_of(${2:class}) + <text><![CDATA[|should_not| be_kind_of(${1:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> - <text><![CDATA[${1:smaller} |should| be_less_than(${2:bigger}) + <text><![CDATA[|should| be_less_than(${1:bigger}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> - <text><![CDATA[${1:smaller} |should_not| be_less_than(${2:bigger}) + <text><![CDATA[|should_not| be_less_than(${1:bigger}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> - <text><![CDATA[${1:smaller} |should| be_less_than_or_equal_to(${2:bigger}) + <text><![CDATA[|should| be_less_than_or_equal_to(${1:bigger}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> - <text><![CDATA[${1:smaller} |should_not| be_less_than_or_equal_to(${2:bigger}) + <text><![CDATA[|should_not| be_less_than_or_equal_to(${1:bigger}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should| be_equal_to_ignoring_case(${2:expect}) + <text><![CDATA[|should| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_not| be_equal_to_ignoring_case(${2:expect}) + <text><![CDATA[|should_not| be_equal_to_ignoring_case(${1:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should| have_in_any_order(${2:items}) + <text><![CDATA[|should| have_in_any_order(${1:items}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_not| have_in_any_order(${2:items}) + <text><![CDATA[|should_not| have_in_any_order(${1:items}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> - <text><![CDATA[${1:string} |should| be_like(${2:regex}) + <text><![CDATA[|should| be_like(${1:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> - <text><![CDATA[${1:string} |should_not| be_like(${2:regex}) + <text><![CDATA[|should_not| be_like(${1:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> - <text><![CDATA[${1:raiser} |should| throw(${2:exception}) + <text><![CDATA[|should| throw(${1:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> - <text><![CDATA[${1:raiser} |should_not| throw(${2:exception}) + <text><![CDATA[|should_not| throw(${1:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> - <text><![CDATA[${1:exception} |should| be_throw_by(${2:raiser}) + <text><![CDATA[|should| be_throw_by(${1:raiser}) $0]]></text> <tag>throwby</tag> <description>Should be throw by</description> </snippet> <snippet> - <text><![CDATA[${1:exception} |should_not| be_throw_by(${2:raiser}) + <text><![CDATA[|should_not| be_throw_by(${1:raiser}) $0]]></text> <tag>notthrowby</tag> <description>Should not be throw by</description> </snippet> </snippets>
hugomaiavieira/batraquio
5e6858af8de0e77875b9e446c10a3cc6c9cc6869
Modified should-dsl matchers for the new usage
diff --git a/snippets/python.xml b/snippets/python.xml index 5799919..3164221 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,262 +1,263 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_be| ${2:expected} + <text><![CDATA[${1:actual} |should| be(${2:expected}) $0]]></text> <tag>be</tag> <description>Should be</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_not_be| ${2:expected} + <text><![CDATA[${1:actual} |should_not| be(${2:expected}) $0]]></text> <tag>notbe</tag> <description>Should not be</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_have| ${2:items} + <text><![CDATA[${1:collection} |should| have(${2:items}) $0]]></text> <tag>have</tag> <description>Should have</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_not_have| ${2:items} + <text><![CDATA[${1:collection} |should_not| have(${2:items}) $0]]></text> <tag>nothave</tag> <description>Should not have</description> </snippet> <snippet> - <text><![CDATA[${1:items} |should_be| into(${2:collection}) + <text><![CDATA[${1:items} |should| be_into(${2:collection}) $0]]></text> <tag>into</tag> <description>Should be into</description> </snippet> <snippet> - <text><![CDATA[${1:items} |should_not_be| into(${2:collection}) + <text><![CDATA[${1:items} |should_not| be_into(${2:collection}) $0]]></text> <tag>notinto</tag> <description>Should not be into</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_be| equal_to({2:expect}) + <text><![CDATA[${1:actual} |should| be_equal_to(${2:expect}) $0]]></text> <tag>equal</tag> <description>Should be equal to</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_not_be| equal_to({2:expect}) + <text><![CDATA[${1:actual} |should_not| be_equal_to(${2:expect}) $0]]></text> <tag>notequal</tag> <description>Should not be equal to</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_have| all_of({2:items}) + <text><![CDATA[${1:collection} |should| have_all_of(${2:items}) $0]]></text> <tag>allof</tag> <description>Should have all of</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_not_have| all_of({2:items}) + <text><![CDATA[${1:collection} |should_not| have_all_of(${2:items}) $0]]></text> <tag>notallof</tag> <description>Should not have all of</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_have| any_of({2:items}) + <text><![CDATA[${1:collection} |should| have_any_of(${2:items}) $0]]></text> <tag>anyof</tag> <description>Should have any of</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_not_have| any_of({2:items}) + <text><![CDATA[${1:collection} |should_not| have_any_of(${2:items}) $0]]></text> <tag>notanyof</tag> <description>Should not have any of</description> </snippet> <snippet> - <text><![CDATA[${1:string} |should_be| ended_with({2:substring}) + <text><![CDATA[${1:string} |should| be_ended_with(${2:substring}) $0]]></text> <tag>ended</tag> <description>Should be ended with</description> </snippet> <snippet> - <text><![CDATA[${1:string} |should_not_be| ended_with({2:substring}) + <text><![CDATA[${1:string} |should_not| be_ended_with(${2:substring}) $0]]></text> <tag>notended</tag> <description>Should not be ended with</description> </snippet> <snippet> - <text><![CDATA[${1:bigger} |should_be| greater_than({2:smaller}) + <text><![CDATA[${1:bigger} |should| be_greater_than(${2:smaller}) $0]]></text> <tag>greater</tag> <description>Should be greater than</description> </snippet> <snippet> - <text><![CDATA[${1:bigger} |should_not_be| greater_than({2:smaller}) + <text><![CDATA[${1:bigger} |should_not| be_greater_than(${2:smaller}) $0]]></text> <tag>notgreater</tag> <description>Should not be greater than</description> </snippet> <snippet> - <text><![CDATA[${1:bigger} |should_be| greater_than_or_equal_to({2:smaller}) + <text><![CDATA[${1:bigger} |should| be_greater_than_or_equal_to(${2:smaller}) $0]]></text> <tag>greaterequal</tag> <description>Should be greater than or equal to</description> </snippet> <snippet> - <text><![CDATA[${1:bigger} |should_not_be| greater_than_or_equal_to({2:smaller}) + <text><![CDATA[${1:bigger} |should_not| be_greater_than_or_equal_to(${2:smaller}) $0]]></text> <tag>notgreaterequal</tag> <description>Should not be greater than or equal to</description> </snippet> <snippet> - <text><![CDATA[${1:instance} |should_be| kind_of({2:class}) + <text><![CDATA[${1:instance} |should| be_kind_of(${2:class}) $0]]></text> <tag>kind</tag> <description>Should be kind of</description> </snippet> <snippet> - <text><![CDATA[${1:instance} |should_not_be| kind_of({2:class}) + <text><![CDATA[${1:instance} |should_not| be_kind_of(${2:class}) $0]]></text> <tag>notkind</tag> <description>Should not be kind of</description> </snippet> <snippet> - <text><![CDATA[${1:smaller} |should_be| less_than({2:bigger}) + <text><![CDATA[${1:smaller} |should| be_less_than(${2:bigger}) $0]]></text> <tag>less</tag> <description>Should be less than</description> </snippet> <snippet> - <text><![CDATA[${1:smaller} |should_not_be| less_than({2:bigger}) + <text><![CDATA[${1:smaller} |should_not| be_less_than(${2:bigger}) $0]]></text> <tag>notless</tag> <description>Should not be less than</description> </snippet> <snippet> - <text><![CDATA[${1:smaller} |should_be| less_than_or_equal_to({2:bigger}) + <text><![CDATA[${1:smaller} |should| be_less_than_or_equal_to(${2:bigger}) $0]]></text> <tag>lessequal</tag> <description>Should be less than or equal to</description> </snippet> <snippet> - <text><![CDATA[${1:smaller} |should_not_be| less_than_or_equal_to({2:bigger}) + <text><![CDATA[${1:smaller} |should_not| be_less_than_or_equal_to(${2:bigger}) $0]]></text> <tag>notlessequal</tag> <description>Should not be less than or equal to</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_be| equal_to_ignoring_case({2:expect}) + <text><![CDATA[${1:actual} |should| be_equal_to_ignoring_case(${2:expect}) $0]]></text> <tag>equalignoring</tag> <description>Should be equal to ignoring case</description> </snippet> <snippet> - <text><![CDATA[${1:actual} |should_not_be| equal_to_ignoring_case({2:expect}) + <text><![CDATA[${1:actual} |should_not| be_equal_to_ignoring_case(${2:expect}) $0]]></text> <tag>notequalignoring</tag> <description>Should not be equal to ignoring case</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_have| in_any_order({2:items}) + <text><![CDATA[${1:collection} |should| have_in_any_order(${2:items}) $0]]></text> <tag>anyorder</tag> <description>Should have in any order</description> </snippet> <snippet> - <text><![CDATA[${1:collection} |should_not_have| in_any_order({2:items}) + <text><![CDATA[${1:collection} |should_not| have_in_any_order(${2:items}) $0]]></text> <tag>notanyorder</tag> <description>Should not have in any order</description> </snippet> <snippet> - <text><![CDATA[${1:string} |should_be| like(${2:regex}) + <text><![CDATA[${1:string} |should| be_like(${2:regex}) $0]]></text> <tag>like</tag> <description>Should be like</description> </snippet> <snippet> - <text><![CDATA[${1:string} |should_not_be| like(${2:regex}) + <text><![CDATA[${1:string} |should_not| be_like(${2:regex}) $0]]></text> <tag>notlike</tag> <description>Should not be like</description> </snippet> <snippet> <text><![CDATA[${1:raiser} |should| throw(${2:exception}) $0]]></text> <tag>throw</tag> <description>Should throw</description> </snippet> <snippet> <text><![CDATA[${1:raiser} |should_not| throw(${2:exception}) $0]]></text> <tag>notthrow</tag> <description>Should not throw</description> </snippet> <snippet> - <text><![CDATA[${1:exception} |should_be| throw_by(${2:raiser}) + <text><![CDATA[${1:exception} |should| be_throw_by(${2:raiser}) $0]]></text> <tag>throwby</tag> <description>Should be throw by</description> </snippet> <snippet> - <text><![CDATA[${1:exception} |should_not_be| throw_by(${2:raiser}) + <text><![CDATA[${1:exception} |should_not| be_throw_by(${2:raiser}) $0]]></text> <tag>notthrowby</tag> <description>Should not be throw by</description> </snippet> </snippets> +
hugomaiavieira/batraquio
89957c2e94c352d69cfe1e16e09bf8f07043578e
Add all should-dsl matchers
diff --git a/should-dsl.py b/should-dsl.py index e5c432a..4546bc6 100644 --- a/should-dsl.py +++ b/should-dsl.py @@ -1,153 +1,154 @@ # This is a temporary file!! * all_of * any_of * be * ended_with * equal # Documentação errada. O certo é equal_to ou be_equal_to * equal_to_ignoring_case * greater_than_or_equal_to * greater_than * in_any_order * into * kind_of * less_than_or_equal_to * less_than * like * throw * thrown_by # should be (b) ${1:actual} |should_be| ${2:expected} $0 # should not be (nb) ${1:actual} |should_not_be| ${2:expected} $0 # Should have (h) ${1:collection} |should_have| ${2:items} $0 # Should not have (nh) ${1:collection} |should_not_have| ${2:items} $0 # Should be into (i) ${1:items} |should_be| into(${2:collection}) $0 # Should not be into (ni) ${1:items} |should_not_be| into(${2:collection}) $0 # Should be equal to (et) ${1:actual} |should_be| equal_to({2:expect}) $0 # Should not be equal to (net) ${1:actual} |should_not_be| equal_to({2:expect}) $0 # Should have all of (allof) ${1:collection} |should_have| all_of({2:items}) $0 # Should not have all of (nallof) ${1:collection} |should_not_have| all_of({2:items}) $0 # Should have any of (anyof) ${1:collection} |should_have| any_of({2:items}) $0 # Should not have any of (nanyof) ${1:collection} |should_not_have| any_of({2:items}) $0 # Should be ended with (ew) ${1:string} |should_be| ended_with({2:substring}) $0 # Should not be ended with (new) ${1:string} |should_not_be| ended_with({2:substring}) $0 # Should be greater than (g) ${1:bigger} |should_be| greater_than({2:smaller}) $0 # Should not be greater than (ng) ${1:bigger} |should_not_be| greater_than({2:smaller}) $0 # Should be greater than or equal to (ge) ${1:bigger} |should_be| greater_than_or_equal_to({2:smaller}) $0 # Should not be greater than or equal to (nge) ${1:bigger} |should_not_be| greater_than_or_equal_to({2:smaller}) $0 # Should be kind of (ko) ${1:instance} |should_be| kind_of({2:class}) $0 # Should not be kind of (nko) ${1:instance} |should_not_be| kind_of({2:class}) $0 # Should be less than (l) ${1:smaller} |should_be| less_than({2:bigger}) $0 # Should not be less than (nl) ${1:smaller} |should_not_be| less_than({2:bigger}) $0 # Should be less than or equal to (le) ${1:smaller} |should_be| less_than_or_equal_to({2:bigger}) $0 # Should not be less than or equal to (nle) ${1:smaller} |should_not_be| less_than_or_equal_to({2:bigger}) $0 # Should be equal to ignoring case (etic) ${1:actual} |should_be| equal_to_ignoring_case({2:expect}) $0 # Should not be equal to ignoring case (netic) ${1:actual} |should_not_be| equal_to_ignoring_case({2:expect}) $0 # Should have in any order (anyorder) ${1:collection} |should_have| in_any_order({2:items}) $0 # Should not have in any order (nanyorder) ${1:collection} |should_not_have| in_any_order({2:items}) +$0 # should be like (bl) ${1:string} |should_be| like(${2:regex}) $0 # should not be like (nbl) ${1:string} |should_not_be| like(${2:regex}) $0 # should throw (t) ${1:raiser} |should| throw(${2:exception}) $0 # should not throw (nt) ${1:raiser} |should_not| throw(${2:exception}) $0 # should be throw by (t) ${1:exception} |should_be| throw_by(${2:raiser}) $0 # should not be throw by (nt) ${1:exception} |should_not_be| throw_by(${2:raiser}) $0 diff --git a/snippets/python.xml b/snippets/python.xml index 30d156d..5799919 100644 --- a/snippets/python.xml +++ b/snippets/python.xml @@ -1,59 +1,262 @@ <?xml version='1.0' encoding='utf-8'?> <snippets language="python"> <snippet> <text><![CDATA[$< import re global white_spaces white_spaces = '' regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') regex=regex.match($GEDIT_CURRENT_LINE) if regex: dictionary=regex.groupdict() method=dictionary['method'].replace(' ','_') white_spaces=dictionary['white_spaces'] params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' result = white_spaces + 'def ' + method + '(' + params + '):' else: result = $GEDIT_CURRENT_LINE return result > $<return white_spaces>]]></text> <accelerator><![CDATA[<Control>u]]></accelerator> <description>Smart def</description> </snippet> <snippet> <text><![CDATA[import unittest from should_dsl import * class ${1:ClassName}(unittest.TestCase): ]]></text> <tag>ut</tag> <description>Unittest</description> </snippet> <snippet> <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') $< import re params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) params_number = len(params_list) params = '' for number in range(params_number): params += 'var' + str(number+1) if number+1 != params_number: params += ' ,' step = ${2}.lower() for param in params_list: step = step.replace(param, '') step = re.sub(r'\s+$', '', step) step = re.sub(r'\s+', '_', step) result = 'def ' + step + '(' + params + '):' return result > $0]]></text> <tag>sd</tag> <description>Step definition</description> </snippet> + <snippet> + <text><![CDATA[${1:actual} |should_be| ${2:expected} +$0]]></text> + <tag>be</tag> + <description>Should be</description> + </snippet> + <snippet> + <text><![CDATA[${1:actual} |should_not_be| ${2:expected} +$0]]></text> + <tag>notbe</tag> + <description>Should not be</description> + </snippet> + <snippet> + <text><![CDATA[${1:collection} |should_have| ${2:items} +$0]]></text> + <tag>have</tag> + <description>Should have</description> + </snippet> + <snippet> + <text><![CDATA[${1:collection} |should_not_have| ${2:items} +$0]]></text> + <tag>nothave</tag> + <description>Should not have</description> + </snippet> + <snippet> + <text><![CDATA[${1:items} |should_be| into(${2:collection}) +$0]]></text> + <tag>into</tag> + <description>Should be into</description> + </snippet> + <snippet> + <text><![CDATA[${1:items} |should_not_be| into(${2:collection}) +$0]]></text> + <tag>notinto</tag> + <description>Should not be into</description> + </snippet> + <snippet> + <text><![CDATA[${1:actual} |should_be| equal_to({2:expect}) +$0]]></text> + <tag>equal</tag> + <description>Should be equal to</description> + </snippet> + <snippet> + <text><![CDATA[${1:actual} |should_not_be| equal_to({2:expect}) +$0]]></text> + <tag>notequal</tag> + <description>Should not be equal to</description> + </snippet> + <snippet> + <text><![CDATA[${1:collection} |should_have| all_of({2:items}) +$0]]></text> + <tag>allof</tag> + <description>Should have all of</description> + </snippet> + <snippet> + <text><![CDATA[${1:collection} |should_not_have| all_of({2:items}) +$0]]></text> + <tag>notallof</tag> + <description>Should not have all of</description> + </snippet> + <snippet> + <text><![CDATA[${1:collection} |should_have| any_of({2:items}) +$0]]></text> + <tag>anyof</tag> + <description>Should have any of</description> + </snippet> + <snippet> + <text><![CDATA[${1:collection} |should_not_have| any_of({2:items}) +$0]]></text> + <tag>notanyof</tag> + <description>Should not have any of</description> + </snippet> + <snippet> + <text><![CDATA[${1:string} |should_be| ended_with({2:substring}) +$0]]></text> + <tag>ended</tag> + <description>Should be ended with</description> + </snippet> + <snippet> + <text><![CDATA[${1:string} |should_not_be| ended_with({2:substring}) +$0]]></text> + <tag>notended</tag> + <description>Should not be ended with</description> + </snippet> + <snippet> + <text><![CDATA[${1:bigger} |should_be| greater_than({2:smaller}) +$0]]></text> + <tag>greater</tag> + <description>Should be greater than</description> + </snippet> + <snippet> + <text><![CDATA[${1:bigger} |should_not_be| greater_than({2:smaller}) +$0]]></text> + <tag>notgreater</tag> + <description>Should not be greater than</description> + </snippet> + <snippet> + <text><![CDATA[${1:bigger} |should_be| greater_than_or_equal_to({2:smaller}) +$0]]></text> + <tag>greaterequal</tag> + <description>Should be greater than or equal to</description> + </snippet> + <snippet> + <text><![CDATA[${1:bigger} |should_not_be| greater_than_or_equal_to({2:smaller}) +$0]]></text> + <tag>notgreaterequal</tag> + <description>Should not be greater than or equal to</description> + </snippet> + <snippet> + <text><![CDATA[${1:instance} |should_be| kind_of({2:class}) +$0]]></text> + <tag>kind</tag> + <description>Should be kind of</description> + </snippet> + <snippet> + <text><![CDATA[${1:instance} |should_not_be| kind_of({2:class}) +$0]]></text> + <tag>notkind</tag> + <description>Should not be kind of</description> + </snippet> + <snippet> + <text><![CDATA[${1:smaller} |should_be| less_than({2:bigger}) +$0]]></text> + <tag>less</tag> + <description>Should be less than</description> + </snippet> + <snippet> + <text><![CDATA[${1:smaller} |should_not_be| less_than({2:bigger}) +$0]]></text> + <tag>notless</tag> + <description>Should not be less than</description> + </snippet> + <snippet> + <text><![CDATA[${1:smaller} |should_be| less_than_or_equal_to({2:bigger}) +$0]]></text> + <tag>lessequal</tag> + <description>Should be less than or equal to</description> + </snippet> + <snippet> + <text><![CDATA[${1:smaller} |should_not_be| less_than_or_equal_to({2:bigger}) +$0]]></text> + <tag>notlessequal</tag> + <description>Should not be less than or equal to</description> + </snippet> + <snippet> + <text><![CDATA[${1:actual} |should_be| equal_to_ignoring_case({2:expect}) +$0]]></text> + <tag>equalignoring</tag> + <description>Should be equal to ignoring case</description> + </snippet> + <snippet> + <text><![CDATA[${1:actual} |should_not_be| equal_to_ignoring_case({2:expect}) +$0]]></text> + <tag>notequalignoring</tag> + <description>Should not be equal to ignoring case</description> + </snippet> + <snippet> + <text><![CDATA[${1:collection} |should_have| in_any_order({2:items}) +$0]]></text> + <tag>anyorder</tag> + <description>Should have in any order</description> + </snippet> + <snippet> + <text><![CDATA[${1:collection} |should_not_have| in_any_order({2:items}) +$0]]></text> + <tag>notanyorder</tag> + <description>Should not have in any order</description> + </snippet> + <snippet> + <text><![CDATA[${1:string} |should_be| like(${2:regex}) +$0]]></text> + <tag>like</tag> + <description>Should be like</description> + </snippet> + <snippet> + <text><![CDATA[${1:string} |should_not_be| like(${2:regex}) +$0]]></text> + <tag>notlike</tag> + <description>Should not be like</description> + </snippet> + <snippet> + <text><![CDATA[${1:raiser} |should| throw(${2:exception}) +$0]]></text> + <tag>throw</tag> + <description>Should throw</description> + </snippet> + <snippet> + <text><![CDATA[${1:raiser} |should_not| throw(${2:exception}) +$0]]></text> + <tag>notthrow</tag> + <description>Should not throw</description> + </snippet> + <snippet> + <text><![CDATA[${1:exception} |should_be| throw_by(${2:raiser}) +$0]]></text> + <tag>throwby</tag> + <description>Should be throw by</description> + </snippet> + <snippet> + <text><![CDATA[${1:exception} |should_not_be| throw_by(${2:raiser}) +$0]]></text> + <tag>notthrowby</tag> + <description>Should not be throw by</description> + </snippet> </snippets> -
hugomaiavieira/batraquio
6e9d9ab8a43ec8c88660c7e4cbd6aac7e97c5635
Finished the should-dsl matchers in the temporary file
diff --git a/README.md b/README.md new file mode 100644 index 0000000..2249cc9 --- /dev/null +++ b/README.md @@ -0,0 +1,94 @@ +Batraquio +======== + +Batraquio is a set of gedit snippets for python. The goal of help and speed up +the development, mostly using BDD approach. + +I strongly recommend the you install the [gmate](http://github.com/gmate/gmate) +and the package gedit-plugins. + +Smart def +-------- + +The Smart def snippet speeds up the method definition. The activation is made +with **Ctrl + u**. The examples below show the ways to use: + +Type the line below and press Ctrl + u with the cursor on the line + + it should return the sum of two numbers + +and you will have this (the | represents the cursor): + + def it_should_return_the_sum_of_two_numbers(self): + | + +You can pass params too: + + it should return the sum of two numbers(number1, number2) + +And you will have this: + + def it_should_return_the_sum_of_two_numbers(self, number1, number2): + | + +----------------------------------------------------------------------- + +You can also do this... + + def it should return the sum of two numbers + +This... + + def it should return the sum of two numbers + +This... + + it should return the sum of two numbers: + +This... + + def it should return the sum of two numbers (): + +Or many combinations of fails syntax that you will have this: + + def it_should_return_the_sum_of_two_numbers(self): + | + + +Unittest +-------- + +Type **ut** and then press **Tab** and you get this: + + import unittest + from should_dsl import * + + class ClassName(unittest.TestCase): + | + +You only have to write the class name and press tab again. + +I assume that you use the amazing package [should-dls](http://github.com/hugobr/should-dsl) +that gives you a lot of matchers and turns your test/specs more readable. + + +Step Definition +--------------- + +This snippet is based on [freshen](http://github.com/rlisagor/freshen) step +definition, but is functional for [pycukes](http://github.com/hugobr/pycukes) +and [lettuce](http://lettuce.it) too. The difference is that you should add +manually the parameter *context* or *step* respectively. + +Type **sd** and press **Tab** and you get this: + + @Given/When/Then(r'step definition with params (.*)') + def step_definition_with_params(var1): + | + +You only have to write *Given*, *When* or *Then* (for freshen or pycukes) or +*step* for lettuce; press *Tab* and write the step definition; press *Tab* again +and the method will be created. The name for the method is created replacing +spaces for undescore on the step definition text. The params list is created +based on the regex finded in the step definition text. + diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..d83f811 --- /dev/null +++ b/install.sh @@ -0,0 +1,16 @@ +# Black magic to get the folder where the script is running +FOLDER=$(cd $(dirname $0); pwd -P) + +# Create the gedit config folder +if [ ! -d $HOME/.gnome2/gedit ] +then + mkdir -p ~/.gnome2/gedit +fi + +# Copy Snippets +if [ ! -d $HOME/.gnome2/gedit/snippets ] +then + mkdir -p ~/.gnome2/gedit/snippets +fi +cp $FOLDER/snippets/* ~/.gnome2/gedit/snippets/ + diff --git a/should-dsl.py b/should-dsl.py new file mode 100644 index 0000000..e5c432a --- /dev/null +++ b/should-dsl.py @@ -0,0 +1,153 @@ +# This is a temporary file!! + * all_of + * any_of + * be + * ended_with + * equal # Documentação errada. O certo é equal_to ou be_equal_to + * equal_to_ignoring_case + * greater_than_or_equal_to + * greater_than + * in_any_order + * into + * kind_of + * less_than_or_equal_to + * less_than + * like + * throw + * thrown_by + +# should be (b) +${1:actual} |should_be| ${2:expected} +$0 + +# should not be (nb) +${1:actual} |should_not_be| ${2:expected} +$0 + +# Should have (h) +${1:collection} |should_have| ${2:items} +$0 + +# Should not have (nh) +${1:collection} |should_not_have| ${2:items} +$0 + +# Should be into (i) +${1:items} |should_be| into(${2:collection}) +$0 + +# Should not be into (ni) +${1:items} |should_not_be| into(${2:collection}) +$0 + +# Should be equal to (et) +${1:actual} |should_be| equal_to({2:expect}) +$0 + +# Should not be equal to (net) +${1:actual} |should_not_be| equal_to({2:expect}) +$0 + +# Should have all of (allof) +${1:collection} |should_have| all_of({2:items}) +$0 + +# Should not have all of (nallof) +${1:collection} |should_not_have| all_of({2:items}) +$0 + +# Should have any of (anyof) +${1:collection} |should_have| any_of({2:items}) +$0 + +# Should not have any of (nanyof) +${1:collection} |should_not_have| any_of({2:items}) +$0 + +# Should be ended with (ew) +${1:string} |should_be| ended_with({2:substring}) +$0 + +# Should not be ended with (new) +${1:string} |should_not_be| ended_with({2:substring}) +$0 + +# Should be greater than (g) +${1:bigger} |should_be| greater_than({2:smaller}) +$0 + +# Should not be greater than (ng) +${1:bigger} |should_not_be| greater_than({2:smaller}) +$0 + +# Should be greater than or equal to (ge) +${1:bigger} |should_be| greater_than_or_equal_to({2:smaller}) +$0 + +# Should not be greater than or equal to (nge) +${1:bigger} |should_not_be| greater_than_or_equal_to({2:smaller}) +$0 + +# Should be kind of (ko) +${1:instance} |should_be| kind_of({2:class}) +$0 + +# Should not be kind of (nko) +${1:instance} |should_not_be| kind_of({2:class}) +$0 + +# Should be less than (l) +${1:smaller} |should_be| less_than({2:bigger}) +$0 + +# Should not be less than (nl) +${1:smaller} |should_not_be| less_than({2:bigger}) +$0 + +# Should be less than or equal to (le) +${1:smaller} |should_be| less_than_or_equal_to({2:bigger}) +$0 + +# Should not be less than or equal to (nle) +${1:smaller} |should_not_be| less_than_or_equal_to({2:bigger}) +$0 + +# Should be equal to ignoring case (etic) +${1:actual} |should_be| equal_to_ignoring_case({2:expect}) +$0 + +# Should not be equal to ignoring case (netic) +${1:actual} |should_not_be| equal_to_ignoring_case({2:expect}) +$0 + +# Should have in any order (anyorder) +${1:collection} |should_have| in_any_order({2:items}) +$0 + +# Should not have in any order (nanyorder) +${1:collection} |should_not_have| in_any_order({2:items}) + +# should be like (bl) +${1:string} |should_be| like(${2:regex}) +$0 + +# should not be like (nbl) +${1:string} |should_not_be| like(${2:regex}) +$0 + +# should throw (t) +${1:raiser} |should| throw(${2:exception}) +$0 + +# should not throw (nt) +${1:raiser} |should_not| throw(${2:exception}) +$0 + +# should be throw by (t) +${1:exception} |should_be| throw_by(${2:raiser}) +$0 + +# should not be throw by (nt) +${1:exception} |should_not_be| throw_by(${2:raiser}) +$0 + diff --git a/snippets/python.xml b/snippets/python.xml new file mode 100644 index 0000000..30d156d --- /dev/null +++ b/snippets/python.xml @@ -0,0 +1,59 @@ +<?xml version='1.0' encoding='utf-8'?> +<snippets language="python"> + <snippet> + <text><![CDATA[$< +import re +global white_spaces +white_spaces = '' +regex=re.compile(r'(?P<white_spaces\>\s*)(def )?(?P<method\>[_ \w]+\w)[ ]?(\((?P<params\>.*)\))?:?') +regex=regex.match($GEDIT_CURRENT_LINE) +if regex: + dictionary=regex.groupdict() + method=dictionary['method'].replace(' ','_') + white_spaces=dictionary['white_spaces'] + params= dictionary['params'] and 'self, ' + dictionary['params'] or 'self' + result = white_spaces + 'def ' + method + '(' + params + '):' +else: + result = $GEDIT_CURRENT_LINE +return result +> + $<return white_spaces>]]></text> + <accelerator><![CDATA[<Control>u]]></accelerator> + <description>Smart def</description> + </snippet> + <snippet> + <text><![CDATA[import unittest +from should_dsl import * + +class ${1:ClassName}(unittest.TestCase): + ]]></text> + <tag>ut</tag> + <description>Unittest</description> + </snippet> + <snippet> + <text><![CDATA[@${1:Given/When/Then}(r'${2:step definition with params (.*)}') +$< +import re +params_list = re.findall(r'["|\']?\(.*?\)["|\']?', ${2}) +params_number = len(params_list) +params = '' +for number in range(params_number): + params += 'var' + str(number+1) + if number+1 != params_number: + params += ' ,' + +step = ${2}.lower() +for param in params_list: + step = step.replace(param, '') +step = re.sub(r'\s+$', '', step) +step = re.sub(r'\s+', '_', step) + +result = 'def ' + step + '(' + params + '):' +return result +> + $0]]></text> + <tag>sd</tag> + <description>Step definition</description> + </snippet> +</snippets> +
SeanRoberts/easylistening
e0095d665849ba491bf44db1c7388ceb29fc4e04
Added itunes support
diff --git a/app/controllers/albums_controller.rb b/app/controllers/albums_controller.rb index 7057d52..e66e95f 100644 --- a/app/controllers/albums_controller.rb +++ b/app/controllers/albums_controller.rb @@ -1,13 +1,11 @@ -class AlbumsController < ApplicationController - require 'clamp' - +class AlbumsController < ApplicationController def index - @albums = Album.paginate(:all, :order => "title", :include => :tracks, :page => params[:page], :per_page => 50) + @albums = Album.paginate(:all, :order => "title", :include => :tracks, :page => params[:page], :per_page => 15) end def play @album = Album.find(params[:id], :include => "tracks", :order => "tracks.sort_track_number") - Clamp.new.play_album(@album.tracks) - redirect_to :action => :index + PLAYER.new.play_album(@album.tracks) + render :nothing => true end end diff --git a/app/controllers/application.rb b/app/controllers/application.rb index 81e82f2..301f339 100644 --- a/app/controllers/application.rb +++ b/app/controllers/application.rb @@ -1,15 +1,25 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time # See ActionController::RequestForgeryProtection for details # Uncomment the :secret if you're not using the cookie session store protect_from_forgery # :secret => '3ba2759d4cbdf57831fa493d4e5d764e' # See ActionController::Base for details # Uncomment this to filter the contents of submitted sensitive data parameters # from your application log (in this case, all fields with names like "password"). # filter_parameter_logging :password + + before_filter :get_info + + def get_info + @info, player = {}, PLAYER.new + @info[:current_track] = player.current_track + @info[:player_state] = player.player_state + @info[:player_position] = [player.player_position, player.track_duration] + @info[:player_position_percent] = (@info[:player_position][0] / @info[:player_position][1]) * 100 + end end diff --git a/app/controllers/player_controller.rb b/app/controllers/player_controller.rb new file mode 100644 index 0000000..942ae30 --- /dev/null +++ b/app/controllers/player_controller.rb @@ -0,0 +1,5 @@ +class PlayerController < ApplicationController + def now_playing + render :partial => "shared/now_playing" + end +end diff --git a/app/controllers/tracks_controller.rb b/app/controllers/tracks_controller.rb index e44af95..6fb40d8 100755 --- a/app/controllers/tracks_controller.rb +++ b/app/controllers/tracks_controller.rb @@ -1,15 +1,13 @@ -class TracksController < ApplicationController - require 'clamp' - +class TracksController < ApplicationController def index @tracks = Track.paginate(:include => [:artist, :album], :order => "albums.title, tracks.sort_track_number", :per_page => 200, :page => params[:page]) end def play @track = Track.find(params[:id]) - Clamp.new.play(@track.launch_path) - redirect_to :action => :index + PLAYER.new.play(@track.path) + render :nothing => true end end diff --git a/app/helpers/player_helper.rb b/app/helpers/player_helper.rb new file mode 100644 index 0000000..1547257 --- /dev/null +++ b/app/helpers/player_helper.rb @@ -0,0 +1,2 @@ +module PlayerHelper +end diff --git a/app/views/albums/index.html.haml b/app/views/albums/index.html.haml index c6c2417..75efcb4 100644 --- a/app/views/albums/index.html.haml +++ b/app/views/albums/index.html.haml @@ -1,14 +1,14 @@ = will_paginate @albums %table - @albums.each do |album| %tr{:class => cycle('normal', 'alternate')} - %td{:style => "width: 16px;"}= link_to image_tag("control_play.png"), "/albums/play/#{album.id}" + %td{:style => "width: 16px;"}= link_to image_tag("control_play.png"), "/albums/play/#{album.id}", :class => "play-link" %td %strong= album.title %br/ = album.tracks.first.artist.title if album.tracks.first && album.tracks.first.artist %br/ = album.tracks.length tracks \ No newline at end of file diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml index cc1dbf7..629578c 100644 --- a/app/views/layouts/application.html.haml +++ b/app/views/layouts/application.html.haml @@ -1,25 +1,28 @@ !!! Strict %html{ :lang => "en" } %head %meta{ :content => "text/html; charset=utf-8", "http-equiv" => "Content-Type" }/ %title EasyListening %meta{ :name => "generator", :content => "TextMate http://macromates.com/" }/ %meta{ :name => "author", :content => "Sean Roberts" }/ = stylesheet_link_tag 'style' + = javascript_include_tag 'jquery', 'application' / Date: 2008-12-09 %body #header-wrapper #header %h1 = image_tag('headphones.png', :style => "vertical-align: middle; width: 56px;") EasyListening %h3 Because walking to the living room is for suckers! #container #nav %ul %li= link_to "Artists", artists_path %li= link_to "Albums", albums_path %li= link_to "All Tracks", tracks_path + + #info= render :partial => "shared/now_playing" #body= yield \ No newline at end of file diff --git a/app/views/shared/_now_playing.html.haml b/app/views/shared/_now_playing.html.haml new file mode 100644 index 0000000..18b7786 --- /dev/null +++ b/app/views/shared/_now_playing.html.haml @@ -0,0 +1,11 @@ +%ul + %li + %strong= @info[:current_track].artist.title + %br/ + = @info[:current_track].title + + %li + .progress-holder + .progress{:style => "width: #{@info[:player_position_percent]}%"} + = @info[:player_position].map { |pos| pos.to_i.to_mm_ss }.join(' / ') + \ No newline at end of file diff --git a/app/views/tracks/index.html.haml b/app/views/tracks/index.html.haml index b8d6f09..8ad4112 100644 --- a/app/views/tracks/index.html.haml +++ b/app/views/tracks/index.html.haml @@ -1,18 +1,11 @@ = will_paginate @tracks %table - %tr - %th Title - %th Artist - %th Album - %th Track # - @tracks.each do |track| - %tr{:class => cycle('normal', 'alternate')} + %tr{:class => cycle(nil, 'alternate')} + %td{:style => "width: 16px;"}= link_to image_tag("control_play.png"), "/tracks/play/#{track.id}", :class => "play-link" %td - = track.title - = link_to "play", "/tracks/play/#{track.id}" - &nbsp; - = link_to "play album", "/albums/play/#{track.album.id}" if track.album - %td= track.artist.title if track.artist - %td= track.album.title if track.album - %td= track.track_number \ No newline at end of file + %strong= track.title + %br/ + = track.artist.title if track.artist + = "- " + track.album.title if track.album \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index 51095fe..ae6b9b3 100755 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,78 +1,80 @@ # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'UTC' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_easylistening_session', :secret => '913248f68579a7666dbb2d3c6e18481d821909f6e85d3a92b4520ff5dc65908c3967ff1dd4eb7f52f67363e83f6871fb880e1ab7866f035342e29624ed67c3cb' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end CONFIG = YAML.load(File.open("#{RAILS_ROOT}/config/easy.yml")) +require CONFIG['player'].downcase +PLAYER = CONFIG['player'].constantize require 'will_paginate' diff --git a/config/initializers/extensions.rb b/config/initializers/extensions.rb new file mode 100644 index 0000000..f40645a --- /dev/null +++ b/config/initializers/extensions.rb @@ -0,0 +1,7 @@ +class Fixnum + def to_mm_ss + minutes, seconds = self / 60, self % 60 + seconds = "0" + seconds.to_s if seconds < 10 + return "#{minutes}:#{seconds}" + end +end \ No newline at end of file diff --git a/lib/itunes.rb b/lib/itunes.rb index 82399e2..fd4cd48 100644 --- a/lib/itunes.rb +++ b/lib/itunes.rb @@ -1,60 +1,51 @@ class Itunes - attr_accessor :path_to_clamp - - def initialize(path) - @path_to_clamp = path - end - - def run(command, arguments = '') - arguments.gsub!(/&&|\||;/, '') - return false unless COMMANDS[command] - "#{path_to_clamp} #{command} #{arguments}" - end - - - COMMANDS = { - # General - "START" => "Start Winamp", - "QUIT" => "Exit Winamp", - "RESTART" =>" => ""Restart Winamp", - "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", - "STOP" => "Stop playing", - "STOPFADE" => "Stop playing with fadout", - "STOPAFTER" => "Stop playing after current track (returns now, stops later)", - "PAUSE" => "Toggle pause mode", - "PAUSE ON|OFF" => "Sets pause mode", - "PLAYPAUSE" => "Same as PAUSE", - "NEXT" => "Play next song", - "PREV" => "Play previous song", - "FWD" => "Forward 5 seconds", - "REW" => "Rewind 5 seconds", - "JUMP" => "Seek to <time> (in millisecs)", - "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", - - # Playlists - "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", - "LOAD" => "Same as above", - "PLCLEAR" => "Clear Playlist", - "CLEAR" => "Same as above", - "PL" => "Show/Hide Winamp Playlist window", - "PLWIN" => "Same as above", - "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", - "PLFIRST" => "Play first item of playlist", - "PLLAST" => "Play last item of playlist", - "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", - "PLSET RANDOM" => "Set current playlist item to a random item within playlist", - "SETPLPOS" => "Same as PLSET", - "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", - "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", - "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", - + require 'rbosa' + + def initialize + # open iTunes in the background if it's not already running + `open -g -a iTunes` - # Winamp Volume Control - "VOLUP" => "Volume up", - "VOLDN" => "Volume down", - "VOLSET" => "Volume set (scale 0-255)", - "VOL=<value>" => "Volume set (scale 0-100)", - "VOLMAX" => "Volume max", - "VOLMIN" => "Volume min (no sound)" - } + @itunes = OSA.app('iTunes') + create_playlist + end + + def create_playlist + @playlist = @itunes.sources[0].playlists.select { |p| p.name == "EasyListeningPL" }[0] || @itunes.make(OSA::ITunes::Playlist, nil, {:name => "EasyListeningPL"}) + end + + def clear_playlist + if @playlist.tracks.length > 0 + @itunes.delete @playlist + create_playlist + end + end + + def play(path) + clear_playlist + @itunes.add(path, :to => @playlist) + @itunes.stop + @itunes.play(@playlist) + end + + def play_album(tracks) + clear_playlist + tracks.each { |t| @itunes.add(t.path, :to => @playlist) } + @itunes.play(@playlist) + end + + def current_track + Track.find_by_path(@itunes.current_track.get.location) + end + + def player_state + @itunes.player_state + end + + def player_position + @itunes.player_position + end + + def track_duration + @itunes.current_track.duration + end end \ No newline at end of file diff --git a/lib/winamp.rb b/lib/winamp.rb new file mode 100755 index 0000000..fc0f7d8 --- /dev/null +++ b/lib/winamp.rb @@ -0,0 +1,77 @@ +class Winamp + @@path = CONFIG["path_to_clamp"] + + def initialize() + system(@@path + " /START") + sleep 1 + end + + + def run(command, arguments = '') + arguments.gsub!(/&&|\||;/, '') + puts "#{command} not recognized" and return false unless COMMANDS[command.upcase] + cmd = "#{@@path} /#{command}" + cmd += ' "' + arguments + '"' unless arguments.blank? + system(cmd) + end + + def play(path) + self.run('PLCLEAR') + self.run('PLADD', path) + self.run('PLFIRST') + self.run('PLAY') + end + + def play_album(tracks) + self.run('plclear') + tracks.each { |track| self.run('pladd', track.launch_path) } + self.run('plfirst') + self.run('play') + end + + COMMANDS = { + # General + "START" => "Start Winamp", + "QUIT" => "Exit Winamp", + "RESTART" =>" => ""Restart Winamp", + "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", + "STOP" => "Stop playing", + "STOPFADE" => "Stop playing with fadout", + "STOPAFTER" => "Stop playing after current track (returns now, stops later)", + "PAUSE" => "Toggle pause mode", + "PAUSE ON|OFF" => "Sets pause mode", + "PLAYPAUSE" => "Same as PAUSE", + "NEXT" => "Play next song", + "PREV" => "Play previous song", + "FWD" => "Forward 5 seconds", + "REW" => "Rewind 5 seconds", + "JUMP" => "Seek to <time> (in millisecs)", + "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", + + # Playlists + "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", + "LOAD" => "Same as above", + "PLCLEAR" => "Clear Playlist", + "CLEAR" => "Same as above", + "PL" => "Show/Hide Winamp Playlist window", + "PLWIN" => "Same as above", + "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", + "PLFIRST" => "Play first item of playlist", + "PLLAST" => "Play last item of playlist", + "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", + "PLSET RANDOM" => "Set current playlist item to a random item within playlist", + "SETPLPOS" => "Same as PLSET", + "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", + "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", + "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", + + + # Winamp Volume Control + "VOLUP" => "Volume up", + "VOLDN" => "Volume down", + "VOLSET" => "Volume set (scale 0-255)", + "VOL=<value>" => "Volume set (scale 0-100)", + "VOLMAX" => "Volume max", + "VOLMIN" => "Volume min (no sound)" + } +end diff --git a/public/javascripts/application.js b/public/javascripts/application.js index fe45776..cf38726 100644 --- a/public/javascripts/application.js +++ b/public/javascripts/application.js @@ -1,2 +1,16 @@ // Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults + +function updatePlayer() { + $.get('/player/now_playing', null, function(data) { + $('#info').html(data); + }); +} + +$(function() { + setInterval('updatePlayer();', 1000); + $('.play-link').click(function(e) { + e.preventDefault(); + $.get(this); + }); +}); \ No newline at end of file diff --git a/public/javascripts/jquery.js b/public/javascripts/jquery.js new file mode 100644 index 0000000..82b98e1 --- /dev/null +++ b/public/javascripts/jquery.js @@ -0,0 +1,32 @@ +/* + * jQuery 1.2.6 - New Wave Javascript + * + * Copyright (c) 2008 John Resig (jquery.com) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $ + * $Rev: 5685 $ + */ +(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else +return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else +return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else +selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else +return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else +this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else +return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else +jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&&copy&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else +script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else +for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else +for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else +jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else +ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&&notxml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&&notxml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&&notxml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else +while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else +while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else +for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else +jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else +xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else +jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else +for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else +s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else +e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})(); \ No newline at end of file diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 6ab4659..e8e838e 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,105 +1,125 @@ /* "#AD0606" "#8A7676" "#D1A29C" "#96B0C4" "#6C8699" */ body { font-family: Helvetica, Arial, Sans-Serif; margin: 0; font-size: 13px; color: #333; } a { color: #AD0606; } a img { vertical-align: middle; border: 0px; } /*--------------- layout --------------- */ #header-wrapper { width: 100%; background: #6C8699; color: white; padding: 20px 0px; margin-bottom: 20px; border-top: 5px solid #96B0C4; font-family: "Georgia", Times, Sans-Serif; } #header, #container { width: 960px; margin: 0px auto; } #nav { float: left; margin-right: 20px; width: 140px; } #body { width: 800px; float: left; } .pagination { margin-bottom: 10px; font-size: 11px; } /*------------ the info table ---------- */ table { width: 100%; border-collapse: collapse; font-size: 11px; + margin-bottom: 15px; } th, td { text-align: left; padding: 8px; border-top: 1px solid silver; } tr.alternate { background: #eee; } /*------------ text styles ----------- */ h1, h2 { color: #8A7676; } #header h1, #header h3 { color: white; } #header h1 { font-size: 32px; font-weight: normal; margin: 0; } #body h1 { margin: 0px 0px 10px; } +#info { + margin-top: 10px; + font-size: 11px; +} + +.progress { + height: 10px; + background: #D1A29C; +} + +.progress-holder { + width: 100%; + border: 1px solid black; + margin-bottom: 3px; +} + +.play-link { + outline: none; +} /*------------- navigation ----------- */ #nav a { text-decoration: none; } #nav ul { list-style-type: none; margin: 0px; padding: 0px; } #nav li { border-top: 1px solid silver; padding: 5px 10px; } \ No newline at end of file diff --git a/test/functional/player_controller_test.rb b/test/functional/player_controller_test.rb new file mode 100644 index 0000000..ae9e0cb --- /dev/null +++ b/test/functional/player_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class PlayerControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end
SeanRoberts/easylistening
37757dc99c7b3d82ac81e726fa434b3ee18dac31
System commands are better
diff --git a/app/views/albums/index.html.haml b/app/views/albums/index.html.haml index 371af40..c6c2417 100644 --- a/app/views/albums/index.html.haml +++ b/app/views/albums/index.html.haml @@ -1,14 +1,14 @@ = will_paginate @albums %table - %tr{:class => cycle(nil, 'alternate')} - %th Title - %th Artist - %th Tracks - @albums.each do |album| %tr{:class => cycle('normal', 'alternate')} + %td{:style => "width: 16px;"}= link_to image_tag("control_play.png"), "/albums/play/#{album.id}" + %td - = link_to image_tag("control_play.png"), "/albums/play/#{album.id}" - = album.title - %td= album.tracks.first.artist.title if album.tracks.first && album.tracks.first.artist - %td= album.tracks.length \ No newline at end of file + %strong= album.title + %br/ + = album.tracks.first.artist.title if album.tracks.first && album.tracks.first.artist + %br/ + = album.tracks.length + tracks \ No newline at end of file diff --git a/lib/clamp.rb b/lib/clamp.rb index fe186a3..c516c61 100755 --- a/lib/clamp.rb +++ b/lib/clamp.rb @@ -1,77 +1,77 @@ class Clamp @@path = CONFIG["path_to_clamp"] def initialize() system(@@path + " /START") sleep 1 end def run(command, arguments = '') arguments.gsub!(/&&|\||;/, '') puts "#{command} not recognized" and return false unless COMMANDS[command.upcase] cmd = "#{@@path} /#{command}" cmd += ' "' + arguments + '"' unless arguments.blank? - puts `#{cmd}` + system(cmd) end def play(path) self.run('PLCLEAR') self.run('PLADD', path) self.run('PLFIRST') self.run('PLAY') end def play_album(tracks) self.run('plclear') tracks.each { |track| self.run('pladd', track.launch_path) } self.run('plfirst') self.run('play') end COMMANDS = { # General "START" => "Start Winamp", "QUIT" => "Exit Winamp", "RESTART" =>" => ""Restart Winamp", "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", "STOP" => "Stop playing", "STOPFADE" => "Stop playing with fadout", "STOPAFTER" => "Stop playing after current track (returns now, stops later)", "PAUSE" => "Toggle pause mode", "PAUSE ON|OFF" => "Sets pause mode", "PLAYPAUSE" => "Same as PAUSE", "NEXT" => "Play next song", "PREV" => "Play previous song", "FWD" => "Forward 5 seconds", "REW" => "Rewind 5 seconds", "JUMP" => "Seek to <time> (in millisecs)", "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", # Playlists "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", "LOAD" => "Same as above", "PLCLEAR" => "Clear Playlist", "CLEAR" => "Same as above", "PL" => "Show/Hide Winamp Playlist window", "PLWIN" => "Same as above", "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", "PLFIRST" => "Play first item of playlist", "PLLAST" => "Play last item of playlist", "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", "PLSET RANDOM" => "Set current playlist item to a random item within playlist", "SETPLPOS" => "Same as PLSET", "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", # Winamp Volume Control "VOLUP" => "Volume up", "VOLDN" => "Volume down", "VOLSET" => "Volume set (scale 0-255)", "VOL=<value>" => "Volume set (scale 0-100)", "VOLMAX" => "Volume max", "VOLMIN" => "Volume min (no sound)" } end
SeanRoberts/easylistening
a746352fb34be0e77aaf02fdc71f7d34ad558d02
Configured for cygwin
diff --git a/app/controllers/tracks_controller.rb b/app/controllers/tracks_controller.rb old mode 100644 new mode 100755 index 85567c0..e44af95 --- a/app/controllers/tracks_controller.rb +++ b/app/controllers/tracks_controller.rb @@ -1,15 +1,15 @@ class TracksController < ApplicationController require 'clamp' def index @tracks = Track.paginate(:include => [:artist, :album], :order => "albums.title, tracks.sort_track_number", :per_page => 200, :page => params[:page]) end def play @track = Track.find(params[:id]) - Clamp.new.play(@track.path) + Clamp.new.play(@track.launch_path) redirect_to :action => :index end end diff --git a/app/models/track.rb b/app/models/track.rb old mode 100644 new mode 100755 index 00f5c15..4a43b9b --- a/app/models/track.rb +++ b/app/models/track.rb @@ -1,23 +1,27 @@ class Track < ActiveRecord::Base belongs_to :artist belongs_to :album def set_attributes_from_tag(tag) # Artist and Album self.artist = Artist.find_by_title(tag.artist.gsub(/\000/, '')) || Artist.create(:title => tag.artist.gsub(/\000/, '')) unless tag.artist.blank? self.album = Album.find_by_title(tag.album.gsub(/\000/, '')) || Album.create(:title => tag.album.gsub(/\000/, '')) unless tag.album.blank? # Title self.title = tag.title ? tag.title.gsub(/\000/, '') : File.basename(path) # Track and Sorting Track Tracks are strings sometimes formatted as "5/14", # sort_track is an integer field so that would just be saved as 5 self.sort_track_number = self.track_number = tag.track.gsub(/\000/, '') unless tag.track.blank? # Track Length, Track Year song_duration = tag.select { |hash| hash[:id] == :TLEN } self.duration = song_duration[0][:text].gsub(/\000/, '') unless song_duration.blank? || song_duration[0][:text].blank? self.year = tag.year.gsub(/\000/, '') unless tag.year.blank? end + + def launch_path + path.gsub('/cygdrive/d', 'D:').gsub('/', '\\') + end end diff --git a/config/environment.rb b/config/environment.rb old mode 100644 new mode 100755 index f2d075f..51095fe --- a/config/environment.rb +++ b/config/environment.rb @@ -1,77 +1,78 @@ # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'UTC' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_easylistening_session', :secret => '913248f68579a7666dbb2d3c6e18481d821909f6e85d3a92b4520ff5dc65908c3967ff1dd4eb7f52f67363e83f6871fb880e1ab7866f035342e29624ed67c3cb' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end +CONFIG = YAML.load(File.open("#{RAILS_ROOT}/config/easy.yml")) require 'will_paginate' diff --git a/lib/clamp.rb b/lib/clamp.rb old mode 100644 new mode 100755 index d8ff0e9..fe186a3 --- a/lib/clamp.rb +++ b/lib/clamp.rb @@ -1,78 +1,77 @@ class Clamp - @@path = "F:/Program\ Files/clamp.exe" + @@path = CONFIG["path_to_clamp"] def initialize() - system(@@path + "/START") + system(@@path + " /START") sleep 1 end def run(command, arguments = '') arguments.gsub!(/&&|\||;/, '') puts "#{command} not recognized" and return false unless COMMANDS[command.upcase] cmd = "#{@@path} /#{command}" cmd += ' "' + arguments + '"' unless arguments.blank? - puts "Running #{cmd}..." - system(cmd) + puts `#{cmd}` end def play(path) self.run('PLCLEAR') - self.run('PLADD', path.gsub('/', '\\')) + self.run('PLADD', path) self.run('PLFIRST') self.run('PLAY') end def play_album(tracks) self.run('plclear') - tracks.each { |track| self.run('pladd', track.path.gsub('/', '\\')) } + tracks.each { |track| self.run('pladd', track.launch_path) } self.run('plfirst') self.run('play') end COMMANDS = { # General "START" => "Start Winamp", "QUIT" => "Exit Winamp", "RESTART" =>" => ""Restart Winamp", "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", "STOP" => "Stop playing", "STOPFADE" => "Stop playing with fadout", "STOPAFTER" => "Stop playing after current track (returns now, stops later)", "PAUSE" => "Toggle pause mode", "PAUSE ON|OFF" => "Sets pause mode", "PLAYPAUSE" => "Same as PAUSE", "NEXT" => "Play next song", "PREV" => "Play previous song", "FWD" => "Forward 5 seconds", "REW" => "Rewind 5 seconds", "JUMP" => "Seek to <time> (in millisecs)", "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", # Playlists "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", "LOAD" => "Same as above", "PLCLEAR" => "Clear Playlist", "CLEAR" => "Same as above", "PL" => "Show/Hide Winamp Playlist window", "PLWIN" => "Same as above", "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", "PLFIRST" => "Play first item of playlist", "PLLAST" => "Play last item of playlist", "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", "PLSET RANDOM" => "Set current playlist item to a random item within playlist", "SETPLPOS" => "Same as PLSET", "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", # Winamp Volume Control "VOLUP" => "Volume up", "VOLDN" => "Volume down", "VOLSET" => "Volume set (scale 0-255)", "VOL=<value>" => "Volume set (scale 0-100)", "VOLMAX" => "Volume max", "VOLMIN" => "Volume min (no sound)" } end diff --git a/lib/tasks/easylistening.rake b/lib/tasks/easylistening.rake old mode 100644 new mode 100755 index 26e5fa9..906fecb --- a/lib/tasks/easylistening.rake +++ b/lib/tasks/easylistening.rake @@ -1,49 +1,49 @@ namespace "easy" do desc "Update Media Library" task(:update_library => :environment) do require 'yaml' require 'find' require 'id3lib' - config = YAML.load(File.open("#{RAILS_ROOT}/config/easy.yml")) - @base_dir = config['music_dir'] + @base_dir = CONFIG['music_dir'] @extnames = [".mp3", ".ogg", ".wav", ".wma"] + puts "Searching #{@base_dir} for music..." Find.find(@base_dir) do |path| if @extnames.include?(File.extname(path)) print "Processing #{path}... " track = Track.find_by_path(path) if track.blank? || (track && track.updated_at < File.mtime(path)) track ||= Track.new(:path => path) tag = ID3Lib::Tag.new(path) track.set_attributes_from_tag(tag) track.save puts "Updated!" else puts "No update required!" end end end end desc "Remove Dead Tracks" task(:remove_dead_tracks => :environment) do Track.all.each do |track| unless File.exist?(track.path) puts "#{track.path} not found. Deleting from library." track.destroy end end [Album, Artist].each do |klass| klass.all.each { |obj| obj.destroy if obj.tracks.length < 1 } end end desc "Wipe The Entire Library" task(:wipe_library => :environment) do Artist.destroy_all Track.destroy_all Album.destroy_all end -end \ No newline at end of file +end
SeanRoberts/easylistening
8fe038c662f6589582669d364a2ebdbc5da5c4a8
Some visual changes, some pagination changes
diff --git a/app/controllers/albums_controller.rb b/app/controllers/albums_controller.rb index f2eca42..7057d52 100644 --- a/app/controllers/albums_controller.rb +++ b/app/controllers/albums_controller.rb @@ -1,13 +1,13 @@ class AlbumsController < ApplicationController require 'clamp' def index - @albums = Album.paginate(:all, :order => "title", :include => :tracks, :page => params[:page], :per_page => 100) + @albums = Album.paginate(:all, :order => "title", :include => :tracks, :page => params[:page], :per_page => 50) end def play @album = Album.find(params[:id], :include => "tracks", :order => "tracks.sort_track_number") Clamp.new.play_album(@album.tracks) redirect_to :action => :index end end diff --git a/app/views/albums/index.html.haml b/app/views/albums/index.html.haml index c556f74..371af40 100644 --- a/app/views/albums/index.html.haml +++ b/app/views/albums/index.html.haml @@ -1,14 +1,14 @@ = will_paginate @albums %table - %tr + %tr{:class => cycle(nil, 'alternate')} %th Title %th Artist %th Tracks - @albums.each do |album| %tr{:class => cycle('normal', 'alternate')} %td + = link_to image_tag("control_play.png"), "/albums/play/#{album.id}" = album.title - = link_to "play", "/albums/play/#{album.id}" %td= album.tracks.first.artist.title if album.tracks.first && album.tracks.first.artist %td= album.tracks.length \ No newline at end of file diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml index 2a9609c..cc1dbf7 100644 --- a/app/views/layouts/application.html.haml +++ b/app/views/layouts/application.html.haml @@ -1,20 +1,25 @@ !!! Strict %html{ :lang => "en" } %head %meta{ :content => "text/html; charset=utf-8", "http-equiv" => "Content-Type" }/ - %title Easy Listening + %title EasyListening %meta{ :name => "generator", :content => "TextMate http://macromates.com/" }/ %meta{ :name => "author", :content => "Sean Roberts" }/ = stylesheet_link_tag 'style' / Date: 2008-12-09 %body - #header - %h1 EasyListening - %h3 Because walking to the living room is for suckers! - - #nav - = link_to "Artists", artists_path - = link_to "Albums", albums_path - = link_to "All Tracks", tracks_path + #header-wrapper + #header + %h1 + = image_tag('headphones.png', :style => "vertical-align: middle; width: 56px;") + EasyListening + %h3 Because walking to the living room is for suckers! - #body= yield \ No newline at end of file + #container + #nav + %ul + %li= link_to "Artists", artists_path + %li= link_to "Albums", albums_path + %li= link_to "All Tracks", tracks_path + + #body= yield \ No newline at end of file diff --git a/public/images/control_play.png b/public/images/control_play.png new file mode 100755 index 0000000..0846555 Binary files /dev/null and b/public/images/control_play.png differ diff --git a/public/images/headphones.png b/public/images/headphones.png new file mode 100644 index 0000000..6041d27 Binary files /dev/null and b/public/images/headphones.png differ diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 30eca1d..6ab4659 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,60 +1,105 @@ /* "#AD0606" "#8A7676" "#D1A29C" -"#D1A29C" +"#96B0C4" "#6C8699" */ body { font-family: Helvetica, Arial, Sans-Serif; margin: 0; font-size: 13px; + color: #333; +} + +a { + color: #AD0606; +} + +a img { + vertical-align: middle; + border: 0px; +} + +/*--------------- layout --------------- */ +#header-wrapper { + width: 100%; + background: #6C8699; + color: white; + padding: 20px 0px; + margin-bottom: 20px; + border-top: 5px solid #96B0C4; + font-family: "Georgia", Times, Sans-Serif; +} + +#header, #container { + width: 960px; + margin: 0px auto; +} + +#nav { + float: left; + margin-right: 20px; + width: 140px; +} + +#body { + width: 800px; + float: left; } +.pagination { + margin-bottom: 10px; + font-size: 11px; +} + +/*------------ the info table ---------- */ table { width: 100%; border-collapse: collapse; font-size: 11px; } th, td { text-align: left; - padding: 5px; - border: 1px solid silver; + padding: 8px; + border-top: 1px solid silver; } -#header { - width: 100%; - background: #333; - color: white; - padding: 20px 0px; - margin-bottom: 20px; - border-top: 5px solid black; +tr.alternate { + background: #eee; +} + + +/*------------ text styles ----------- */ +h1, h2 { + color: #8A7676; } #header h1, #header h3 { - padding: 0px 20px; + color: white; } #header h1 { font-size: 32px; font-weight: normal; margin: 0; } - -#nav { - float: left; - margin: 0px 20px; +#body h1 { + margin: 0px 0px 10px; } +/*------------- navigation ----------- */ #nav a { - display: block; - margin: 0px 0px 5px; + text-decoration: none; } -#body { - float: left; +#nav ul { + list-style-type: none; + margin: 0px; + padding: 0px; } -#body h1 { - margin: 0px 0px 10px; +#nav li { + border-top: 1px solid silver; + padding: 5px 10px; } \ No newline at end of file
SeanRoberts/easylistening
a84c1c21981818237b65af373517a13253e445e1
Using a config file for directories
diff --git a/.gitignore b/.gitignore index cd567d6..720273f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,14 @@ log/*.log tmp/**/* .DS_Store doc/api doc/app coverage .loadpath .project db/*.sqlite3 db/development.sqlite3 config/database.yml config/database_old.yml gunk -public/photos -public/headshots +config/easy.yml diff --git a/lib/tasks/easylistening.rake b/lib/tasks/easylistening.rake index 1c7a6a5..26e5fa9 100644 --- a/lib/tasks/easylistening.rake +++ b/lib/tasks/easylistening.rake @@ -1,46 +1,49 @@ namespace "easy" do desc "Update Media Library" task(:update_library => :environment) do + require 'yaml' require 'find' require 'id3lib' - @base_dir = "/Users/seanroberts/Music" + + config = YAML.load(File.open("#{RAILS_ROOT}/config/easy.yml")) + @base_dir = config['music_dir'] @extnames = [".mp3", ".ogg", ".wav", ".wma"] Find.find(@base_dir) do |path| if @extnames.include?(File.extname(path)) print "Processing #{path}... " track = Track.find_by_path(path) if track.blank? || (track && track.updated_at < File.mtime(path)) track ||= Track.new(:path => path) tag = ID3Lib::Tag.new(path) track.set_attributes_from_tag(tag) track.save puts "Updated!" else puts "No update required!" end end end end desc "Remove Dead Tracks" task(:remove_dead_tracks => :environment) do Track.all.each do |track| unless File.exist?(track.path) puts "#{track.path} not found. Deleting from library." track.destroy end end [Album, Artist].each do |klass| klass.all.each { |obj| obj.destroy if obj.tracks.length < 1 } end end desc "Wipe The Entire Library" task(:wipe_library => :environment) do Artist.destroy_all Track.destroy_all Album.destroy_all end end \ No newline at end of file diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 7588aad..30eca1d 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,53 +1,60 @@ +/* +"#AD0606" +"#8A7676" +"#D1A29C" +"#D1A29C" +"#6C8699" +*/ body { font-family: Helvetica, Arial, Sans-Serif; margin: 0; font-size: 13px; } table { width: 100%; border-collapse: collapse; font-size: 11px; } th, td { text-align: left; padding: 5px; border: 1px solid silver; } #header { width: 100%; background: #333; color: white; padding: 20px 0px; margin-bottom: 20px; border-top: 5px solid black; } #header h1, #header h3 { padding: 0px 20px; } #header h1 { font-size: 32px; font-weight: normal; margin: 0; } #nav { float: left; margin: 0px 20px; } #nav a { display: block; margin: 0px 0px 5px; } #body { float: left; } #body h1 { margin: 0px 0px 10px; } \ No newline at end of file
SeanRoberts/easylistening
456a46912e8585a8908c7498134ceec0e8e96210
Rejigged clamp class slightly to sleep for 1 second before sending commands (to ensure winamp is open). Also paginated albums, fixed rake tasks for updating and removing dead tracks from the library.
diff --git a/app/controllers/albums_controller.rb b/app/controllers/albums_controller.rb index 55213bb..f2eca42 100644 --- a/app/controllers/albums_controller.rb +++ b/app/controllers/albums_controller.rb @@ -1,11 +1,13 @@ class AlbumsController < ApplicationController + require 'clamp' + def index - @albums = Album.find(:all, :order => "title", :include => :tracks) + @albums = Album.paginate(:all, :order => "title", :include => :tracks, :page => params[:page], :per_page => 100) end def play @album = Album.find(params[:id], :include => "tracks", :order => "tracks.sort_track_number") - Clamp.play_album(@album.tracks) + Clamp.new.play_album(@album.tracks) redirect_to :action => :index end end diff --git a/app/controllers/tracks_controller.rb b/app/controllers/tracks_controller.rb index e55bd85..85567c0 100644 --- a/app/controllers/tracks_controller.rb +++ b/app/controllers/tracks_controller.rb @@ -1,15 +1,15 @@ class TracksController < ApplicationController require 'clamp' def index @tracks = Track.paginate(:include => [:artist, :album], :order => "albums.title, tracks.sort_track_number", :per_page => 200, :page => params[:page]) end def play @track = Track.find(params[:id]) - Clamp.play(@track.path) + Clamp.new.play(@track.path) redirect_to :action => :index end end diff --git a/app/models/track.rb b/app/models/track.rb index d3edb2f..00f5c15 100644 --- a/app/models/track.rb +++ b/app/models/track.rb @@ -1,23 +1,23 @@ class Track < ActiveRecord::Base belongs_to :artist belongs_to :album - def get_info_from_tag!(tag) + def set_attributes_from_tag(tag) # Artist and Album self.artist = Artist.find_by_title(tag.artist.gsub(/\000/, '')) || Artist.create(:title => tag.artist.gsub(/\000/, '')) unless tag.artist.blank? self.album = Album.find_by_title(tag.album.gsub(/\000/, '')) || Album.create(:title => tag.album.gsub(/\000/, '')) unless tag.album.blank? # Title self.title = tag.title ? tag.title.gsub(/\000/, '') : File.basename(path) # Track and Sorting Track Tracks are strings sometimes formatted as "5/14", # sort_track is an integer field so that would just be saved as 5 self.sort_track_number = self.track_number = tag.track.gsub(/\000/, '') unless tag.track.blank? # Track Length, Track Year song_duration = tag.select { |hash| hash[:id] == :TLEN } self.duration = song_duration[0][:text].gsub(/\000/, '') unless song_duration.blank? || song_duration[0][:text].blank? self.year = tag.year.gsub(/\000/, '') unless tag.year.blank? end end diff --git a/app/views/albums/index.html.haml b/app/views/albums/index.html.haml index 41699c9..c556f74 100644 --- a/app/views/albums/index.html.haml +++ b/app/views/albums/index.html.haml @@ -1,12 +1,14 @@ += will_paginate @albums + %table %tr %th Title %th Artist %th Tracks - @albums.each do |album| %tr{:class => cycle('normal', 'alternate')} %td = album.title = link_to "play", "/albums/play/#{album.id}" %td= album.tracks.first.artist.title if album.tracks.first && album.tracks.first.artist %td= album.tracks.length \ No newline at end of file diff --git a/lib/clamp.rb b/lib/clamp.rb index d183f79..d8ff0e9 100644 --- a/lib/clamp.rb +++ b/lib/clamp.rb @@ -1,79 +1,78 @@ class Clamp - - def initialize(path) - @path_to_clamp = path + @@path = "F:/Program\ Files/clamp.exe" + + def initialize() + system(@@path + "/START") + sleep 1 end - def self.path - "F:/Program\ Files/clamp.exe" - end - def self.run(command, arguments = '') + def run(command, arguments = '') arguments.gsub!(/&&|\||;/, '') puts "#{command} not recognized" and return false unless COMMANDS[command.upcase] - cmd = "#{self.path} /#{command}" + cmd = "#{@@path} /#{command}" cmd += ' "' + arguments + '"' unless arguments.blank? puts "Running #{cmd}..." system(cmd) end - def self.play(path) + def play(path) self.run('PLCLEAR') self.run('PLADD', path.gsub('/', '\\')) self.run('PLFIRST') self.run('PLAY') end - def self.play_album(tracks) + def play_album(tracks) self.run('plclear') tracks.each { |track| self.run('pladd', track.path.gsub('/', '\\')) } self.run('plfirst') self.run('play') end COMMANDS = { # General "START" => "Start Winamp", "QUIT" => "Exit Winamp", "RESTART" =>" => ""Restart Winamp", "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", "STOP" => "Stop playing", "STOPFADE" => "Stop playing with fadout", "STOPAFTER" => "Stop playing after current track (returns now, stops later)", "PAUSE" => "Toggle pause mode", "PAUSE ON|OFF" => "Sets pause mode", "PLAYPAUSE" => "Same as PAUSE", "NEXT" => "Play next song", "PREV" => "Play previous song", "FWD" => "Forward 5 seconds", "REW" => "Rewind 5 seconds", "JUMP" => "Seek to <time> (in millisecs)", "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", # Playlists "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", "LOAD" => "Same as above", "PLCLEAR" => "Clear Playlist", "CLEAR" => "Same as above", "PL" => "Show/Hide Winamp Playlist window", "PLWIN" => "Same as above", "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", "PLFIRST" => "Play first item of playlist", "PLLAST" => "Play last item of playlist", "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", "PLSET RANDOM" => "Set current playlist item to a random item within playlist", "SETPLPOS" => "Same as PLSET", "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", # Winamp Volume Control "VOLUP" => "Volume up", "VOLDN" => "Volume down", "VOLSET" => "Volume set (scale 0-255)", "VOL=<value>" => "Volume set (scale 0-100)", "VOLMAX" => "Volume max", "VOLMIN" => "Volume min (no sound)" } end diff --git a/lib/tasks/easylistening.rake b/lib/tasks/easylistening.rake index 678a6fb..1c7a6a5 100644 --- a/lib/tasks/easylistening.rake +++ b/lib/tasks/easylistening.rake @@ -1,26 +1,46 @@ namespace "easy" do desc "Update Media Library" task(:update_library => :environment) do require 'find' require 'id3lib' @base_dir = "/Users/seanroberts/Music" @extnames = [".mp3", ".ogg", ".wav", ".wma"] Find.find(@base_dir) do |path| if @extnames.include?(File.extname(path)) - unless Track.find_by_path(path) - puts "Processing #{path}..." - track, tag = Track.new(:path => path), ID3Lib::Tag.new(path) - track.get_info_from_tag!(tag) + print "Processing #{path}... " + track = Track.find_by_path(path) + if track.blank? || (track && track.updated_at < File.mtime(path)) + track ||= Track.new(:path => path) + tag = ID3Lib::Tag.new(path) + track.set_attributes_from_tag(tag) track.save + puts "Updated!" + else + puts "No update required!" end end end end + desc "Remove Dead Tracks" + task(:remove_dead_tracks => :environment) do + Track.all.each do |track| + unless File.exist?(track.path) + puts "#{track.path} not found. Deleting from library." + track.destroy + end + end + + [Album, Artist].each do |klass| + klass.all.each { |obj| obj.destroy if obj.tracks.length < 1 } + end + + end + desc "Wipe The Entire Library" task(:wipe_library => :environment) do Artist.destroy_all Track.destroy_all Album.destroy_all end end \ No newline at end of file
SeanRoberts/easylistening
99007ecc36fefc5871059e44b169899195815083
Clamp from PC
diff --git a/lib/clamp.rb b/lib/clamp.rb index 0e43fe6..d183f79 100644 --- a/lib/clamp.rb +++ b/lib/clamp.rb @@ -1,76 +1,79 @@ class Clamp - + def initialize(path) @path_to_clamp = path end - + def self.path - "F:\\Program Files\\clamp.exe" + "F:/Program\ Files/clamp.exe" end - + def self.run(command, arguments = '') arguments.gsub!(/&&|\||;/, '') - return false unless COMMANDS[command.upcase] - "#{self.path} /#{command} \"#{arguments}\"" + puts "#{command} not recognized" and return false unless COMMANDS[command.upcase] + cmd = "#{self.path} /#{command}" + cmd += ' "' + arguments + '"' unless arguments.blank? + puts "Running #{cmd}..." + system(cmd) end - + def self.play(path) - self.run('plclear') - self.run('pladd', path) - self.run('plfirst') - self.run('play') + self.run('PLCLEAR') + self.run('PLADD', path.gsub('/', '\\')) + self.run('PLFIRST') + self.run('PLAY') end - + def self.play_album(tracks) self.run('plclear') - tracks.each { |track| self.run('pladd', track.path) } + tracks.each { |track| self.run('pladd', track.path.gsub('/', '\\')) } self.run('plfirst') self.run('play') end - + COMMANDS = { # General "START" => "Start Winamp", "QUIT" => "Exit Winamp", "RESTART" =>" => ""Restart Winamp", "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", "STOP" => "Stop playing", "STOPFADE" => "Stop playing with fadout", "STOPAFTER" => "Stop playing after current track (returns now, stops later)", "PAUSE" => "Toggle pause mode", "PAUSE ON|OFF" => "Sets pause mode", "PLAYPAUSE" => "Same as PAUSE", "NEXT" => "Play next song", "PREV" => "Play previous song", "FWD" => "Forward 5 seconds", "REW" => "Rewind 5 seconds", "JUMP" => "Seek to <time> (in millisecs)", "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", - + # Playlists "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", "LOAD" => "Same as above", "PLCLEAR" => "Clear Playlist", "CLEAR" => "Same as above", "PL" => "Show/Hide Winamp Playlist window", "PLWIN" => "Same as above", "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", "PLFIRST" => "Play first item of playlist", "PLLAST" => "Play last item of playlist", "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", "PLSET RANDOM" => "Set current playlist item to a random item within playlist", "SETPLPOS" => "Same as PLSET", "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", - - + + # Winamp Volume Control - "VOLUP" => "Volume up", - "VOLDN" => "Volume down", - "VOLSET" => "Volume set (scale 0-255)", - "VOL=<value>" => "Volume set (scale 0-100)", - "VOLMAX" => "Volume max", - "VOLMIN" => "Volume min (no sound)" + "VOLUP" => "Volume up", + "VOLDN" => "Volume down", + "VOLSET" => "Volume set (scale 0-255)", + "VOL=<value>" => "Volume set (scale 0-100)", + "VOLMAX" => "Volume max", + "VOLMIN" => "Volume min (no sound)" } -end \ No newline at end of file +end
SeanRoberts/easylistening
a3a6c1588d8dc67b3c4a7aa9bcab6f2840d48f07
Some basic layouts, plus pagination for tracks
diff --git a/app/controllers/albums_controller.rb b/app/controllers/albums_controller.rb index 2f800bd..55213bb 100644 --- a/app/controllers/albums_controller.rb +++ b/app/controllers/albums_controller.rb @@ -1,2 +1,11 @@ class AlbumsController < ApplicationController + def index + @albums = Album.find(:all, :order => "title", :include => :tracks) + end + + def play + @album = Album.find(params[:id], :include => "tracks", :order => "tracks.sort_track_number") + Clamp.play_album(@album.tracks) + redirect_to :action => :index + end end diff --git a/app/controllers/index_controller.rb b/app/controllers/index_controller.rb index 6a6675b..4af204c 100644 --- a/app/controllers/index_controller.rb +++ b/app/controllers/index_controller.rb @@ -1,19 +1,5 @@ class IndexController < ApplicationController - require 'clamp' - def index - @tracks = Track.paginate(:include => [:artist, :album], :order => "albums.title, tracks.sort_track_number", :per_page => 200, :page => params[:page]) + @count = {:albums => Album.count, :artists => Artist.count, :tracks => Track.count} end - - def play - @track = Track.find(params[:id]) - Clamp.play(@track.path) - redirect_to :action => :index - end - - def play_album - @album = Album.find(params[:id], :include => "tracks", :order => "tracks.sort_track_number") - Clamp.play_album(@album.tracks) - redirect_to :action => :index - end -end +end \ No newline at end of file diff --git a/app/controllers/tracks_controller.rb b/app/controllers/tracks_controller.rb index 3666eb6..e55bd85 100644 --- a/app/controllers/tracks_controller.rb +++ b/app/controllers/tracks_controller.rb @@ -1,2 +1,15 @@ class TracksController < ApplicationController + require 'clamp' + + def index + @tracks = Track.paginate(:include => [:artist, :album], :order => "albums.title, tracks.sort_track_number", :per_page => 200, :page => params[:page]) + end + + def play + @track = Track.find(params[:id]) + Clamp.play(@track.path) + redirect_to :action => :index + end + + end diff --git a/app/views/albums/index.html.haml b/app/views/albums/index.html.haml new file mode 100644 index 0000000..41699c9 --- /dev/null +++ b/app/views/albums/index.html.haml @@ -0,0 +1,12 @@ +%table + %tr + %th Title + %th Artist + %th Tracks + - @albums.each do |album| + %tr{:class => cycle('normal', 'alternate')} + %td + = album.title + = link_to "play", "/albums/play/#{album.id}" + %td= album.tracks.first.artist.title if album.tracks.first && album.tracks.first.artist + %td= album.tracks.length \ No newline at end of file diff --git a/app/views/index/index.html.haml b/app/views/index/index.html.haml index 9d04cbb..f34de55 100644 --- a/app/views/index/index.html.haml +++ b/app/views/index/index.html.haml @@ -1,16 +1,10 @@ -%table - %tr - %th Title - %th Artist - %th Album - %th Track # - - @tracks.each do |track| - %tr{:class => cycle('normal', 'alternate')} - %td - = track.title - = link_to "play", "/index/play/#{track.id}" - &nbsp; - = link_to "play album", "/index/play_album/#{track.album.id}" if track.album - %td= track.artist.title if track.artist - %td= track.album.title if track.album - %td= track.track_number \ No newline at end of file +%h1 Welcome to EasyListening! + +%p + This installation of EasyListening has an index of + %strong= @count[:artists] + artists, + %strong= @count[:albums] + albums, and + %strong= @count[:tracks] + tracks. \ No newline at end of file diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml index dd38cbd..2a9609c 100644 --- a/app/views/layouts/application.html.haml +++ b/app/views/layouts/application.html.haml @@ -1,11 +1,20 @@ !!! Strict %html{ :lang => "en" } %head %meta{ :content => "text/html; charset=utf-8", "http-equiv" => "Content-Type" }/ %title Easy Listening %meta{ :name => "generator", :content => "TextMate http://macromates.com/" }/ %meta{ :name => "author", :content => "Sean Roberts" }/ = stylesheet_link_tag 'style' / Date: 2008-12-09 %body - = yield \ No newline at end of file + #header + %h1 EasyListening + %h3 Because walking to the living room is for suckers! + + #nav + = link_to "Artists", artists_path + = link_to "Albums", albums_path + = link_to "All Tracks", tracks_path + + #body= yield \ No newline at end of file diff --git a/app/views/tracks/index.html.haml b/app/views/tracks/index.html.haml new file mode 100644 index 0000000..b8d6f09 --- /dev/null +++ b/app/views/tracks/index.html.haml @@ -0,0 +1,18 @@ += will_paginate @tracks + +%table + %tr + %th Title + %th Artist + %th Album + %th Track # + - @tracks.each do |track| + %tr{:class => cycle('normal', 'alternate')} + %td + = track.title + = link_to "play", "/tracks/play/#{track.id}" + &nbsp; + = link_to "play album", "/albums/play/#{track.album.id}" if track.album + %td= track.artist.title if track.artist + %td= track.album.title if track.album + %td= track.track_number \ No newline at end of file diff --git a/lib/clamp.rb b/lib/clamp.rb index 95888ff..0e43fe6 100644 --- a/lib/clamp.rb +++ b/lib/clamp.rb @@ -1,76 +1,76 @@ class Clamp def initialize(path) @path_to_clamp = path end def self.path "F:\\Program Files\\clamp.exe" end def self.run(command, arguments = '') arguments.gsub!(/&&|\||;/, '') - return false unless COMMANDS[command] + return false unless COMMANDS[command.upcase] "#{self.path} /#{command} \"#{arguments}\"" end def self.play(path) self.run('plclear') self.run('pladd', path) self.run('plfirst') self.run('play') end def self.play_album(tracks) self.run('plclear') tracks.each { |track| self.run('pladd', track.path) } self.run('plfirst') self.run('play') end COMMANDS = { # General "START" => "Start Winamp", "QUIT" => "Exit Winamp", "RESTART" =>" => ""Restart Winamp", "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", "STOP" => "Stop playing", "STOPFADE" => "Stop playing with fadout", "STOPAFTER" => "Stop playing after current track (returns now, stops later)", "PAUSE" => "Toggle pause mode", "PAUSE ON|OFF" => "Sets pause mode", "PLAYPAUSE" => "Same as PAUSE", "NEXT" => "Play next song", "PREV" => "Play previous song", "FWD" => "Forward 5 seconds", "REW" => "Rewind 5 seconds", "JUMP" => "Seek to <time> (in millisecs)", "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", # Playlists "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", "LOAD" => "Same as above", "PLCLEAR" => "Clear Playlist", "CLEAR" => "Same as above", "PL" => "Show/Hide Winamp Playlist window", "PLWIN" => "Same as above", "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", "PLFIRST" => "Play first item of playlist", "PLLAST" => "Play last item of playlist", "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", "PLSET RANDOM" => "Set current playlist item to a random item within playlist", "SETPLPOS" => "Same as PLSET", "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", # Winamp Volume Control "VOLUP" => "Volume up", "VOLDN" => "Volume down", "VOLSET" => "Volume set (scale 0-255)", "VOL=<value>" => "Volume set (scale 0-100)", "VOLMAX" => "Volume max", "VOLMIN" => "Volume min (no sound)" } end \ No newline at end of file diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 3c9e15e..7588aad 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,15 +1,53 @@ body { font-family: Helvetica, Arial, Sans-Serif; - font-size: 11px; + margin: 0; + font-size: 13px; } table { - width: 60%; + width: 100%; border-collapse: collapse; + font-size: 11px; } th, td { text-align: left; padding: 5px; border: 1px solid silver; +} + +#header { + width: 100%; + background: #333; + color: white; + padding: 20px 0px; + margin-bottom: 20px; + border-top: 5px solid black; +} + +#header h1, #header h3 { + padding: 0px 20px; +} +#header h1 { + font-size: 32px; + font-weight: normal; + margin: 0; +} + +#nav { + float: left; + margin: 0px 20px; +} + +#nav a { + display: block; + margin: 0px 0px 5px; +} + +#body { + float: left; +} + +#body h1 { + margin: 0px 0px 10px; } \ No newline at end of file
SeanRoberts/easylistening
764d9a09a0e3dfe04ee71ca799b5d0ff0dd42a10
Ok I think I've got a better handle on CLamp now.
diff --git a/app/controllers/index_controller.rb b/app/controllers/index_controller.rb index ea6bd5b..6a6675b 100644 --- a/app/controllers/index_controller.rb +++ b/app/controllers/index_controller.rb @@ -1,15 +1,19 @@ class IndexController < ApplicationController require 'clamp' def index @tracks = Track.paginate(:include => [:artist, :album], :order => "albums.title, tracks.sort_track_number", :per_page => 200, :page => params[:page]) end def play @track = Track.find(params[:id]) - Clamp.run('plclear') - Clamp.run('load', @track.path) - Clamp.run('play') + Clamp.play(@track.path) + redirect_to :action => :index + end + + def play_album + @album = Album.find(params[:id], :include => "tracks", :order => "tracks.sort_track_number") + Clamp.play_album(@album.tracks) redirect_to :action => :index end end diff --git a/app/models/album.rb b/app/models/album.rb index 46fa309..de0d6a4 100644 --- a/app/models/album.rb +++ b/app/models/album.rb @@ -1,2 +1,3 @@ class Album < ActiveRecord::Base + has_many :tracks, :order => "sort_track_number" end diff --git a/app/views/index/index.html.haml b/app/views/index/index.html.haml index 34c5040..9d04cbb 100644 --- a/app/views/index/index.html.haml +++ b/app/views/index/index.html.haml @@ -1,14 +1,16 @@ %table %tr %th Title %th Artist %th Album %th Track # - @tracks.each do |track| %tr{:class => cycle('normal', 'alternate')} %td = track.title = link_to "play", "/index/play/#{track.id}" + &nbsp; + = link_to "play album", "/index/play_album/#{track.album.id}" if track.album %td= track.artist.title if track.artist %td= track.album.title if track.album %td= track.track_number \ No newline at end of file diff --git a/lib/clamp.rb b/lib/clamp.rb index 90b0902..95888ff 100644 --- a/lib/clamp.rb +++ b/lib/clamp.rb @@ -1,63 +1,76 @@ class Clamp def initialize(path) @path_to_clamp = path end def self.path "F:\\Program Files\\clamp.exe" end def self.run(command, arguments = '') arguments.gsub!(/&&|\||;/, '') return false unless COMMANDS[command] - "#{self.path} /#{command} #{arguments}" + "#{self.path} /#{command} \"#{arguments}\"" end + def self.play(path) + self.run('plclear') + self.run('pladd', path) + self.run('plfirst') + self.run('play') + end + + def self.play_album(tracks) + self.run('plclear') + tracks.each { |track| self.run('pladd', track.path) } + self.run('plfirst') + self.run('play') + end COMMANDS = { # General "START" => "Start Winamp", "QUIT" => "Exit Winamp", "RESTART" =>" => ""Restart Winamp", "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", "STOP" => "Stop playing", "STOPFADE" => "Stop playing with fadout", "STOPAFTER" => "Stop playing after current track (returns now, stops later)", "PAUSE" => "Toggle pause mode", "PAUSE ON|OFF" => "Sets pause mode", "PLAYPAUSE" => "Same as PAUSE", "NEXT" => "Play next song", "PREV" => "Play previous song", "FWD" => "Forward 5 seconds", "REW" => "Rewind 5 seconds", "JUMP" => "Seek to <time> (in millisecs)", "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", # Playlists "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", "LOAD" => "Same as above", "PLCLEAR" => "Clear Playlist", "CLEAR" => "Same as above", "PL" => "Show/Hide Winamp Playlist window", "PLWIN" => "Same as above", "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", "PLFIRST" => "Play first item of playlist", "PLLAST" => "Play last item of playlist", "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", "PLSET RANDOM" => "Set current playlist item to a random item within playlist", "SETPLPOS" => "Same as PLSET", "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", # Winamp Volume Control "VOLUP" => "Volume up", "VOLDN" => "Volume down", "VOLSET" => "Volume set (scale 0-255)", "VOL=<value>" => "Volume set (scale 0-100)", "VOLMAX" => "Volume max", "VOLMIN" => "Volume min (no sound)" } end \ No newline at end of file
SeanRoberts/easylistening
c6f1c58baf93653227cb12cf1adbc7b48347a7af
Fixed clamp (hopefully)
diff --git a/app/controllers/index_controller.rb b/app/controllers/index_controller.rb index 3f415f1..ea6bd5b 100644 --- a/app/controllers/index_controller.rb +++ b/app/controllers/index_controller.rb @@ -1,13 +1,15 @@ class IndexController < ApplicationController require 'clamp' def index @tracks = Track.paginate(:include => [:artist, :album], :order => "albums.title, tracks.sort_track_number", :per_page => 200, :page => params[:page]) end def play @track = Track.find(params[:id]) - Clamp.run('PLAY', @track.path) + Clamp.run('plclear') + Clamp.run('load', @track.path) + Clamp.run('play') redirect_to :action => :index end end diff --git a/lib/clamp.rb b/lib/clamp.rb index 099660a..90b0902 100644 --- a/lib/clamp.rb +++ b/lib/clamp.rb @@ -1,63 +1,63 @@ class Clamp def initialize(path) @path_to_clamp = path end def self.path "F:\\Program Files\\clamp.exe" end def self.run(command, arguments = '') arguments.gsub!(/&&|\||;/, '') return false unless COMMANDS[command] - "#{self.path} #{command} #{arguments}" + "#{self.path} /#{command} #{arguments}" end COMMANDS = { # General "START" => "Start Winamp", "QUIT" => "Exit Winamp", "RESTART" =>" => ""Restart Winamp", "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", "STOP" => "Stop playing", "STOPFADE" => "Stop playing with fadout", "STOPAFTER" => "Stop playing after current track (returns now, stops later)", "PAUSE" => "Toggle pause mode", "PAUSE ON|OFF" => "Sets pause mode", "PLAYPAUSE" => "Same as PAUSE", "NEXT" => "Play next song", "PREV" => "Play previous song", "FWD" => "Forward 5 seconds", "REW" => "Rewind 5 seconds", "JUMP" => "Seek to <time> (in millisecs)", "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", # Playlists "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", "LOAD" => "Same as above", "PLCLEAR" => "Clear Playlist", "CLEAR" => "Same as above", "PL" => "Show/Hide Winamp Playlist window", "PLWIN" => "Same as above", "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", "PLFIRST" => "Play first item of playlist", "PLLAST" => "Play last item of playlist", "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", "PLSET RANDOM" => "Set current playlist item to a random item within playlist", "SETPLPOS" => "Same as PLSET", "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", # Winamp Volume Control "VOLUP" => "Volume up", "VOLDN" => "Volume down", "VOLSET" => "Volume set (scale 0-255)", "VOL=<value>" => "Volume set (scale 0-100)", "VOLMAX" => "Volume max", "VOLMIN" => "Volume min (no sound)" } end \ No newline at end of file
SeanRoberts/easylistening
6441d6c77b04e6671b6d139e32f9b80b87259010
The simplest thing that could possibly work
diff --git a/app/controllers/index_controller.rb b/app/controllers/index_controller.rb index 3690832..3f415f1 100644 --- a/app/controllers/index_controller.rb +++ b/app/controllers/index_controller.rb @@ -1,9 +1,13 @@ class IndexController < ApplicationController + require 'clamp' + def index @tracks = Track.paginate(:include => [:artist, :album], :order => "albums.title, tracks.sort_track_number", :per_page => 200, :page => params[:page]) end def play - Itunes::play() + @track = Track.find(params[:id]) + Clamp.run('PLAY', @track.path) + redirect_to :action => :index end end diff --git a/app/views/index/index.html.haml b/app/views/index/index.html.haml index 8977a97..34c5040 100644 --- a/app/views/index/index.html.haml +++ b/app/views/index/index.html.haml @@ -1,12 +1,14 @@ %table %tr %th Title %th Artist %th Album %th Track # - @tracks.each do |track| %tr{:class => cycle('normal', 'alternate')} - %td= track.title + %td + = track.title + = link_to "play", "/index/play/#{track.id}" %td= track.artist.title if track.artist %td= track.album.title if track.album %td= track.track_number \ No newline at end of file diff --git a/lib/clamp.rb b/lib/clamp.rb index 74373d0..099660a 100644 --- a/lib/clamp.rb +++ b/lib/clamp.rb @@ -1,60 +1,63 @@ class Clamp - attr_accessor :path_to_clamp def initialize(path) @path_to_clamp = path end - def run(command, arguments = '') + def self.path + "F:\\Program Files\\clamp.exe" + end + + def self.run(command, arguments = '') arguments.gsub!(/&&|\||;/, '') return false unless COMMANDS[command] - "#{path_to_clamp} #{command} #{arguments}" + "#{self.path} #{command} #{arguments}" end COMMANDS = { # General "START" => "Start Winamp", "QUIT" => "Exit Winamp", "RESTART" =>" => ""Restart Winamp", "PLAY" =>" => ""Play (current file) - Quits Stopped or Pause mode", "STOP" => "Stop playing", "STOPFADE" => "Stop playing with fadout", "STOPAFTER" => "Stop playing after current track (returns now, stops later)", "PAUSE" => "Toggle pause mode", "PAUSE ON|OFF" => "Sets pause mode", "PLAYPAUSE" => "Same as PAUSE", "NEXT" => "Play next song", "PREV" => "Play previous song", "FWD" => "Forward 5 seconds", "REW" => "Rewind 5 seconds", "JUMP" => "Seek to <time> (in millisecs)", "QUITAFTER" => "Close winamp upon completion of current track - CLAmp will not return immediately", # Playlists "PLADD" => "Add file(s) to end of playlist (like drag-n-drop)", "LOAD" => "Same as above", "PLCLEAR" => "Clear Playlist", "CLEAR" => "Same as above", "PL" => "Show/Hide Winamp Playlist window", "PLWIN" => "Same as above", "PLPOS" => "Query Playlist position (requires Winamp 2.05+)", "PLFIRST" => "Play first item of playlist", "PLLAST" => "Play last item of playlist", "PLSET <num>" => "Set current playlist item (note this does not interfere with curring playing, if needed, use /PLAY after to go to this item)", "PLSET RANDOM" => "Set current playlist item to a random item within playlist", "SETPLPOS" => "Same as PLSET", "LOADNEW <file>" => "Same as /PLCLEAR /PLADD <file>", "LOADPLAY <file>" => "Shortcut for /PLCLEAR /PLADD <file> /PLAY", "PLSAVE <file>" => "Saves current playlist to <file> (as a M3U file)", # Winamp Volume Control "VOLUP" => "Volume up", "VOLDN" => "Volume down", "VOLSET" => "Volume set (scale 0-255)", "VOL=<value>" => "Volume set (scale 0-100)", "VOLMAX" => "Volume max", "VOLMIN" => "Volume min (no sound)" } end \ No newline at end of file
noahgibbs/noahgibbs.github.com
59509742e349abb46c649f861e4cbf1230cf3858
Add WMJ and Shanna's Pizza
diff --git a/index.html b/index.html index 31849ba..2d2e79a 100644 --- a/index.html +++ b/index.html @@ -1,33 +1,37 @@ <html> <head> <title> Noah Gibbs on GitHub </title> </head> <body> <h1> Noah Gibbs's Projects </h1> <p> All projects' source code can be found in my <a href="http://github.com/noahgibbs">GitHub repository</a>. </p> <h2> Large, Useful or Complete Projects </h2> <ul> - <li> <a href="RailsGame">RailsGame</a>, an architecture for games </li> + <li> <a href="http://wantmyjob.com">WantMyJob</a>, a peer-to-peer job-hunting + web site </li> + <li> <a href="http://github.com/noahgibbs/shannas_pizza">Shanna's Pizza</a>, + a simple teaching game of circuit design (Windows and Linux, SDL) </li> <li> <a href="cheaptoad">CheapToad</a>, a Rails plugin to turn your app into a server for <a href="http://hoptoadapp.com">Hoptoad</a> errors</li> + <li> <a href="http://blog.angelbob.com">My blog</a>, every Rails programmer + should write one :-) </li> + <li> <a href="RailsGame">RailsGame</a>, an architecture for games </li> <li> <a href="http://github.com/on-site/easypartials">EasyPartials</a> has moved to On-Site's GitHub repo. They're my employer, and the idea for the gem was based on a coworker's idea. </li> - <li> <a href="http://blog.angelbob.com">My blog</a>, every Rails programmer - should write one :-) </li> <li> <a href="diffeq">DiffEQ</a>, a symbolic math and differential equation package, written entirely in Ruby </li> </ul> <p> For minor stuff, don't look here -- just check the GitHub repository. </p> </body>
noahgibbs/noahgibbs.github.com
84aa1e7207a4ecba39c4790013e6fd1e713cb449
Trim down index
diff --git a/index.html b/index.html index be4f390..31849ba 100644 --- a/index.html +++ b/index.html @@ -1,37 +1,33 @@ <html> <head> <title> Noah Gibbs on GitHub </title> </head> <body> <h1> Noah Gibbs's Projects </h1> <p> All projects' source code can be found in my <a href="http://github.com/noahgibbs">GitHub repository</a>. </p> -<h3> Game Projects </h3> +<h2> Large, Useful or Complete Projects </h2> <ul> <li> <a href="RailsGame">RailsGame</a>, an architecture for games </li> - <li> <a href="Astrino">The Defense of Astrino</a> (using RailsGame) </li> - <li> <a href="RailsMUD">RailsMUD</a> (using RailsGame) </li> -</ul> - -<h3> Other Projects </h3> - -<ul> <li> <a href="cheaptoad">CheapToad</a>, a Rails plugin to turn your app into a server for <a href="http://hoptoadapp.com">Hoptoad</a> errors</li> - <li> <a href="easypartials">EasyPartials</a>, a simple Ruby on Rails - helper for easy use of partials in your views </li> + <li> <a href="http://github.com/on-site/easypartials">EasyPartials</a> has + moved to On-Site's GitHub repo. They're my employer, and the idea for + the gem was based on a coworker's idea. </li> <li> <a href="http://blog.angelbob.com">My blog</a>, every Rails programmer should write one :-) </li> <li> <a href="diffeq">DiffEQ</a>, a symbolic math and differential equation package, written entirely in Ruby </li> - <li> <a href="maslow">Maslow</a>, a simple AI library for judging the - effect of future actions on future happiness</li> </ul> +<p> + For minor stuff, don't look here -- just check the GitHub repository. +</p> + </body>
noahgibbs/noahgibbs.github.com
9c559bea7268567252a9d11279960b07c5374a78
Add Maslow link
diff --git a/index.html b/index.html index 3edf46f..be4f390 100644 --- a/index.html +++ b/index.html @@ -1,35 +1,37 @@ <html> <head> <title> Noah Gibbs on GitHub </title> </head> <body> <h1> Noah Gibbs's Projects </h1> <p> All projects' source code can be found in my <a href="http://github.com/noahgibbs">GitHub repository</a>. </p> <h3> Game Projects </h3> <ul> <li> <a href="RailsGame">RailsGame</a>, an architecture for games </li> <li> <a href="Astrino">The Defense of Astrino</a> (using RailsGame) </li> <li> <a href="RailsMUD">RailsMUD</a> (using RailsGame) </li> </ul> <h3> Other Projects </h3> <ul> <li> <a href="cheaptoad">CheapToad</a>, a Rails plugin to turn your app into a server for <a href="http://hoptoadapp.com">Hoptoad</a> errors</li> <li> <a href="easypartials">EasyPartials</a>, a simple Ruby on Rails helper for easy use of partials in your views </li> <li> <a href="http://blog.angelbob.com">My blog</a>, every Rails programmer should write one :-) </li> - <li> <a href="diffeq">DiffEQ</a> - a symbolic math and differential equation + <li> <a href="diffeq">DiffEQ</a>, a symbolic math and differential equation package, written entirely in Ruby </li> + <li> <a href="maslow">Maslow</a>, a simple AI library for judging the + effect of future actions on future happiness</li> </ul> </body>
noahgibbs/noahgibbs.github.com
d6c94bb28e049f100072f686ba00ef77d2b5aa8b
Add DiffEQ link
diff --git a/index.html b/index.html index 6e45322..3edf46f 100644 --- a/index.html +++ b/index.html @@ -1,34 +1,35 @@ <html> <head> <title> Noah Gibbs on GitHub </title> </head> <body> <h1> Noah Gibbs's Projects </h1> <p> All projects' source code can be found in my <a href="http://github.com/noahgibbs">GitHub repository</a>. </p> <h3> Game Projects </h3> <ul> <li> <a href="RailsGame">RailsGame</a>, an architecture for games </li> <li> <a href="Astrino">The Defense of Astrino</a> (using RailsGame) </li> <li> <a href="RailsMUD">RailsMUD</a> (using RailsGame) </li> </ul> <h3> Other Projects </h3> <ul> <li> <a href="cheaptoad">CheapToad</a>, a Rails plugin to turn your app into a server for <a href="http://hoptoadapp.com">Hoptoad</a> errors</li> <li> <a href="easypartials">EasyPartials</a>, a simple Ruby on Rails helper for easy use of partials in your views </li> <li> <a href="http://blog.angelbob.com">My blog</a>, every Rails programmer should write one :-) </li> - <li> DiffEQ - needs to be imported from RubyForge and regemified </li> + <li> <a href="diffeq">DiffEQ</a> - a symbolic math and differential equation + package, written entirely in Ruby </li> </ul> </body>
noahgibbs/noahgibbs.github.com
95f188b3c60f3209e14b4a5eac9e24e9465d75dc
Add links
diff --git a/index.html b/index.html index 521f50a..878ab1f 100644 --- a/index.html +++ b/index.html @@ -1,15 +1,15 @@ <html> <head> <title> Noah Gibbs on GitHub </title> </head> <body> <h1> Noah Gibbs's Projects </h1> <ul> - <li> RailsGame </li> - <li> RailsMUD </li> + <li> <a href="RailsGame">RailsGame</a> </li> + <li> <a href="RailsMUD">RailsMUD</a> </li> <li> DiffEQ </li> </ul> </body>
noahgibbs/noahgibbs.github.com
63f767fd4e763e87f7731438465df30db985c5e7
Add .gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8346063 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +#*# +*~
dansch/happy_menu
4268b47b46b4ccd4ef9b798dacacb22aa0eb8d3d
improved README
diff --git a/README.rdoc b/README.rdoc index 168419b..90b3c34 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,44 +1,44 @@ == HappyMenu Simple highlighted HTML-Menus in Rails. No more crazy view logic, no instance variables in controllers - you can be happy with your menu again. == Example === Simple Example <% happy_menu do %> <% happy_menu_item "Start", dashboard_path, [{:dashboard => [:index]}] %> <% happy_menu_item "Projects", projects_path, [:projects] %> <% happy_menu_item "Log Out", logout_path, nil %> <% end %> Let's say you are calling the dashboard controller's index action. <ul> <li><a href="your_dashboard_link" class="selected"></a></li> <li><a href="your_projects_link"></a></li> <li><a href="your_log_out_link"></a></li> </ul> === Advanced Example Still to come == Usage -HappyMenu provides you simple ViewHelpers and performs the selection of a menu item based on the current controller action. It uses the controller_name and action_name to determine the current selection. It expects an array or nil. Each array element can either be a symbol or a hash. Use a symbol if all controller actions should be selected, a hash to set the selection per action. +HappyMenu provides simple ViewHelpers and performs the selection of a menu item based on the current controller action. It uses the controller_name and action_name to determine the current selection. It expects an array or nil. Each array element can either be a symbol or a hash. Use a symbol if all controller actions should be selected, a hash to set the selection per action. == Configuration HappyMenu can either be customized on a global level or via each method call. See HappyMenu::Base for details. == TODO * Rails version testing (Not tested in Rails 3 yet) * Fix indentation for haml templates == Project Info Thanks to Henning Peters for the initial idea. Copyright (c) 2010 Daniel Schoppmann, released under the MIT license
dansch/happy_menu
5de9617c649284279f4c8788a6f99e4409ad14eb
used assert_dom_equal in tests
diff --git a/README.rdoc b/README.rdoc index 62698fe..168419b 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,45 +1,44 @@ == HappyMenu Simple highlighted HTML-Menus in Rails. No more crazy view logic, no instance variables in controllers - you can be happy with your menu again. == Example === Simple Example <% happy_menu do %> <% happy_menu_item "Start", dashboard_path, [{:dashboard => [:index]}] %> <% happy_menu_item "Projects", projects_path, [:projects] %> <% happy_menu_item "Log Out", logout_path, nil %> <% end %> -Let's say you calling the index action on the dashboard controller it will produce: +Let's say you are calling the dashboard controller's index action. <ul> <li><a href="your_dashboard_link" class="selected"></a></li> <li><a href="your_projects_link"></a></li> <li><a href="your_log_out_link"></a></li> </ul> === Advanced Example Still to come == Usage -HappyMenu provides you with ViewHelpers and performs the selection of a menu item based on the current controller action. It uses the current controller_name and action_name to determine the current selection. It expects an array or nil. Each array element can either be a symbol or a hash. Use a symbol if alle controller actions should be selected, a hash to set the selection on an per action basis. +HappyMenu provides you simple ViewHelpers and performs the selection of a menu item based on the current controller action. It uses the controller_name and action_name to determine the current selection. It expects an array or nil. Each array element can either be a symbol or a hash. Use a symbol if all controller actions should be selected, a hash to set the selection per action. == Configuration -HappyMenu can either be customized on a global level or via each method call. See base.rb for details. +HappyMenu can either be customized on a global level or via each method call. See HappyMenu::Base for details. == TODO -* improved documentation -* Rails version testing +* Rails version testing (Not tested in Rails 3 yet) * Fix indentation for haml templates == Project Info Thanks to Henning Peters for the initial idea. Copyright (c) 2010 Daniel Schoppmann, released under the MIT license diff --git a/test/happy_menu_test.rb b/test/happy_menu_test.rb index 61dab33..37efd65 100644 --- a/test/happy_menu_test.rb +++ b/test/happy_menu_test.rb @@ -1,78 +1,78 @@ require 'test_helper' class HappyMenuTest < ActionView::TestCase include HappyMenuTestHelper def setup mock_everything end test "global settings" do assert_equal :ul, HappyMenu::Base.menu_options[:menu_tag] assert_equal :li, HappyMenu::Base.menu_options[:menu_item_tag] assert_equal 'selected', HappyMenu::Base.menu_options[:active_class] assert_equal true, HappyMenu::Base.menu_options[:active_link_wrapper] end test "basic happy_menu" do - assert_equal "<ul></ul>", happy_menu{} + assert_dom_equal "<ul></ul>", happy_menu{} end test "happy_menu with html attributes" do expected = "<ul class=\"test_class\" id=\"test_id\"></ul>" - assert_equal expected, happy_menu({:class => "test_class", :id => "test_id"}){} + assert_dom_equal expected, happy_menu({:class => "test_class", :id => "test_id"}){} end test "happy_menu with menu options" do expected = "<ol></ol>" - assert_equal expected, happy_menu({}, {:menu_tag => 'ol'}){} + assert_dom_equal expected, happy_menu({}, {:menu_tag => 'ol'}){} end test "happy_menu with global setting" do HappyMenu::Base.menu_options[:menu_tag] = :ol expected = "<ol></ol>" - assert_equal expected, happy_menu{} + assert_dom_equal expected, happy_menu{} HappyMenu::Base.menu_options[:menu_tag] = :ul end test "basic happy_menu_item" do expected = "<li><a href=\"/projects\">Test</a></li>" - assert_equal expected, happy_menu_item("Test", projects_path, nil) + assert_dom_equal expected, happy_menu_item("Test", projects_path, nil) end test "happy_menu_item with html attributes" do - expected = "<li class=\"test_class\" id=\"test_id\"><a href=\"/projects\">Test</a></li>" - assert_equal expected, happy_menu_item("Test", projects_path, nil, {:id => "test_id", :class => "test_class"}) + expected = "<li id=\"test_id\" class=\"test_class\"><a href=\"/projects\">Test</a></li>" + assert_dom_equal expected, happy_menu_item("Test", projects_path, nil, {:id => "test_id", :class => "test_class"}) end test "happy_menu_item with link options" do expected = "<li><a href=\"/projects\" id=\"test_id\">Test</a></li>" - assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {:id => "test_id"}) + assert_dom_equal expected, happy_menu_item("Test", projects_path, nil, {}, {:id => "test_id"}) end test "happy_menu_item with menu options" do expected = "<h2><a href=\"/projects\">Test</a></h2>" - assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {}, {:menu_item_tag => 'h2'}) + assert_dom_equal expected, happy_menu_item("Test", projects_path, nil, {}, {}, {:menu_item_tag => 'h2'}) end test "happy_menu_item with global setting" do HappyMenu::Base.menu_options[:menu_item_tag] = :h2 expected = "<h2><a href=\"/projects\">Test</a></h2>" - assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {}, {:menu_item_tag => 'h2'}) + assert_dom_equal expected, happy_menu_item("Test", projects_path, nil, {}, {}, {:menu_item_tag => 'h2'}) HappyMenu::Base.menu_options[:menu_item_tag] = :li end test "happy_menu_item with submenu" do expected = "<li><a href=\"/projects\">Test</a><ul></ul></li>" - assert_equal expected, happy_menu_item("Test", projects_path, nil){happy_menu{}} + assert_dom_equal expected, happy_menu_item("Test", projects_path, nil){happy_menu{}} end # TODO test for selection (setting the css_class) #test "happy_menu_item with selection" do # stub controller_name # expected = "<li><a href=\"/projects\">Test</a></li>" # assert_equal expected, happy_menu_item("Test", projects_path, [:projects]) #end end
dansch/happy_menu
14e6941d353bbde2778a27831be491c308daf9aa
fix in uncommented section
diff --git a/test/happy_menu_test.rb b/test/happy_menu_test.rb index e9395e7..61dab33 100644 --- a/test/happy_menu_test.rb +++ b/test/happy_menu_test.rb @@ -1,78 +1,78 @@ require 'test_helper' class HappyMenuTest < ActionView::TestCase include HappyMenuTestHelper def setup mock_everything end test "global settings" do assert_equal :ul, HappyMenu::Base.menu_options[:menu_tag] assert_equal :li, HappyMenu::Base.menu_options[:menu_item_tag] assert_equal 'selected', HappyMenu::Base.menu_options[:active_class] assert_equal true, HappyMenu::Base.menu_options[:active_link_wrapper] end test "basic happy_menu" do assert_equal "<ul></ul>", happy_menu{} end test "happy_menu with html attributes" do expected = "<ul class=\"test_class\" id=\"test_id\"></ul>" assert_equal expected, happy_menu({:class => "test_class", :id => "test_id"}){} end test "happy_menu with menu options" do expected = "<ol></ol>" assert_equal expected, happy_menu({}, {:menu_tag => 'ol'}){} end test "happy_menu with global setting" do HappyMenu::Base.menu_options[:menu_tag] = :ol expected = "<ol></ol>" assert_equal expected, happy_menu{} HappyMenu::Base.menu_options[:menu_tag] = :ul end test "basic happy_menu_item" do expected = "<li><a href=\"/projects\">Test</a></li>" assert_equal expected, happy_menu_item("Test", projects_path, nil) end test "happy_menu_item with html attributes" do expected = "<li class=\"test_class\" id=\"test_id\"><a href=\"/projects\">Test</a></li>" assert_equal expected, happy_menu_item("Test", projects_path, nil, {:id => "test_id", :class => "test_class"}) end test "happy_menu_item with link options" do expected = "<li><a href=\"/projects\" id=\"test_id\">Test</a></li>" assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {:id => "test_id"}) end test "happy_menu_item with menu options" do expected = "<h2><a href=\"/projects\">Test</a></h2>" assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {}, {:menu_item_tag => 'h2'}) end test "happy_menu_item with global setting" do HappyMenu::Base.menu_options[:menu_item_tag] = :h2 expected = "<h2><a href=\"/projects\">Test</a></h2>" assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {}, {:menu_item_tag => 'h2'}) HappyMenu::Base.menu_options[:menu_item_tag] = :li end test "happy_menu_item with submenu" do expected = "<li><a href=\"/projects\">Test</a><ul></ul></li>" assert_equal expected, happy_menu_item("Test", projects_path, nil){happy_menu{}} end # TODO test for selection (setting the css_class) #test "happy_menu_item with selection" do # stub controller_name # expected = "<li><a href=\"/projects\">Test</a></li>" # assert_equal expected, happy_menu_item("Test", projects_path, [:projects]) - end + #end end
dansch/happy_menu
9271e4052cd719408450e18098ffed6fe52d8d79
added tests
diff --git a/README.rdoc b/README.rdoc index 9a71294..62698fe 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,46 +1,45 @@ == HappyMenu -HTML-Menus made simple. No crazy view logic, no instance variables in controllers - you can be happy with your menu again. +Simple highlighted HTML-Menus in Rails. No more crazy view logic, no instance variables in controllers - you can be happy with your menu again. == Example === Simple Example <% happy_menu do %> <% happy_menu_item "Start", dashboard_path, [{:dashboard => [:index]}] %> <% happy_menu_item "Projects", projects_path, [:projects] %> <% happy_menu_item "Log Out", logout_path, nil %> <% end %> Let's say you calling the index action on the dashboard controller it will produce: <ul> <li><a href="your_dashboard_link" class="selected"></a></li> <li><a href="your_projects_link"></a></li> <li><a href="your_log_out_link"></a></li> </ul> === Advanced Example Still to come == Usage HappyMenu provides you with ViewHelpers and performs the selection of a menu item based on the current controller action. It uses the current controller_name and action_name to determine the current selection. It expects an array or nil. Each array element can either be a symbol or a hash. Use a symbol if alle controller actions should be selected, a hash to set the selection on an per action basis. == Configuration HappyMenu can either be customized on a global level or via each method call. See base.rb for details. == TODO -* Tests * improved documentation * Rails version testing * Fix indentation for haml templates == Project Info Thanks to Henning Peters for the initial idea. Copyright (c) 2010 Daniel Schoppmann, released under the MIT license diff --git a/lib/happy_menu.rb b/lib/happy_menu.rb index 66d5863..3ab8f7d 100644 --- a/lib/happy_menu.rb +++ b/lib/happy_menu.rb @@ -1,5 +1,6 @@ require 'happy_menu/base' +require 'happy_menu/selector' class ActionView::Base include HappyMenu::Base end \ No newline at end of file diff --git a/tasks/happy_menu_tasks.rake b/tasks/happy_menu_tasks.rake deleted file mode 100644 index fa04fd9..0000000 --- a/tasks/happy_menu_tasks.rake +++ /dev/null @@ -1,4 +0,0 @@ -# desc "Explaining what the task does" -# task :happy_menu do -# # Task goes here -# end diff --git a/test/happy_menu_test.rb b/test/happy_menu_test.rb index debe991..e9395e7 100644 --- a/test/happy_menu_test.rb +++ b/test/happy_menu_test.rb @@ -1,8 +1,78 @@ require 'test_helper' -class HappyMenuTest < ActiveSupport::TestCase - # Replace this with your real tests. - test "the truth" do - assert true +class HappyMenuTest < ActionView::TestCase + include HappyMenuTestHelper + + def setup + mock_everything end + + test "global settings" do + assert_equal :ul, HappyMenu::Base.menu_options[:menu_tag] + assert_equal :li, HappyMenu::Base.menu_options[:menu_item_tag] + assert_equal 'selected', HappyMenu::Base.menu_options[:active_class] + assert_equal true, HappyMenu::Base.menu_options[:active_link_wrapper] + end + + test "basic happy_menu" do + assert_equal "<ul></ul>", happy_menu{} + end + + test "happy_menu with html attributes" do + expected = "<ul class=\"test_class\" id=\"test_id\"></ul>" + assert_equal expected, happy_menu({:class => "test_class", :id => "test_id"}){} + end + + test "happy_menu with menu options" do + expected = "<ol></ol>" + assert_equal expected, happy_menu({}, {:menu_tag => 'ol'}){} + end + + test "happy_menu with global setting" do + HappyMenu::Base.menu_options[:menu_tag] = :ol + expected = "<ol></ol>" + assert_equal expected, happy_menu{} + HappyMenu::Base.menu_options[:menu_tag] = :ul + end + + test "basic happy_menu_item" do + expected = "<li><a href=\"/projects\">Test</a></li>" + assert_equal expected, happy_menu_item("Test", projects_path, nil) + end + + test "happy_menu_item with html attributes" do + expected = "<li class=\"test_class\" id=\"test_id\"><a href=\"/projects\">Test</a></li>" + assert_equal expected, happy_menu_item("Test", projects_path, nil, {:id => "test_id", :class => "test_class"}) + end + + test "happy_menu_item with link options" do + expected = "<li><a href=\"/projects\" id=\"test_id\">Test</a></li>" + assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {:id => "test_id"}) + end + + test "happy_menu_item with menu options" do + expected = "<h2><a href=\"/projects\">Test</a></h2>" + assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {}, {:menu_item_tag => 'h2'}) + end + + test "happy_menu_item with global setting" do + HappyMenu::Base.menu_options[:menu_item_tag] = :h2 + expected = "<h2><a href=\"/projects\">Test</a></h2>" + assert_equal expected, happy_menu_item("Test", projects_path, nil, {}, {}, {:menu_item_tag => 'h2'}) + HappyMenu::Base.menu_options[:menu_item_tag] = :li + end + + test "happy_menu_item with submenu" do + expected = "<li><a href=\"/projects\">Test</a><ul></ul></li>" + assert_equal expected, happy_menu_item("Test", projects_path, nil){happy_menu{}} + end + + # TODO test for selection (setting the css_class) + + #test "happy_menu_item with selection" do + # stub controller_name + # expected = "<li><a href=\"/projects\">Test</a></li>" + # assert_equal expected, happy_menu_item("Test", projects_path, [:projects]) + end + end diff --git a/test/test_helper.rb b/test/test_helper.rb index cf148b8..f57d562 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,3 +1,43 @@ require 'rubygems' -require 'active_support' -require 'active_support/test_case' \ No newline at end of file +require 'test/unit' +require 'action_controller' +require 'action_view' +require 'action_controller/test_case' +require 'action_view/test_case' + +require File.expand_path(File.join(File.dirname(__FILE__), '../lib/happy_menu')) + + +module HappyMenuTestHelper + # include ActionView::Helpers::FormHelper + # include ActionView::Helpers::FormTagHelper + # include ActionView::Helpers::FormOptionsHelper + # include ActionView::Helpers::UrlHelper + # include ActionView::Helpers::TagHelper + # include ActionView::Helpers::TextHelper + # include ActionView::Helpers::ActiveRecordHelper + # include ActionView::Helpers::RecordIdentificationHelper + # include ActionView::Helpers::CaptureHelper + # include ActiveSupport + # include ActionController::PolymorphicRoutes + + include HappyMenu::Base + + class ::Project + def id + end + end + + def mock_everything + + # Resource-oriented styles like form_for(@post) will expect a path method for the object, + # so we're defining some here. + def project_path(o); "/projects/1"; end + def projects_path; "/projects"; end + + def user_path(o); "/users/1"; end + def users_path; "/users"; end + + end + +end
dansch/happy_menu
fc863359c8272d9dbed94dbb20e2410828b9a1e1
removed inactive_class option and improved documentation
diff --git a/lib/happy_menu/base.rb b/lib/happy_menu/base.rb index 0c5d191..52b19ec 100644 --- a/lib/happy_menu/base.rb +++ b/lib/happy_menu/base.rb @@ -1,64 +1,63 @@ module HappyMenu module Base @@menu_options = { :active_class => 'selected', - :inactive_class => 'not-selected', :menu_tag => :ul, :menu_item_tag => :li, :active_link_wrapper => true } mattr_reader :menu_options # creates an outer tag (defaults to ul-Tag) # accepcts block, which might contain menu_items or further menus # - html_options: must be an hash of html-attributes - # - menu_options: to be filled + # - menu_options: must be an hash. Can be used to overwrite default values def happy_menu(html_options={}, menu_options={}, &block) return unless block_given? updated_menu_options = menu_options.symbolize_keys.reverse_merge HappyMenu::Base.menu_options html = content_tag updated_menu_options[:menu_tag].to_sym, html_options do capture(&block) end concat(html) end # creates an inner tag (defaults to li-Tag) # accepts block, so can be nested or filled with any html - # - selectors: must be an array. Can contain Symbols, Strings which will be compared to the controller_name, - # or Hashed, where the key will be compared to the controller_name, the value to the action_name. - # Value can either be an array of Symbols - # E.g. [:users, {:projects => [:index, :edit]}, :tasks] - # - item_options: html attributes for li-element + # - selectors: must be an array. Can contain Symbols, Strings and/or Hashes. Symbols and Strings will be + # compared to the controller_name. The key of a hash will be compared to the controller_name, the value to the action_name. + # Value can either be an array of Symbols or nil for all actions. + # E.g. [:users, {:projects => [:index, :edit]}, :tasks] + # - item_options: html attributes for item tag-element # - link_options: html attributes for a-element - # - menu_options: replace default values of MenuBuilder. Should be set globally, e.g. in an initialier + # - menu_options: must be an hash. Can be used to overwrite default values def happy_menu_item(item, path, selectors, item_options={}, link_options={}, menu_options={}, &block) updated_menu_options = menu_options.symbolize_keys.reverse_merge HappyMenu::Base.menu_options selector_class = HappyMenu::Selector.new(self, updated_menu_options, selectors).result selected = (selector_class == updated_menu_options[:active_class]) if selected item_options[:class] = item_options[:class].blank? ? selector_class : item_options[:class].concat(" #{selector_class}") link_options[:class] = link_options[:class].blank? ? selector_class : link_options[:class].concat(" #{selector_class}") end html, inner_html = "", "" inner_html = capture(&block) if block_given? html += content_tag updated_menu_options[:menu_item_tag].to_sym, item_options do if selected and updated_menu_options[:active_link_wrapper] content_tag :strong, (link_to(item, path, link_options) + inner_html) else link_to(item, path, link_options) + inner_html end end html end end end \ No newline at end of file diff --git a/lib/happy_menu/selector.rb b/lib/happy_menu/selector.rb index 134aa30..558abd3 100644 --- a/lib/happy_menu/selector.rb +++ b/lib/happy_menu/selector.rb @@ -1,35 +1,36 @@ module HappyMenu class Selector attr_accessor :template, :selectors, :options # Selector class to compute actual css_class # # def initialize(template, options, selectors) @selectors = selectors.to_a @template = template @options = options end def result selectors.each do |selector| if selector.is_a?(Hash) and template.controller_name.to_sym == selector.keys.first if selector.values.first.is_a?(Symbol) and template.action_name.to_sym == selector.values.first return options[:active_class] elsif selector.values.first.blank? return options[:active_class] elsif selector.values.first.is_a?(Array) and selector.values.first.include?(template.action_name.to_sym) return options[:active_class] else - return options[:inactive_class] + return nil end elsif selector.is_a?(Symbol) or selector.is_a?(String) - return template.controller_name.to_sym == selector ? options[:active_class] : options[:inactive_class] + return template.controller_name.to_sym == selector ? options[:active_class] : nil else - return options[:inactive_class] + return nil end end end + end end \ No newline at end of file
dansch/happy_menu
f01f83b995826cd1e0fd1c13bc178f2e5cf78604
Improved Readme
diff --git a/README.rdoc b/README.rdoc index 79f0bf6..9a71294 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,43 +1,46 @@ == HappyMenu -Tired of setting instance variables in the controller or building view helpers over and over again to come up with a simple solution for a tab menu selection? In fact, all you want is being happy again? Let HappyMenu help you! +HTML-Menus made simple. No crazy view logic, no instance variables in controllers - you can be happy with your menu again. == Example === Simple Example <% happy_menu do %> <% happy_menu_item "Start", dashboard_path, [{:dashboard => [:index]}] %> <% happy_menu_item "Projects", projects_path, [:projects] %> <% happy_menu_item "Log Out", logout_path, nil %> <% end %> Let's say you calling the index action on the dashboard controller it will produce: <ul> <li><a href="your_dashboard_link" class="selected"></a></li> <li><a href="your_projects_link"></a></li> <li><a href="your_log_out_link"></a></li> </ul> === Advanced Example Still to come == Usage -HappyMenu uses the current controller_name and action_name to determine the current selection. It expects an array, where each element can either be a symbol to the the selection on every action or a hash to set the selection on an per action basis. +HappyMenu provides you with ViewHelpers and performs the selection of a menu item based on the current controller action. It uses the current controller_name and action_name to determine the current selection. It expects an array or nil. Each array element can either be a symbol or a hash. Use a symbol if alle controller actions should be selected, a hash to set the selection on an per action basis. == Configuration -Still to come +HappyMenu can either be customized on a global level or via each method call. See base.rb for details. == TODO * Tests * improved documentation * Rails version testing +* Fix indentation for haml templates == Project Info +Thanks to Henning Peters for the initial idea. + Copyright (c) 2010 Daniel Schoppmann, released under the MIT license
dansch/happy_menu
f14adbd3db2a1417b2bfdb181995e28218ae79a1
improved README
diff --git a/README.rdoc b/README.rdoc index 6baf594..79f0bf6 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,43 +1,43 @@ == HappyMenu -Tired of setting instance variables in the controller or build your view helpers over and over again to come up with a simple solution to show the user which navigation element is selected?. In fact, all you just want to be is happy again? Let HappyMenu be your rescue. +Tired of setting instance variables in the controller or building view helpers over and over again to come up with a simple solution for a tab menu selection? In fact, all you want is being happy again? Let HappyMenu help you! == Example === Simple Example <% happy_menu do %> <% happy_menu_item "Start", dashboard_path, [{:dashboard => [:index]}] %> <% happy_menu_item "Projects", projects_path, [:projects] %> <% happy_menu_item "Log Out", logout_path, nil %> <% end %> Let's say you calling the index action on the dashboard controller it will produce: <ul> <li><a href="your_dashboard_link" class="selected"></a></li> <li><a href="your_projects_link"></a></li> <li><a href="your_log_out_link"></a></li> </ul> === Advanced Example Still to come == Usage HappyMenu uses the current controller_name and action_name to determine the current selection. It expects an array, where each element can either be a symbol to the the selection on every action or a hash to set the selection on an per action basis. == Configuration Still to come == TODO * Tests * improved documentation * Rails version testing == Project Info Copyright (c) 2010 Daniel Schoppmann, released under the MIT license
dansch/happy_menu
2e3c6d98765250b3ff846b9362bfd45acda76419
prefixed methods with 'happy' and improved README a bit
diff --git a/README b/README deleted file mode 100644 index 382df6c..0000000 --- a/README +++ /dev/null @@ -1,13 +0,0 @@ -HappyMenu -========= - -Introduction goes here. - - -Example -======= - -Example goes here. - - -Copyright (c) 2010 [name of plugin creator], released under the MIT license diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..6baf594 --- /dev/null +++ b/README.rdoc @@ -0,0 +1,43 @@ +== HappyMenu + +Tired of setting instance variables in the controller or build your view helpers over and over again to come up with a simple solution to show the user which navigation element is selected?. In fact, all you just want to be is happy again? Let HappyMenu be your rescue. + +== Example + +=== Simple Example + + <% happy_menu do %> + <% happy_menu_item "Start", dashboard_path, [{:dashboard => [:index]}] %> + <% happy_menu_item "Projects", projects_path, [:projects] %> + <% happy_menu_item "Log Out", logout_path, nil %> + <% end %> + +Let's say you calling the index action on the dashboard controller it will produce: + + <ul> + <li><a href="your_dashboard_link" class="selected"></a></li> + <li><a href="your_projects_link"></a></li> + <li><a href="your_log_out_link"></a></li> + </ul> + +=== Advanced Example + +Still to come + +== Usage + +HappyMenu uses the current controller_name and action_name to determine the current selection. It expects an array, where each element can either be a symbol to the the selection on every action or a hash to set the selection on an per action basis. + +== Configuration + +Still to come + +== TODO + +* Tests +* improved documentation +* Rails version testing + +== Project Info + +Copyright (c) 2010 Daniel Schoppmann, released under the MIT license diff --git a/lib/happy_menu/base.rb b/lib/happy_menu/base.rb index 2b5b7b4..0c5d191 100644 --- a/lib/happy_menu/base.rb +++ b/lib/happy_menu/base.rb @@ -1,64 +1,64 @@ module HappyMenu module Base @@menu_options = { :active_class => 'selected', :inactive_class => 'not-selected', :menu_tag => :ul, :menu_item_tag => :li, :active_link_wrapper => true } mattr_reader :menu_options # creates an outer tag (defaults to ul-Tag) # accepcts block, which might contain menu_items or further menus # - html_options: must be an hash of html-attributes # - menu_options: to be filled - def menu(html_options={}, menu_options={}, &block) + def happy_menu(html_options={}, menu_options={}, &block) return unless block_given? updated_menu_options = menu_options.symbolize_keys.reverse_merge HappyMenu::Base.menu_options html = content_tag updated_menu_options[:menu_tag].to_sym, html_options do capture(&block) end concat(html) end # creates an inner tag (defaults to li-Tag) # accepts block, so can be nested or filled with any html # - selectors: must be an array. Can contain Symbols, Strings which will be compared to the controller_name, # or Hashed, where the key will be compared to the controller_name, the value to the action_name. # Value can either be an array of Symbols # E.g. [:users, {:projects => [:index, :edit]}, :tasks] # - item_options: html attributes for li-element # - link_options: html attributes for a-element # - menu_options: replace default values of MenuBuilder. Should be set globally, e.g. in an initialier - def menu_item(item, path, selectors, item_options={}, link_options={}, menu_options={}, &block) + def happy_menu_item(item, path, selectors, item_options={}, link_options={}, menu_options={}, &block) updated_menu_options = menu_options.symbolize_keys.reverse_merge HappyMenu::Base.menu_options selector_class = HappyMenu::Selector.new(self, updated_menu_options, selectors).result selected = (selector_class == updated_menu_options[:active_class]) if selected item_options[:class] = item_options[:class].blank? ? selector_class : item_options[:class].concat(" #{selector_class}") link_options[:class] = link_options[:class].blank? ? selector_class : link_options[:class].concat(" #{selector_class}") end html, inner_html = "", "" inner_html = capture(&block) if block_given? html += content_tag updated_menu_options[:menu_item_tag].to_sym, item_options do if selected and updated_menu_options[:active_link_wrapper] content_tag :strong, (link_to(item, path, link_options) + inner_html) else link_to(item, path, link_options) + inner_html end end html end end end \ No newline at end of file
dansch/happy_menu
7c2cf526db418a6d9836796bc47be676809b20fa
move plugin to github
diff --git a/README b/README new file mode 100644 index 0000000..382df6c --- /dev/null +++ b/README @@ -0,0 +1,13 @@ +HappyMenu +========= + +Introduction goes here. + + +Example +======= + +Example goes here. + + +Copyright (c) 2010 [name of plugin creator], released under the MIT license diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..96f00ab --- /dev/null +++ b/Rakefile @@ -0,0 +1,23 @@ +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +desc 'Default: run unit tests.' +task :default => :test + +desc 'Test the happy_menu plugin.' +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.libs << 'test' + t.pattern = 'test/**/*_test.rb' + t.verbose = true +end + +desc 'Generate documentation for the happy_menu plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'HappyMenu' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/init.rb b/init.rb new file mode 100644 index 0000000..c40b5c1 --- /dev/null +++ b/init.rb @@ -0,0 +1 @@ +require File.join(File.dirname(__FILE__), 'lib', 'happy_menu') \ No newline at end of file diff --git a/lib/happy_menu.rb b/lib/happy_menu.rb new file mode 100644 index 0000000..66d5863 --- /dev/null +++ b/lib/happy_menu.rb @@ -0,0 +1,5 @@ +require 'happy_menu/base' + +class ActionView::Base + include HappyMenu::Base +end \ No newline at end of file diff --git a/lib/happy_menu/base.rb b/lib/happy_menu/base.rb new file mode 100644 index 0000000..2b5b7b4 --- /dev/null +++ b/lib/happy_menu/base.rb @@ -0,0 +1,64 @@ +module HappyMenu + module Base + @@menu_options = { + :active_class => 'selected', + :inactive_class => 'not-selected', + :menu_tag => :ul, + :menu_item_tag => :li, + :active_link_wrapper => true + } + mattr_reader :menu_options + + # creates an outer tag (defaults to ul-Tag) + # accepcts block, which might contain menu_items or further menus + # - html_options: must be an hash of html-attributes + # - menu_options: to be filled + + def menu(html_options={}, menu_options={}, &block) + return unless block_given? + + updated_menu_options = menu_options.symbolize_keys.reverse_merge HappyMenu::Base.menu_options + + html = content_tag updated_menu_options[:menu_tag].to_sym, html_options do + capture(&block) + end + concat(html) + end + + + # creates an inner tag (defaults to li-Tag) + # accepts block, so can be nested or filled with any html + # - selectors: must be an array. Can contain Symbols, Strings which will be compared to the controller_name, + # or Hashed, where the key will be compared to the controller_name, the value to the action_name. + # Value can either be an array of Symbols + # E.g. [:users, {:projects => [:index, :edit]}, :tasks] + # - item_options: html attributes for li-element + # - link_options: html attributes for a-element + # - menu_options: replace default values of MenuBuilder. Should be set globally, e.g. in an initialier + + def menu_item(item, path, selectors, item_options={}, link_options={}, menu_options={}, &block) + updated_menu_options = menu_options.symbolize_keys.reverse_merge HappyMenu::Base.menu_options + + selector_class = HappyMenu::Selector.new(self, updated_menu_options, selectors).result + selected = (selector_class == updated_menu_options[:active_class]) + + if selected + item_options[:class] = item_options[:class].blank? ? selector_class : item_options[:class].concat(" #{selector_class}") + link_options[:class] = link_options[:class].blank? ? selector_class : link_options[:class].concat(" #{selector_class}") + end + + html, inner_html = "", "" + inner_html = capture(&block) if block_given? + + html += content_tag updated_menu_options[:menu_item_tag].to_sym, item_options do + if selected and updated_menu_options[:active_link_wrapper] + content_tag :strong, (link_to(item, path, link_options) + inner_html) + else + link_to(item, path, link_options) + inner_html + end + end + html + end + end + +end \ No newline at end of file diff --git a/lib/happy_menu/selector.rb b/lib/happy_menu/selector.rb new file mode 100644 index 0000000..134aa30 --- /dev/null +++ b/lib/happy_menu/selector.rb @@ -0,0 +1,35 @@ +module HappyMenu + class Selector + attr_accessor :template, :selectors, :options + + # Selector class to compute actual css_class + # + # + + def initialize(template, options, selectors) + @selectors = selectors.to_a + @template = template + @options = options + end + + def result + selectors.each do |selector| + if selector.is_a?(Hash) and template.controller_name.to_sym == selector.keys.first + if selector.values.first.is_a?(Symbol) and template.action_name.to_sym == selector.values.first + return options[:active_class] + elsif selector.values.first.blank? + return options[:active_class] + elsif selector.values.first.is_a?(Array) and selector.values.first.include?(template.action_name.to_sym) + return options[:active_class] + else + return options[:inactive_class] + end + elsif selector.is_a?(Symbol) or selector.is_a?(String) + return template.controller_name.to_sym == selector ? options[:active_class] : options[:inactive_class] + else + return options[:inactive_class] + end + end + end + end +end \ No newline at end of file diff --git a/tasks/happy_menu_tasks.rake b/tasks/happy_menu_tasks.rake new file mode 100644 index 0000000..fa04fd9 --- /dev/null +++ b/tasks/happy_menu_tasks.rake @@ -0,0 +1,4 @@ +# desc "Explaining what the task does" +# task :happy_menu do +# # Task goes here +# end diff --git a/test/happy_menu_test.rb b/test/happy_menu_test.rb new file mode 100644 index 0000000..debe991 --- /dev/null +++ b/test/happy_menu_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class HappyMenuTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..cf148b8 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,3 @@ +require 'rubygems' +require 'active_support' +require 'active_support/test_case' \ No newline at end of file
wesmaldonado/test-driven-javascript-example-application
5a92b0d3baf6e58a10da773ff5a1ad64090670c8
Adding license
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5bf08cc --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2008 Wes Maldonado <[email protected]> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +
wesmaldonado/test-driven-javascript-example-application
4427f547f9c936bfbed04e967cdaf74a399c1f3b
Adding it
diff --git a/README b/README new file mode 100644 index 0000000..fc17096 --- /dev/null +++ b/README @@ -0,0 +1,2 @@ +Adding the super duper readme. +
browserplus/bp-service-api
f4659cdf2668dc1d6867a7e1cc217fb9de60b04f
v5 service API headers (from platform 2.9.0)
diff --git a/include/ServiceAPI/bpcfunctions.h b/include/ServiceAPI/bpcfunctions.h index 492835b..e1f3fd2 100644 --- a/include/ServiceAPI/bpcfunctions.h +++ b/include/ServiceAPI/bpcfunctions.h @@ -1,159 +1,177 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * Portions created by Yahoo! are Copyright (c) 2010 Yahoo! Inc. * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ /** * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * - * BPC* functions are provided by BPCore and called by the corelet + * BPC* functions are provided by BPCore and called by the service */ #ifndef __BPCFUNCTIONS_H__ #define __BPCFUNCTIONS_H__ #include <ServiceAPI/bptypes.h> #include <ServiceAPI/bpdefinition.h> #ifdef __cplusplus extern "C" { #endif /** * Post results from a called BPPFunctionPtr. * Subsequent to this call, no callbacks passed as parameters to the * service function may be called. This indicates the completion of the * function invocation or transaction. * * \param tid a transaction id passed into the service via the invocation * of a BPPFunctionPtr * \param results The results of the function invocation. */ typedef void (*BPCPostResultsFuncPtr)(unsigned int tid, const BPElement * results); /** * Post an asynchronous error from a called BPPFunctionPtr. * Subsequent to this call, no callbacks passed as parameters to the * service function may be called. This indicates the completion of the * function invocation or transaction. * - * \param tid a transaction id passed into the corelet via the invocation + * \param tid a transaction id passed into the service via the invocation * of a BPPFunctionPtr * \param error A string representation of an error. If NULL, a generic * error will be raised. These strings should be camel * cased english phrases. The service name will be prepended * to the error, and it will be propogated up to the * caller. * \param verboseError An optional english string describing more verbosely * exactly what went wrong. This is intended for * developers. */ typedef void (*BPCPostErrorFuncPtr)(unsigned int tid, const char * error, const char * verboseError); /** * Invoke a callback that was passed into a service function as a * parameter. * * \param tid a transaction id passed into the service via the invocation * of a BPPFunctionPtr * \param callbackHandle A callback handle attained from the original * function invocation. * \param params - the argument to the callback. */ typedef void (*BPCInvokeCallBackFuncPtr)(unsigned int tid, BPCallBack callbackHandle, const BPElement * params); /** log level argument to BPCLogFuncPtr, debug message*/ #define BP_DEBUG 1 /** log level argument to BPCLogFuncPtr, informational message*/ #define BP_INFO 2 /** log level argument to BPCLogFuncPtr, warning message*/ #define BP_WARN 3 /** log level argument to BPCLogFuncPtr, error message*/ #define BP_ERROR 4 /** log level argument to BPCLogFuncPtr, fatal message*/ #define BP_FATAL 5 /** * Output a log a message. * \param level the severity of the log message * \param fmt a printf() style format string * \param varags arguments to the printf() style format string */ typedef void (*BPCLogFuncPtr)(unsigned int level, const char * fmt, ...); /** * The signature of a function capable of recieving a response to a * promptUser request. * * \param context the same void * pointer passed to the BPCPromptUserFuncPtr * \param promptId the same unsigned int returned from BPCPromptUserFuncPtr * \param response the user's response, a data structure mapped from * javascript. */ typedef void (*BPUserResponseCallbackFuncPtr)( void * context, unsigned int promptId, const BPElement * response); /** * Prompt the end user. end user prompting must be associated with * a specific transaction/method invocation. * * \param tid a transaction id passed into the service via the invocation * of a BPPFunctionPtr - * \param utf8PathToHTMLDialog A utf8 string holding the absolute path + * \param pathToHTMLDialog A native "wide" string holding the absolute path * to the dialog you wish to display. * \param arguments The arguments to make available to the dialog * via the BPDialog.args() call * \param responseCallback A Function pointer to invoke when the response * to the user prompt is available. * \param context a pointer to pass to the responseCallback * * \returns A unsigned prompt ID that wil be passed to the * responseCallback */ typedef unsigned int (*BPCPromptUserFuncPtr)( unsigned int tid, - const char * utf8PathToHTMLDialog, + const BPPath pathToHTMLDialog, const BPElement * arguments, BPUserResponseCallbackFuncPtr responseCallback, void * context); +/** + * The signature of a callback as used by the BPCInvokeOnMainThreadPtr function. + */ +typedef void (*BPCMainThreadCallbackPtr)(void); + +/** + * A thread safe way to request that BrowserPlus invoke your service from the + * "main" thread, which is the thread which invokes all functions on the service. + * + * This is a mechanism to allow a service to safely use the event pump of the + * parent process (A BrowserPlus "service" process). + * + * There is no gaurantee that a callback will be delivered (especially in the + * shutdown case). + */ +typedef void (*BPCInvokeOnMainThreadPtr)(BPCMainThreadCallbackPtr cb); + /** * A table containing function pointers for functions available to be * called by services implemented by BrowserPlus. */ typedef struct { BPCPostResultsFuncPtr postResults; BPCPostErrorFuncPtr postError; BPCLogFuncPtr log; BPCInvokeCallBackFuncPtr invoke; BPCPromptUserFuncPtr prompt; + BPCInvokeOnMainThreadPtr invokeOnMainThread; } BPCFunctionTable; #ifdef __cplusplus }; #endif #endif diff --git a/include/ServiceAPI/bpdefinition.h b/include/ServiceAPI/bpdefinition.h index 6650c92..d0bdd40 100644 --- a/include/ServiceAPI/bpdefinition.h +++ b/include/ServiceAPI/bpdefinition.h @@ -1,88 +1,88 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * Portions created by Yahoo! are Copyright (c) 2010 Yahoo! Inc. * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ /** * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * A service is defined by a set if in-memory structures. These * structures are hierarchical and can define a service containing * any number of functions, which themselves accept any number of * arguments. */ #ifndef __BPDEFINITION_H__ #define __BPDEFINITION_H__ #include <ServiceAPI/bptypes.h> #include <ServiceAPI/bperror.h> #ifdef __cplusplus extern "C" { #endif /** The definition of an argument */ typedef struct { /** The name of the agument, all arguments in BrowserPlus are named */ BPString name; /** A human readable english documentation string */ BPString docString; /** The expected type of the argument */ BPType type; /** whether the argument is required or not */ BPBool required; } BPArgumentDefinition; /** The definition of a function */ typedef struct { /** the name of the function */ BPString functionName; /** A human readable english documentation string. */ BPString docString; /** The number of arguements in the arguments array */ unsigned int numArguments; /** An array of argument definitions */ BPArgumentDefinition * arguments; } BPFunctionDefinition; /** The definition of a service */ -typedef struct BPCoreletDefinition_t { +typedef struct BPServiceDefinition_t { /** The name of the service */ - BPString coreletName; + BPString serviceName; /** The major version of the service */ unsigned int majorVersion; /** The minor version of the service */ unsigned int minorVersion; /** The micro version (build number) of the service */ unsigned int microVersion; /** A human readable english documentation string. */ BPString docString; /** The number of functions in the functions array */ unsigned int numFunctions; /** An array of function definitions */ BPFunctionDefinition * functions; -} BPCoreletDefinition; +} BPServiceDefinition; #ifdef __cplusplus }; #endif #endif diff --git a/include/ServiceAPI/bperror.h b/include/ServiceAPI/bperror.h index 8aa0989..2426b42 100644 --- a/include/ServiceAPI/bperror.h +++ b/include/ServiceAPI/bperror.h @@ -1,54 +1,54 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * Portions created by Yahoo! are Copyright (c) 2010 Yahoo! Inc. * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ /** * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * Suggested error code strings to use for common error cases. * by using these you increase the symmetry between your services * and others. */ #ifndef __BPERROR_H__ #define __BPERROR_H__ #ifdef __cplusplus extern "C" { #endif /** Invalid Parameters. BrowserPlus validates the types of top * level parameters, but cannot validate semantic meaning * (a string as enum), nor complex parameters (Maps and Lists) */ #define BPE_INVALID_PARAMETERS "invalidParameters" /** An error code to return when functionality is not yet implemented */ #define BPE_NOT_IMPLEMENTED "notImplemented" /** the service encounterd an internal error which prevented the * completion of the function execution. Be more specific when * possible */ #define BPE_INTERNAL_ERROR "internalError" #ifdef __cplusplus }; #endif #endif diff --git a/include/ServiceAPI/bppfunctions.h b/include/ServiceAPI/bppfunctions.h index 3943077..ae288d2 100644 --- a/include/ServiceAPI/bppfunctions.h +++ b/include/ServiceAPI/bppfunctions.h @@ -1,194 +1,194 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * Portions created by Yahoo! are Copyright (c) 2010 Yahoo! Inc. * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ /** * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * Overview: * * Functions that must be implemented by the service are prefaced with * BPP and are located in this file. */ #ifndef __BPPFUNCTIONS_H__ #define __BPPFUNCTIONS_H__ #include <ServiceAPI/bptypes.h> #include <ServiceAPI/bpdefinition.h> #include <ServiceAPI/bpcfunctions.h> #ifdef __cplusplus extern "C" { #endif /** * Initialize the service, called once at service load time. + * * * \param coreFunctionTable pointer to a structure of pointers to BPC * functions that the service may call through into * BPCore. - * \param parameterMap A map containing initialization parameters for - * the service. These parameters include: - * - * 'CoreletDirectory': The location on disk where the service - * resides. + * \param serviceDir The directory in which the service being initialized + * is installed. + * \param dependentDir In the case of a provider service, the path to the + * dependent service being loaded. + * \param dependentParams In the case of a provider service, arguments from + * the manifest.json of the dependent service. * + * \return A service definition which describes the interface of the + * service. This memory should not be freed until the service + * is shutdown. */ -typedef const BPCoreletDefinition * (*BPPInitializePtr)( +typedef const BPServiceDefinition * (*BPPInitializePtr)( const BPCFunctionTable * coreFunctionTable, - const BPElement * parameterMap); + const BPPath serviceDir, + const BPPath dependentDir, + const BPElement * dependentParams); /** * Shutdown the service. Called once at service unload time. * All allocated instances will have been deleted by the time * this function is called. */ typedef void (*BPPShutdownPtr)(void); /** * Allocate a new service instance. * * \param instance A void pointer that will be passed back to subsequent * calls to invoke and destroy. This is an output parameter * that services may use to store instance-specific * context. - * \param attachID The ID of the attachment this is associated with for - * provider services (set in BPPAttach call), for - * standalone services, always zero and may be ignored. - * \param contextMap A map containing session specific context. - * 'uri' is a string containing a URI of the current client. This is + * \param uri a UTF8 encoded string containing a URI of the current client. This is * usually the full URL to the webpage that is interacting * with browserplus. In the case of a native local application * interacting with browserplus it should be a URI with a * method of 'bpclient' (i.e. bpclient://CLIENTIDENTIFIER'). - * 'corelet_dir' DEPRECATED, use service_dir instead. - * 'service_dir' is an absolute path to the directory containing the - * files distributed with the service. - * 'data_dir' is a absolute path to where the service should store - * any data that needs to persist. - * 'temp_dir' is a directory that may be used for temporary - * data. it will be unique for every instance, and will - * be purged when the instance is deallocated. - * 'locale' The locale of the end user to which strings, if any, - * should be localized. - * 'userAgent' The client user-agent string. - * 'clientPid' The process ID of the client. + * \param serviceDir is an absolute path to the directory containing the + * files distributed with the service. + * \param dataDir is an absolute path to where the service should store + * any data that needs to persist. + * \param tempDir is an instance-specific directory that may be used for + * temporary data. Service is responsible for + * creating the directory. Service should remove the + * directory when the instance is deallocated. + * \param locale The locale of the end user to which strings, if any, + * should be localized. + * \param userAgent The client user-agent as a UTF8 encoded string. + * \param clientPid The process ID of the client program/browser. * * \return zero on success, non-zero on failure */ -typedef int (*BPPAllocatePtr)(void ** instance, unsigned int attachID, - const BPElement * contextMap); +typedef int (*BPPAllocatePtr)( + void ** instance, const BPString uri, const BPPath serviceDir, + const BPPath dataDir, const BPPath tempDir, const BPString locale, + const BPString userAgent, int clientPid); /** * Destroy a service instance allocated with BPPAllocate. * * \param instance An instance pointer returned from a BPPAllocate call. */ typedef void (*BPPDestroyPtr)(void * instance); /** * Invoke a service method. * - * \param instance An instance pointer returned from a BPPAllocate call. + * \param instance The instance pointer returned from a BPPAllocate call. * \param functionName The name of the function being invoked * \param tid The transaction id of this function invocation. Should * be passed by the service to BPCPostResultsFuncPtr * or BPCPostErrorFuncPtr * \param arguments The validated arguments to the function. The service * is guaranteed that all defined arguments to the function * from the function description structure have been * checked, and that no unsupported arguments are present, * nor are required arguments missing. This is always a * BPTMap. */ typedef void (*BPPInvokePtr)(void * instance, const char * functionName, unsigned int tid, const BPElement * arguments); /** - * The "attach" function supports interpreter services. These are services - * which can be used by other services. The primary types of services - * that will be interested in this functionality are high level language - * interpretation services which allow the authoring of services in - * non-compiled languages. - * - * For most services Attach and Detach may be NULL which indicates that the - * service may not be "used" by other services. - * - * Attach is called after BPPInitialize at the time the dependant service - * is itself initialize. Multiple dependant services may use the same - * provider service, and the provider service may also expose functions - * directly. Multiple attached dependant services may be disambiguated - * using the "attachID". At the time an instance of a attached service - * is instantiated, the attachID is passed in. - * - * The parameters map contains a set of parameters which describe the - * dependant service. These parameters are both set by BrowserPlus, and - * extracted from the manifest of the dependant service. + * Cancel a transaction previously started by calling BPPInvokePtr() * - * The returned service definition describes the interface of the - * dependent service. This will likely be dynamically allocated - * memory, which should not be freed until detach is called + * \param instance The instance pointer returned from a BPPAllocate call. + * \param tid The transaction id of this function invocation. + */ +typedef void (*BPPCancelPtr)(void * instance, unsigned int tid); + +/** + * A callback invoked exactly once immediately after a service is installed + * on disk. This is an opportunity for a service to perform any one-time setup. * - * \warning this is an exception to the ServiceAPI's memory contract, - * and will be fixed in a later version of the ServiceAPI + * \param serviceDir is an absolute path to the directory containing the + * files distributed with the service. + * \param dataDir is an absolute path to where the service should store + * any data that needs to persist. */ -typedef const BPCoreletDefinition * (*BPPAttachPtr)( - unsigned int attachID, const BPElement * parameterMap); +typedef int (*BPPInstallPtr)(const BPPath serviceDir, const BPPath dataDir); /** - * At the time the last instance of a dependant service is deleted, detach - * is called. + * A callback invoked exactly once immediately before a service is purged from + * disk. This is an opportunity for a service to perform any one-time cleanup. + * + * \param serviceDir is an absolute path to the directory containing the + * files distributed with the service. + * \param dataDir is an absolute path to where the service should store + * any data that needs to persist. */ -typedef void (*BPPDetachPtr)(unsigned int attachID); +typedef int (*BPPUninstallPtr)(const BPPath serviceDir, const BPPath dataDir); + -#define BPP_CORELET_API_VERSION 4 +#define BPP_SERVICE_API_VERSION 5 typedef struct BPPFunctionTable_t { - /** The version of the service API to which this service plugin is - * written (use the BPP_CORELET_API_VERSION macro!) */ - unsigned int coreletAPIVersion; + /** The version of the service API to which this service is + * written (use the BPP_SERVICE_API_VERSION macro!) */ + unsigned int serviceAPIVersion; BPPInitializePtr initializeFunc; BPPShutdownPtr shutdownFunc; BPPAllocatePtr allocateFunc; BPPDestroyPtr destroyFunc; BPPInvokePtr invokeFunc; - BPPAttachPtr attachFunc; - BPPDetachPtr detachFunc; + BPPCancelPtr cancelFunc; + BPPInstallPtr installFunc; + BPPUninstallPtr uninstallFunc; } BPPFunctionTable; /** * The single entry point into the plugin which attains a * BPPFunctionTable containing the version. Having a single symbol * which is sought in the plugin interface allows the service author to * strip all other symbols. */ #ifdef WIN32 __declspec(dllexport) #endif const BPPFunctionTable * BPPGetEntryPoints(void); #ifdef __cplusplus }; #endif #endif diff --git a/include/ServiceAPI/bptypes.h b/include/ServiceAPI/bptypes.h index d57342b..c6d32cb 100644 --- a/include/ServiceAPI/bptypes.h +++ b/include/ServiceAPI/bptypes.h @@ -1,126 +1,129 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * Portions created by Yahoo! are Copyright (c) 2010 Yahoo! Inc. * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ /* * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * Types. These basic types are how arguments are passed to services, * and how responses are returned from services. The representation * allows introspection which allows data to be serialized or bound to * native types in different target execution environments. */ #ifndef __BPTYPES_H__ #define __BPTYPES_H__ #ifdef __cplusplus extern "C" { #endif /** * The available types that may be passed across the BrowserPlus <-> Service * boundary. */ typedef enum { BPTNull, /*!< Null type */ BPTBoolean, /*!< Boolean type */ BPTInteger, /*!< integer type */ BPTDouble, /*!< floating point type */ BPTString, /*!< string type, all strings are represented in UTF8 */ BPTMap, /*!< map (hash) type. */ BPTList, /*!< list (array) type. */ BPTCallBack,/*!< callback type. */ - BPTPath, /*!< pathname type - represented as a string however - paths are sensitive and are handled differently - than strings */ + BPTNativePath, /*!< pathname type - represented as a native path: UTF8 + on unix and UTF16 on windows. */ BPTAny /*!< When specified in an argument description, denotes that any data type is allowable. */ } BPType; /* definition of basic types */ /** booleans are represented as integers */ typedef int BPBool; /** BPBool true value */ #define BP_TRUE 1 /** BPBool false value */ #define BP_FALSE 0 /** strings are UTF8 */ typedef char * BPString; /** integers are 64 bit signed entities */ typedef long long int BPInteger; /** floating point values are double precision */ typedef double BPDouble; /** the callback is an integer handle */ typedef BPInteger BPCallBack; /** A structure representing of a list */ typedef struct { /** The number of elements in the list */ unsigned int size; /** an array of pointers to child elements */ struct BPElement_t ** elements; } BPList; /** a structure representing a map */ typedef struct { /** The number of elements in the list */ unsigned int size; /** An array of BPMapElem structures containing keys and values */ struct BPMapElem_t * elements; } BPMap; /** pathnames are UTF8 */ -typedef char * BPPath; +#if defined(WIN32) || defined(WINDOWS) || defined(_WINDOWS) + typedef wchar_t * BPPath; +#else + typedef char * BPPath; +#endif /** The uber structure capable of representing any element */ typedef struct BPElement_t { /** The type of element that this structure contains. This type * determine which union value is valid */ BPType type; /** The value of the element */ union { BPBool booleanVal; BPString stringVal; BPInteger integerVal; BPDouble doubleVal; BPMap mapVal; BPList listVal; BPCallBack callbackVal; BPPath pathVal; } value; } BPElement; /** A BPMapElem contains a pointer to a UTF8 string, and a pointer to * a BPElement structure containing the value */ typedef struct BPMapElem_t { BPString key; BPElement * value; } BPMapElem; #ifdef __cplusplus }; #endif #endif
browserplus/bp-service-api
867130a7452508417569cdca9fee99ef45a99453
check in serviceapi headers from 2.7.1
diff --git a/include/ServiceAPI/bpcfunctions.h b/include/ServiceAPI/bpcfunctions.h index 8ecc88d..492835b 100644 --- a/include/ServiceAPI/bpcfunctions.h +++ b/include/ServiceAPI/bpcfunctions.h @@ -1,158 +1,159 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (C) 2006-2009 Yahoo!. - * All Rights Reserved. + * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ + /** * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * BPC* functions are provided by BPCore and called by the corelet */ #ifndef __BPCFUNCTIONS_H__ #define __BPCFUNCTIONS_H__ #include <ServiceAPI/bptypes.h> #include <ServiceAPI/bpdefinition.h> #ifdef __cplusplus extern "C" { #endif /** * Post results from a called BPPFunctionPtr. * Subsequent to this call, no callbacks passed as parameters to the * service function may be called. This indicates the completion of the * function invocation or transaction. * * \param tid a transaction id passed into the service via the invocation * of a BPPFunctionPtr * \param results The results of the function invocation. */ typedef void (*BPCPostResultsFuncPtr)(unsigned int tid, const BPElement * results); /** * Post an asynchronous error from a called BPPFunctionPtr. * Subsequent to this call, no callbacks passed as parameters to the * service function may be called. This indicates the completion of the * function invocation or transaction. * * \param tid a transaction id passed into the corelet via the invocation * of a BPPFunctionPtr * \param error A string representation of an error. If NULL, a generic * error will be raised. These strings should be camel * cased english phrases. The service name will be prepended * to the error, and it will be propogated up to the * caller. * \param verboseError An optional english string describing more verbosely * exactly what went wrong. This is intended for * developers. */ typedef void (*BPCPostErrorFuncPtr)(unsigned int tid, const char * error, const char * verboseError); /** * Invoke a callback that was passed into a service function as a * parameter. * * \param tid a transaction id passed into the service via the invocation * of a BPPFunctionPtr * \param callbackHandle A callback handle attained from the original * function invocation. * \param params - the argument to the callback. */ typedef void (*BPCInvokeCallBackFuncPtr)(unsigned int tid, BPCallBack callbackHandle, const BPElement * params); /** log level argument to BPCLogFuncPtr, debug message*/ #define BP_DEBUG 1 /** log level argument to BPCLogFuncPtr, informational message*/ #define BP_INFO 2 /** log level argument to BPCLogFuncPtr, warning message*/ #define BP_WARN 3 /** log level argument to BPCLogFuncPtr, error message*/ #define BP_ERROR 4 /** log level argument to BPCLogFuncPtr, fatal message*/ #define BP_FATAL 5 /** * Output a log a message. * \param level the severity of the log message * \param fmt a printf() style format string * \param varags arguments to the printf() style format string */ typedef void (*BPCLogFuncPtr)(unsigned int level, const char * fmt, ...); /** * The signature of a function capable of recieving a response to a * promptUser request. * * \param context the same void * pointer passed to the BPCPromptUserFuncPtr * \param promptId the same unsigned int returned from BPCPromptUserFuncPtr * \param response the user's response, a data structure mapped from * javascript. */ typedef void (*BPUserResponseCallbackFuncPtr)( void * context, unsigned int promptId, const BPElement * response); /** * Prompt the end user. end user prompting must be associated with * a specific transaction/method invocation. * * \param tid a transaction id passed into the service via the invocation * of a BPPFunctionPtr * \param utf8PathToHTMLDialog A utf8 string holding the absolute path * to the dialog you wish to display. * \param arguments The arguments to make available to the dialog * via the BPDialog.args() call * \param responseCallback A Function pointer to invoke when the response * to the user prompt is available. * \param context a pointer to pass to the responseCallback * * \returns A unsigned prompt ID that wil be passed to the * responseCallback */ typedef unsigned int (*BPCPromptUserFuncPtr)( unsigned int tid, const char * utf8PathToHTMLDialog, const BPElement * arguments, BPUserResponseCallbackFuncPtr responseCallback, void * context); /** * A table containing function pointers for functions available to be * called by services implemented by BrowserPlus. */ typedef struct { BPCPostResultsFuncPtr postResults; BPCPostErrorFuncPtr postError; BPCLogFuncPtr log; BPCInvokeCallBackFuncPtr invoke; BPCPromptUserFuncPtr prompt; } BPCFunctionTable; #ifdef __cplusplus }; #endif #endif diff --git a/include/ServiceAPI/bpdefinition.h b/include/ServiceAPI/bpdefinition.h index c5e16a5..6650c92 100644 --- a/include/ServiceAPI/bpdefinition.h +++ b/include/ServiceAPI/bpdefinition.h @@ -1,87 +1,88 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (C) 2006-2009 Yahoo!. - * All Rights Reserved. + * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ + /** * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * A service is defined by a set if in-memory structures. These * structures are hierarchical and can define a service containing * any number of functions, which themselves accept any number of * arguments. */ #ifndef __BPDEFINITION_H__ #define __BPDEFINITION_H__ #include <ServiceAPI/bptypes.h> #include <ServiceAPI/bperror.h> #ifdef __cplusplus extern "C" { #endif /** The definition of an argument */ typedef struct { /** The name of the agument, all arguments in BrowserPlus are named */ BPString name; /** A human readable english documentation string */ BPString docString; /** The expected type of the argument */ BPType type; /** whether the argument is required or not */ BPBool required; } BPArgumentDefinition; /** The definition of a function */ typedef struct { /** the name of the function */ BPString functionName; /** A human readable english documentation string. */ BPString docString; /** The number of arguements in the arguments array */ unsigned int numArguments; /** An array of argument definitions */ BPArgumentDefinition * arguments; } BPFunctionDefinition; /** The definition of a service */ typedef struct BPCoreletDefinition_t { /** The name of the service */ BPString coreletName; /** The major version of the service */ unsigned int majorVersion; /** The minor version of the service */ unsigned int minorVersion; /** The micro version (build number) of the service */ unsigned int microVersion; /** A human readable english documentation string. */ BPString docString; /** The number of functions in the functions array */ unsigned int numFunctions; /** An array of function definitions */ BPFunctionDefinition * functions; } BPCoreletDefinition; #ifdef __cplusplus }; #endif #endif diff --git a/include/ServiceAPI/bperror.h b/include/ServiceAPI/bperror.h index 32c46be..8aa0989 100644 --- a/include/ServiceAPI/bperror.h +++ b/include/ServiceAPI/bperror.h @@ -1,53 +1,54 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (C) 2006-2009 Yahoo!. - * All Rights Reserved. + * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ + /** * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * Suggested error code strings to use for common error cases. * by using these you increase the symmetry between your services * and others. */ #ifndef __BPERROR_H__ #define __BPERROR_H__ #ifdef __cplusplus extern "C" { #endif /** Invalid Parameters. BrowserPlus validates the types of top * level parameters, but cannot validate semantic meaning * (a string as enum), nor complex parameters (Maps and Lists) */ #define BPE_INVALID_PARAMETERS "invalidParameters" /** An error code to return when functionality is not yet implemented */ #define BPE_NOT_IMPLEMENTED "notImplemented" /** the service encounterd an internal error which prevented the * completion of the function execution. Be more specific when * possible */ #define BPE_INTERNAL_ERROR "internalError" #ifdef __cplusplus }; #endif #endif diff --git a/include/ServiceAPI/bppfunctions.h b/include/ServiceAPI/bppfunctions.h index ad76f0e..3943077 100644 --- a/include/ServiceAPI/bppfunctions.h +++ b/include/ServiceAPI/bppfunctions.h @@ -1,186 +1,194 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (C) 2006-2009 Yahoo!. - * All Rights Reserved. + * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ + /** * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * Overview: * * Functions that must be implemented by the service are prefaced with * BPP and are located in this file. */ #ifndef __BPPFUNCTIONS_H__ #define __BPPFUNCTIONS_H__ #include <ServiceAPI/bptypes.h> #include <ServiceAPI/bpdefinition.h> #include <ServiceAPI/bpcfunctions.h> #ifdef __cplusplus extern "C" { #endif /** * Initialize the service, called once at service load time. - * the pointer passed in points to a structure of points to BPC - * functions that the service may call through into BPCore. + * + * \param coreFunctionTable pointer to a structure of pointers to BPC + * functions that the service may call through into + * BPCore. + * \param parameterMap A map containing initialization parameters for + * the service. These parameters include: + * + * 'CoreletDirectory': The location on disk where the service + * resides. + * */ typedef const BPCoreletDefinition * (*BPPInitializePtr)( const BPCFunctionTable * coreFunctionTable, const BPElement * parameterMap); /** - * shut down the service. Called once at service unload time, - * all allocated instances will have been deleted by the time - * this function is called. + * Shutdown the service. Called once at service unload time. + * All allocated instances will have been deleted by the time + * this function is called. */ typedef void (*BPPShutdownPtr)(void); /** * Allocate a new service instance. * * \param instance A void pointer that will be passed back to subsequent - * calls into this instance. This is an output parameter - * that services may use to store instance specific + * calls to invoke and destroy. This is an output parameter + * that services may use to store instance-specific * context. * \param attachID The ID of the attachment this is associated with for * provider services (set in BPPAttach call), for * standalone services, always zero and may be ignored. * \param contextMap A map containing session specific context. * 'uri' is a string containing a URI of the current client. This is * usually the full URL to the webpage that is interacting * with browserplus. In the case of a native local application * interacting with browserplus it should be a URI with a * method of 'bpclient' (i.e. bpclient://CLIENTIDENTIFIER'). * 'corelet_dir' DEPRECATED, use service_dir instead. * 'service_dir' is an absolute path to the directory containing the * files distributed with the service. * 'data_dir' is a absolute path to where the service should store * any data that needs to persist. * 'temp_dir' is a directory that may be used for temporary * data. it will be unique for every instance, and will * be purged when the instance is deallocated. * 'locale' The locale of the end user to which strings, if any, * should be localized. * 'userAgent' The client user-agent string. * 'clientPid' The process ID of the client. * * \return zero on success, non-zero on failure */ typedef int (*BPPAllocatePtr)(void ** instance, unsigned int attachID, const BPElement * contextMap); /** * Destroy a service instance allocated with BPPAllocate. + * + * \param instance An instance pointer returned from a BPPAllocate call. */ typedef void (*BPPDestroyPtr)(void * instance); /** - * All callable functions exposed by the service are invoked by BrowserPlus - * by calling the invoke function and passing as a parameter the name of the - * function being invoked. + * Invoke a service method. * - * \param instance The same instance pointer that the service - * returned in the BPPAllocate call. + * \param instance An instance pointer returned from a BPPAllocate call. * \param functionName The name of the function being invoked * \param tid The transaction id of this function invocation. Should * be passed by the service to BPCPostResultsFuncPtr * or BPCPostErrorFuncPtr * \param arguments The validated arguments to the function. The service * is guaranteed that all defined arguments to the function * from the function description structure have been * checked, and that no unsupported arguments are present, * nor are required arguments missing. This is always a * BPTMap. */ typedef void (*BPPInvokePtr)(void * instance, const char * functionName, unsigned int tid, const BPElement * arguments); /** * The "attach" function supports interpreter services. These are services * which can be used by other services. The primary types of services * that will be interested in this functionality are high level language * interpretation services which allow the authoring of services in * non-compiled languages. * * For most services Attach and Detach may be NULL which indicates that the * service may not be "used" by other services. * * Attach is called after BPPInitialize at the time the dependant service * is itself initialize. Multiple dependant services may use the same * provider service, and the provider service may also expose functions * directly. Multiple attached dependant services may be disambiguated * using the "attachID". At the time an instance of a attached service * is instantiated, the attachID is passed in. * * The parameters map contains a set of parameters which describe the * dependant service. These parameters are both set by BrowserPlus, and * extracted from the manifest of the dependant service. * * The returned service definition describes the interface of the * dependent service. This will likely be dynamically allocated * memory, which should not be freed until detach is called * * \warning this is an exception to the ServiceAPI's memory contract, * and will be fixed in a later version of the ServiceAPI */ typedef const BPCoreletDefinition * (*BPPAttachPtr)( unsigned int attachID, const BPElement * parameterMap); /** * At the time the last instance of a dependant service is deleted, detach * is called. */ typedef void (*BPPDetachPtr)(unsigned int attachID); #define BPP_CORELET_API_VERSION 4 typedef struct BPPFunctionTable_t { /** The version of the service API to which this service plugin is * written (use the BPP_CORELET_API_VERSION macro!) */ unsigned int coreletAPIVersion; BPPInitializePtr initializeFunc; BPPShutdownPtr shutdownFunc; BPPAllocatePtr allocateFunc; BPPDestroyPtr destroyFunc; BPPInvokePtr invokeFunc; BPPAttachPtr attachFunc; BPPDetachPtr detachFunc; } BPPFunctionTable; /** * The single entry point into the plugin which attains a * BPPFunctionTable containing the version. Having a single symbol * which is sought in the plugin interface allows the service author to * strip all other symbols. */ #ifdef WIN32 __declspec(dllexport) #endif const BPPFunctionTable * BPPGetEntryPoints(void); #ifdef __cplusplus }; #endif #endif diff --git a/include/ServiceAPI/bptypes.h b/include/ServiceAPI/bptypes.h index 1be1f22..d57342b 100644 --- a/include/ServiceAPI/bptypes.h +++ b/include/ServiceAPI/bptypes.h @@ -1,125 +1,126 @@ /** * ***** BEGIN LICENSE BLOCK ***** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is BrowserPlus (tm). * * The Initial Developer of the Original Code is Yahoo!. - * Portions created by Yahoo! are Copyright (C) 2006-2009 Yahoo!. - * All Rights Reserved. + * Portions created by Yahoo! are Copyright (c) 2009 Yahoo! Inc. + * All rights reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** */ + /* * Written by Lloyd Hilaiel, on or around Fri May 18 17:06:54 MDT 2007 * * Types. These basic types are how arguments are passed to services, * and how responses are returned from services. The representation * allows introspection which allows data to be serialized or bound to * native types in different target execution environments. */ #ifndef __BPTYPES_H__ #define __BPTYPES_H__ #ifdef __cplusplus extern "C" { #endif /** * The available types that may be passed across the BrowserPlus <-> Service * boundary. */ typedef enum { BPTNull, /*!< Null type */ BPTBoolean, /*!< Boolean type */ BPTInteger, /*!< integer type */ BPTDouble, /*!< floating point type */ BPTString, /*!< string type, all strings are represented in UTF8 */ BPTMap, /*!< map (hash) type. */ BPTList, /*!< list (array) type. */ BPTCallBack,/*!< callback type. */ BPTPath, /*!< pathname type - represented as a string however paths are sensitive and are handled differently than strings */ BPTAny /*!< When specified in an argument description, denotes that any data type is allowable. */ } BPType; /* definition of basic types */ /** booleans are represented as integers */ typedef int BPBool; /** BPBool true value */ #define BP_TRUE 1 /** BPBool false value */ #define BP_FALSE 0 /** strings are UTF8 */ typedef char * BPString; /** integers are 64 bit signed entities */ typedef long long int BPInteger; /** floating point values are double precision */ typedef double BPDouble; /** the callback is an integer handle */ typedef BPInteger BPCallBack; /** A structure representing of a list */ typedef struct { /** The number of elements in the list */ unsigned int size; /** an array of pointers to child elements */ struct BPElement_t ** elements; } BPList; /** a structure representing a map */ typedef struct { /** The number of elements in the list */ unsigned int size; /** An array of BPMapElem structures containing keys and values */ struct BPMapElem_t * elements; } BPMap; /** pathnames are UTF8 */ typedef char * BPPath; /** The uber structure capable of representing any element */ typedef struct BPElement_t { /** The type of element that this structure contains. This type * determine which union value is valid */ BPType type; /** The value of the element */ union { BPBool booleanVal; BPString stringVal; BPInteger integerVal; BPDouble doubleVal; BPMap mapVal; BPList listVal; BPCallBack callbackVal; BPPath pathVal; } value; } BPElement; /** A BPMapElem contains a pointer to a UTF8 string, and a pointer to * a BPElement structure containing the value */ typedef struct BPMapElem_t { BPString key; BPElement * value; } BPMapElem; #ifdef __cplusplus }; #endif #endif
browserplus/bp-service-api
bc7ed8eecd4c0f78eeec903a651f4c6cf0381461
put something to read in the README
diff --git a/README b/README index 8b13789..8040413 100644 --- a/README +++ b/README @@ -1 +1,4 @@ +This README is a mirror of the most recent headers and documentation from +the BrowserPlus SDK: +http://browserplus.yahoo.com/developer/service/sdk/
tobinharris/golem
e08259048edcae2512e00aafc4359bcacc33707b
We now have a NAnt recipes solution, and working proof of concept for simple NAnt tasks
diff --git a/Golem.Core/TaskRunner.cs b/Golem.Core/TaskRunner.cs index ebe93e9..86f7ef2 100644 --- a/Golem.Core/TaskRunner.cs +++ b/Golem.Core/TaskRunner.cs @@ -1,130 +1,134 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Linq; namespace Golem.Core { public class RecipeBase { public IList<Assembly> AllAssemblies = new List<Assembly>(); public IList<Recipe> AllRecipes = new List<Recipe>(); } public class TaskRunner { private RecipeCataloger cataloger; public TaskRunner(RecipeCataloger aCataloger) { cataloger = aCataloger; } - public void Run(Recipe recipe, Task task) + + public void Run(Recipe recipe, Task task, params object[] parameters ) { - //TODO: Tasks should run in their own appdomain. + //TODO: Tasks should run in their own appdomain? // We need to create an app domain that has the // base dir the same as the target assembly var recipeInstance = Activator.CreateInstance(recipe.Class); SetContextualInformationIfInheritsRecipeBase(recipeInstance); - task.Method.Invoke(recipeInstance, null); + task.Method.Invoke(recipeInstance, parameters); } private void SetContextualInformationIfInheritsRecipeBase(object recipeInstance) { var tmpRecipe = recipeInstance as RecipeBase; if(tmpRecipe == null) return; tmpRecipe.AllAssemblies = cataloger.AssembliesExamined; tmpRecipe.AllRecipes = cataloger.Recipes; } + + //TODO: Run is Too long //TODO: Nesting depth is too deep - public void Run(string recipeName, string taskName) + public void Run(string recipeName, string taskName, params object[] para) { + if(cataloger.Recipes.Count==0) cataloger.CatalogueRecipes(); foreach (var r in cataloger.Recipes) { if(r.Name.ToLower() == recipeName.ToLower()) { foreach(var t in r.Tasks) { if(t.Name.ToLower() == taskName.ToLower()) { foreach(var methodInfo in t.DependsOnMethods) { - Run(r, r.GetTaskForMethod(methodInfo)); + Run(r, r.GetTaskForMethod(methodInfo), para); } - Run(r, t); + Run(r, t, para); return; } } } } } // public RunManifest BuildRunManifest(string recipeName, string taskName) // { // var manifest = new RunManifest(); // var cataloger = new RecipeCataloger(); // var found = cataloger.CatalogueRecipes(); // // foreach (var r in found) // { // if (r.Name.ToLower() == recipeName.ToLower()) // { // foreach (var t in r.Tasks) // { // if (t.Name.ToLower() == taskName.ToLower()) // { // foreach(var d in t.DependsOnMethods) // { // manifest.Add(null); // } // manifest.Add(t); // // } // } // } // } // return manifest; // } } public class RunManifest { public OrderedDictionary ToRun; public void Add(Task t) { if(! ToRun.Contains(t)) { ToRun.Add(t,new RunManifestItem{Task=t}); } } public RunManifest() { ToRun = new OrderedDictionary(); } public Task TaskAt(int position) { return (Task) ToRun[position]; } } public class RunManifestItem { public Task Task; public bool HasRun; } } \ No newline at end of file diff --git a/Golem.Recipes.NAnt/GRegexTask.cs b/Golem.Recipes.NAnt/GRegexTask.cs new file mode 100644 index 0000000..66d1cc1 --- /dev/null +++ b/Golem.Recipes.NAnt/GRegexTask.cs @@ -0,0 +1,23 @@ +using System; +using NAnt.Core; +using NAnt.Core.Tasks; + +namespace Golem.Recipes.Nant +{ + public class GRegexTask : RegexTask + { + private PropertyDictionary _dict = new PropertyDictionary(null); + public override void Log(Level messageLevel, string message) + { + if (messageLevel == Level.Error) + Console.WriteLine("NANT:" + message); + } + public override PropertyDictionary Properties + { + get + { + return _dict; + } + } + } +} \ No newline at end of file diff --git a/Golem.Recipes.NAnt/GXmlPeekTask.cs b/Golem.Recipes.NAnt/GXmlPeekTask.cs new file mode 100644 index 0000000..d8e115c --- /dev/null +++ b/Golem.Recipes.NAnt/GXmlPeekTask.cs @@ -0,0 +1,23 @@ +using System; +using NAnt.Core; +using NAnt.Core.Tasks; + +namespace Golem.Recipes.Nant +{ + public class GXmlPeekTask : XmlPeekTask + { + private PropertyDictionary _dict = new PropertyDictionary(null); + public override void Log(Level messageLevel, string message) + { + if(messageLevel == Level.Error) + Console.WriteLine("NANT:" + message); + } + public override PropertyDictionary Properties + { + get + { + return _dict; + } + } + } +} \ No newline at end of file diff --git a/Golem.Recipes.NAnt/Golem.Recipes.Nant.csproj b/Golem.Recipes.NAnt/Golem.Recipes.Nant.csproj new file mode 100644 index 0000000..004c85d --- /dev/null +++ b/Golem.Recipes.NAnt/Golem.Recipes.Nant.csproj @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.21022</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{114B7DE4-297E-4FBC-9E0D-FCF07372464A}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>Golem.Recipes.Nant</RootNamespace> + <AssemblyName>Golem.Recipes.Nant</AssemblyName> + <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="NAnt.Core, Version=0.85.2478.0, Culture=neutral, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\nant-0.85\bootstrap\NAnt.Core.dll</HintPath> + </Reference> + <Reference Include="NAnt.DotNetTasks, Version=0.85.2478.0, Culture=neutral, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\nant-0.85\bootstrap\NAnt.DotNetTasks.dll</HintPath> + </Reference> + <Reference Include="System" /> + <Reference Include="System.Core"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Xml.Linq"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data.DataSetExtensions"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="GRegexTask.cs" /> + <Compile Include="GXmlPeekTask.cs" /> + <Compile Include="NantRecipe.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\Golem.Core\Golem.Core.csproj"> + <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> + <Name>Golem.Core</Name> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/Golem.Recipes.NAnt/NantRecipe.cs b/Golem.Recipes.NAnt/NantRecipe.cs new file mode 100644 index 0000000..41c1063 --- /dev/null +++ b/Golem.Recipes.NAnt/NantRecipe.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Xml; +using Golem.Core; +using NAnt.Core.Tasks; + +namespace Golem.Recipes.Nant +{ + /// <summary> + /// TODO: NAntRecipe is pretty pretty ugly, but proof of concept at least! + /// </summary> + [Recipe] + public class NantRecipe + { + [Task(Description="Peek at a property in an XML file.")] + public void XmlPeek(string file, string xpath, string property) + { + var task = new GXmlPeekTask(); + task.InitializeTaskConfiguration(); + task.XmlFile = new FileInfo(file); + task.XPath = xpath; + task.Property = property; + + var m = typeof(XmlPeekTask).GetMethod("ExecuteTask", BindingFlags.NonPublic|BindingFlags.Instance); + if(m==null)throw new Exception("Doh!"); + m.Invoke(task, null); + + foreach (DictionaryEntry p in task.Properties) + { + Console.WriteLine("{0}={1}", p.Key, p.Value); + } + + } + [Task(Description="Runs a regular expression match.")] + public void Regex(string input, string pattern) + { + var task = new GRegexTask(); + task.InitializeTaskConfiguration(); + task.Input = input; + task.Pattern = pattern; + var m = typeof(RegexTask).GetMethod("ExecuteTask", BindingFlags.NonPublic | BindingFlags.Instance); + if (m == null) throw new Exception("Doh!"); + m.Invoke(task, null); + Console.WriteLine("Found {0} matches:", task.Properties.Count); + foreach(DictionaryEntry p in task.Properties) + { + Console.WriteLine("{0}={1}",p.Key, p.Value); + } + } + } +} \ No newline at end of file diff --git a/Golem.Recipes.NAnt/Properties/AssemblyInfo.cs b/Golem.Recipes.NAnt/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..976c444 --- /dev/null +++ b/Golem.Recipes.NAnt/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Golem.Recipes")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Golem.Recipes")] +[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e16bf2fd-8447-4307-b46f-7089bc570c3b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Golem.Runner/Program.cs b/Golem.Runner/Program.cs index 0aca69e..6182e38 100644 --- a/Golem.Runner/Program.cs +++ b/Golem.Runner/Program.cs @@ -1,97 +1,106 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Golem.Core; using Golem.Core; namespace Golem.Runner { public class Program { public static void Main(string[] args) { Console.WriteLine("Golem (Beta) 2008\nYour friendly executable .NET build tool. \n"); IList<Recipe> found; RecipeCataloger finder = CreateCataloger(out found); if(args.Length > 0) { if(args[0] == "-T") { ShowList(found); return; } else if(args[0].ToLower() == "-?") { Console.WriteLine("Help: \n"); Console.WriteLine("golem -T # List build tasks"); Console.WriteLine("golem -? # Show this help"); Console.WriteLine("golem -? # Show this help"); return; } var parts = args[0].Split(':'); var runner = new TaskRunner(finder); - if(parts.Length == 2) + if(parts.Length == 2 && args.Length == 1) + { runner.Run(parts[0],parts[1]); + } + else if(parts.Length ==2 && args.Length > 1) + { + //TODO: Tidy this up and refactor + var dest = new string[args.Length-1]; + Array.Copy(args,1,dest,0,args.Length-1); + runner.Run(parts[0],parts[1],dest); + } else { Console.WriteLine("Type golem -? for help, or try one of the following tasks:\n"); ShowList(found); } } else { ShowList(found); } } private static RecipeCataloger CreateCataloger(out IList<Recipe> found) { RecipeCataloger finder; var config = new Configuration(); //TODO: Remove false when ready. Caching location of recipes isn't going to be useful until we can dynamically load dependant assemblies on the fly if (false && config.SearchPaths.Count > 0) finder = new RecipeCataloger(config.SearchPaths.ToArray()); else { Console.WriteLine("Scanning directories for Build Recipes (could take a while)..."); finder = new RecipeCataloger(Environment.CurrentDirectory); } found = finder.CatalogueRecipes(); if(config.SearchPaths.Count == 0) { config.SearchPaths.AddRange(finder.LoadedAssemblies.Select(s=>s.File.FullName)); config.Save(); } return finder; } private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { //Console.WriteLine("\n{0}\n",!String.IsNullOrEmpty(recipe.Description) ? recipe.Description : recipe.Name); foreach(var task in recipe.Tasks) { var start = "golem " + recipe.Name + ":" + task.Name; Console.WriteLine(start.PadRight(30) +"# " + task.Description); } } if (found.Count == 0) Console.WriteLine("No recipes found under {0}", new DirectoryInfo(Environment.CurrentDirectory).Name); } } } diff --git a/Golem.Test/DemoRecipe.cs b/Golem.Test/DemoRecipe.cs index 508b50c..71ee609 100644 --- a/Golem.Test/DemoRecipe.cs +++ b/Golem.Test/DemoRecipe.cs @@ -1,121 +1,131 @@ using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Golem.Core; using Golem.Core; namespace Golem.Test { [Recipe(Name="demo2")] public class Demo2Recipe { [Task(Name = "one", After = new[] { "Three", "Two" })] public void One() { Console.WriteLine("One!"); } [Task(Name = "two")] public void Two() { Console.WriteLine("Two!"); } [Task(Name = "three")] public void Three() { Console.WriteLine("Three!"); } } [Recipe(Name = "demo")] public class DemoRecipe { [Task(Name = "run")] public void Default() { AppDomain.CurrentDomain.SetData("TEST", "TEST"); } [Task(Name="list", Description = "List all NUnit tests in solution")] public void List() { AppDomain.CurrentDomain.SetData("TEST", "LIST"); } [Task(Name="stats", Description="Lists line counts for all types of files")] public void Stats() { string rootDir = Locations.StartDirs[0]; Console.WriteLine(rootDir); var count = new Dictionary<string, long>() { { "lines", 0 }, { "classes", 0 }, { "files", 0 }, { "enums", 0 }, { "methods", 0 }, { "comments", 0 } }; GetLineCount(rootDir, "*.cs", count); Console.WriteLine("c# Files:\t\t{0}", count["files"]); Console.WriteLine("c# Classes: \t{0}", count["classes"]); Console.WriteLine("c# Methods: \t{0}", count["methods"]); Console.WriteLine("c# Lines:\t\t{0}", count["lines"]); Console.WriteLine("c# Comment Lines:\t\t{0}", count["comments"]); Console.WriteLine("Avg Methods Per Class:\t\t{0}", count["methods"]/count["classes"]); } private static void GetLineCount(string rootDir, string fileFilter, Dictionary<string,long> counts) { var files = Directory.GetFiles(rootDir, fileFilter, SearchOption.AllDirectories); long lineCount = 0; foreach(var file in files) { using(var r = File.OpenText(file)) { counts["files"] += 1; var line = r.ReadLine(); while(line != null) { if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+class.+").Length > 0) counts["classes"] += 1; if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+enum.+").Length > 0) counts["enums"] += 1; if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+\\(.*\\).+").Length > 0) counts["methods"] += 1; if (fileFilter == "*.cs" && Regex.Match(line, ".+//.+").Length > 0) counts["comments"] += 1; counts["lines"] += 1; line = r.ReadLine(); } } } } } [Recipe] public class Demo3Recipe { [Task] public void Hello() { Console.WriteLine("Hello"); } } [Recipe] public class Demo4Recipe : RecipeBase { [Task] public void Hello() { Console.WriteLine(this.AllAssemblies.Count); Console.WriteLine(this.AllRecipes.Count); } } + + [Recipe] + public class Demo5Recipe + { + [Task] + public void Foo(string a, string b) + { + Console.WriteLine("{0},{1}", a, b); + } + } } \ No newline at end of file diff --git a/Golem.Test/Golem.Test.csproj b/Golem.Test/Golem.Test.csproj index 5982907..db0402b 100644 --- a/Golem.Test/Golem.Test.csproj +++ b/Golem.Test/Golem.Test.csproj @@ -1,71 +1,76 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golem.Test</RootNamespace> <AssemblyName>Golem.Test</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="nunit.framework, Version=2.4.7.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\..\Program Files\NUnit 2.4.7\bin\nunit.framework.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="DemoRecipe.cs" /> <Compile Include="FinderConfigurationFixture.cs" /> + <Compile Include="NantRecipeFixure.cs" /> <Compile Include="RecipeDiscoveryFixture.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Golem.Core\Golem.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> <Name>Golem.Core</Name> </ProjectReference> + <ProjectReference Include="..\Golem.Recipes.NAnt\Golem.Recipes.Nant.csproj"> + <Project>{114B7DE4-297E-4FBC-9E0D-FCF07372464A}</Project> + <Name>Golem.Recipes.Nant</Name> + </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Golem.Test/NantRecipeFixure.cs b/Golem.Test/NantRecipeFixure.cs new file mode 100644 index 0000000..4d87aa5 --- /dev/null +++ b/Golem.Test/NantRecipeFixure.cs @@ -0,0 +1,24 @@ +using Golem.Recipes.Nant; +using NUnit.Framework; + +namespace Golem.Test +{ + [TestFixture] + public class NantRecipeFixure + { + [Test] + public void XmlPeek() + { + var r = new NantRecipe(); + r.XmlPeek("HelloWorld.xml", "//Item[2]/@name","name"); + + } + + [Test] + public void Regex() + { + var r = new NantRecipe(); + r.Regex("Hello World",".+(Wor).+"); + } + } +} \ No newline at end of file diff --git a/Golem.Test/RecipeDiscoveryFixture.cs b/Golem.Test/RecipeDiscoveryFixture.cs index da17f17..d290e57 100644 --- a/Golem.Test/RecipeDiscoveryFixture.cs +++ b/Golem.Test/RecipeDiscoveryFixture.cs @@ -1,122 +1,141 @@ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Golem.Core; using NUnit.Framework; using Golem.Core; namespace Golem.Test { [TestFixture] public class RecipeDiscoveryFixture { private RecipeCataloger cataloger; IList<Recipe> found; [SetUp] public void Before_Each_Test_Is_Run() { cataloger = new RecipeCataloger(Environment.CurrentDirectory + "..\\..\\..\\..\\"); found = cataloger.CatalogueRecipes(); } [Test] public void Can_Discover_Recipes() { foreach(var r in found) { Console.WriteLine(r.Name); } Assert.AreEqual(4, found.Count); } [Test] public void Can_Discover_Recipe_Details() { var recipeInfo = found[1]; Assert.AreEqual("demo", recipeInfo.Name); } [Test] public void Can_Discover_Tasks_And_Details() { var recipeInfo = found[1]; Assert.AreEqual(3, recipeInfo.Tasks.Count); Assert.AreEqual("list", recipeInfo.Tasks[1].Name); Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); } [Test] public void Can_Run_Task() { var recipeInfo = found[1]; var runner = new TaskRunner(cataloger); runner.Run(recipeInfo, recipeInfo.Tasks[0]); Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } [Test] public void Can_Run_Task_By_Name() { var runner = new TaskRunner(cataloger); Locations.StartDirs = new[] {Environment.CurrentDirectory + "..\\..\\..\\..\\"}; runner.Run("demo","list"); Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); } + [Test] + public void Can_Execute_Tasks_With_Parameters() + { + var runner = new TaskRunner(cataloger); + var demo5 = found[4]; + Assert.AreEqual("demo5", found[4].Name); + Assert.AreEqual("foo", found[4].Tasks[0].Name); + runner.Run(demo5,demo5.Tasks[0],"TESTING","123"); + } + + [Test] + public void Can_Execute_Tasks_With_Parameters_By_Name() + { + var runner = new TaskRunner(cataloger); + runner.Run("demo5", "foo", "TESTING", "123"); + } + + + [Test, Ignore] public void Can_Run_All_Default_Tasks() { Assert.Fail(); } [Test] public void Can_Set_Dependencies() { var demo2 = found[0]; Assert.AreEqual("demo2", demo2.Name); Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); } [Test] public void Functions_Are_Called_In_Correct_Order_With_Dependencies() { var runner = new TaskRunner(cataloger); runner.Run("demo2", "one"); } [Test] public void Can_Infer_Recipe_Category_And_Task_Name() { var runner = new TaskRunner(cataloger); runner.Run("demo3", "hello"); } [Test, Ignore] public void Can_Override_Current_Root_Folder() { Assert.Fail(); } [Test, Ignore] public void Can_Fetch_List_Of_Available_Recipes_From_Server() { Assert.Fail(); } [Test] public void Recipes_Inheriting_RecipeBase_Have_Contextual_Information() { var demo4 = found[3]; var runner = new TaskRunner(cataloger); runner.Run(demo4,demo4.Tasks[0]); } } } diff --git a/Golem.sln b/Golem.sln index 0569a09..dd64652 100644 --- a/Golem.sln +++ b/Golem.sln @@ -1,43 +1,49 @@  Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Core", "Golem.Core\Golem.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Test", "Golem.Test\Golem.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Runner", "Golem.Runner\Golem.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Build", "Golem.Build\Golem.Build.csproj", "{9F3F3B09-AB90-42E0-B099-81E8BB505954}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Readme", "Readme", "{5ADDCA30-41AD-4EFD-BC98-08C7924EADC7}" ProjectSection(SolutionItems) = preProject - README.txt = README.txt + README.markdown = README.markdown EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Recipes.Nant", "Golem.Recipes.NAnt\Golem.Recipes.Nant.csproj", "{114B7DE4-297E-4FBC-9E0D-FCF07372464A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.Build.0 = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.ActiveCfg = Release|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.Build.0 = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.Build.0 = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.Build.0 = Release|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.Build.0 = Debug|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.ActiveCfg = Release|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.Build.0 = Release|Any CPU + {114B7DE4-297E-4FBC-9E0D-FCF07372464A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {114B7DE4-297E-4FBC-9E0D-FCF07372464A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {114B7DE4-297E-4FBC-9E0D-FCF07372464A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {114B7DE4-297E-4FBC-9E0D-FCF07372464A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
tobinharris/golem
46b8b854838d5583969765e41171b481f48dcdee
The README now has additional info and is less ambiguous.
diff --git a/README.markdown b/README.markdown index 136c0b7..386fff1 100644 --- a/README.markdown +++ b/README.markdown @@ -1,147 +1,162 @@ Golem .NET Build Tool ====================================================================== By [Tobin Harris](mailto:[email protected]) [http://www.tobinharris.com](http://www.tobinharris.com) About Golem ----------- Golem is a simple build tool for Microsoft .NET inspired by Rake and NUnit. It lets you write useful build scripts in regular c# code and run them during development. -Here is a taste of some Golem recipes and their tasks (this is what you type into the command line): +Here is a taste of some *possible* Golem recipes and their tasks. I have *some* of these working already. This is what you type into the command line: - golem test:units # Run all unit NUnit tests in the solution + golem test:units # Run all unit NUnit tests in the solution golem logs:clear # Clear all log files that my app generates - golem iis:restart # Restarts IIS + golem iis:restart # Restarts IIS golem ndepend:top10 # Print out NDepend top 10 problems report golem nhib:mappings # Summarise NHibernate mappings (class -> table) - golem nhib:dbreset # Drop and recreate the development database using NHibernate Mappings - golem stats:code # Print out a count of LOC, classes and functions. - golem solution:clone # Clone a new copy of this solution, pass in NS=newnamespace + golem nhib:dbreset # Drop and recreate the development database using NHibernate Mappings + golem stats:code # Print out a count of LOC, classes and functions. + golem solution:clone # Clone a new copy of this solution, pass in NS=newnamespace golem deploy:staging # Push solution live to staging servers The plan is to have recipes for all sorts of useful things. Including NUnit, NHibernate, Linq 2 SQL, code metrics, log files you name it!... Visual Studio integration is also being considered, so that you can run tasks from there. Also, a pretty GUI is in the pipe-line too. Why Golem? ---------- Golem lets you do a few useful things: - * Create custom tasks and recipes in good old c# or VB.NET code. - * Create tasks for any purpose - * ..Testing, build, deployment, nhibernate, db, documentation, code metrics, reporting etc). - * ..If you can write it in .NET code, you can automate it with Golem! - * No learning new build languages or tools - * Quick and easy to write - * Tasks are easy to run. Invoke from the command line or GUI runner. - * Share recipes between projects - * Share recipes with the community +* Create custom tasks and recipes in good old c# or VB.NET code. +* Create tasks for any purpose +* ..Testing, build, deployment, nhibernate, db, documentation, code metrics, reporting etc). +* ..If you can write it in .NET code, you can automate it with Golem! +* No learning new build languages or tools +* Quick and easy to write +* Tasks are easy to run. Invoke from the command line or GUI runner. +* Share recipes between projects +* Share recipes with the community Golem is an experiment with writing a build system, but it will mature if people like it! Other cool looking Open Source build systems include [Psake](http://code.google.com/p/psake/) which uses Powershell, [Boobs](http://code.google.com/p/boo-build-system/) which uses the Boo language, and [Rake](http://rake.rubyforge.org/) which uses Ruby. Writing Build Recipes & Tasks ----------------------------- If you've used a unit testing framework, then Golem will be familiar territory. Just as NUnit has Test Fixtures and Tests, Golem has Build Recipes and Tasks. Here is a Golem recipe in c# code: // //include this anywhere in your solution // [Recipe(Description="Database Build Tasks")] public class DbRecipe { [Task(Description="Drop the development database"] public void Drop() { //some regular c# code drop the db //...load and execute the SQL drop script Console.WriteLine("Database Schema Dropped"); } [Task(Description="Create the development database") public void Create() { //some regular c# code to create the database //...load and execute the SQL create script Console.WriteLine("Database Schema Created"); } [Task(Description="Drop, create and populat the development database", After=new[]{"Drop","Create"}) public void Reset() { //some regular code to populate data (Drop and Create called automatically) //...load and execute the insert SQL script Console.WriteLine("Sample Dev Data Loaded"); } } Build your solution, and then type this at the command line: cd c:\Code\FooBar golem -T ...which lists available build commands: Golem (Beta) 2008 Your friendly executable .NET build tool. golem db:drop # Drop the development database golem db:create # Create the development database golem db:reset # Drop, create and populat the development database You could now type: > golem db:reset ... to quickly drop, creat and populate your development database. Cool huh? The Sky is the Limit -------------------- Writing your own build tasks is cool, but you find it better to reuse ones already published in the community. Watch out for some cool build tasks in the making... golem nhib:mappings # Lists NHibernate classes and associated tables golem nhib:reset # Drops and recreates db objects for the current environment using NHibernate mapping golem test:all # Runs all NUnit tests in the test solution golem build:all # Runs MSBuild on the solution golem swiss:guid # Generates a new GUID golem swiss:secret # Generates a cryptographically secure secret. golem mvc:routes # List ASP.NET MVC routes and controllers golem mvc:scaffold # Creates an ASP.NET MVC controller and view with given name golem mvc:checklinks # Checks for broken links in current running web site golem stress:db # Runs custom stress test against dev DB and outputs report golem stress:web # Runs custom stress test against web site and outputs report golem ndepend:all # Generate all stats for the project as HTML file and show in browser golem ndepend:critical # Generate critical fixes report from NDepend golem config:reset # Clears config files and replaces them with master copy golem config:init # Copies config files needed to correct places golem config:clear # Deletes copies of Windsor and Hibernate config files from projects golem recipes:list # List available community recipes on public server golem recipes:install # Install a community recipe for use in this project golem recipes:submit # Submit a recipe to the community golem system:update # Update to latest version of Rakish. Pass VERSION for specific version. golem iis:restart # Restart local IIS (Use IP=X.X.X.X for remote golem iis:backupconfigs # Backup IIS configuration files (into project folder here) Early Days ---------- **WARNING:** Golem is still in early development. I'm getting some value from it in my personal projects right now, and you can too. BUT, it's probably not not quite ready for use on commercial projects yet. The code base is still unstable. Get Involved ------------ Download and try it out. If you're interested in helping with Golem, then let me know. Also, feel free to send your ideas, thoughts or findings to [[email protected]]([email protected]). +Vision +------ +It's important to have a vision, even if it's naive :) The vision for Golem is as follows: + +* The defacto build "swiss army knife" for automating development tasks +* Visual Studio integration, command line and stand-alone runner +* Totally easy to understand and start using +* Easy to share recipes and get huge leverage from other peoples work +* Integration with popular CI servers +* Mono compatible +* Installs with useful ready-to-use recipes for all popular tools and technologies (ASP.NET, NUnit, MVC, Linq 2 SQL, NHibernate, NDepend, SQL Server, Documentation, Deployment etc) +* Ability to list, download and start using new recipes at the click of a button (or tap on the keybaord) +* Self updating +* Vendors write recipes and deploy them with their tools. +
tobinharris/golem
8f8f466d16b7a03ebe49893829a864e8e5607e48
The README file now has more useful information
diff --git a/README.markdown b/README.markdown index e9304cd..136c0b7 100644 --- a/README.markdown +++ b/README.markdown @@ -1,130 +1,147 @@ Golem .NET Build Tool ====================================================================== -By Tobin Harris [http://www.tobinharris.com](http://www.tobinharris.com) +By [Tobin Harris](mailto:[email protected]) [http://www.tobinharris.com](http://www.tobinharris.com) About Golem ----------- -Golem is a simple build tool for Microsoft .NET 3.5. -It lets you specify build tasks in regular c# code. -You can run those in various ways: from the command line, a GUI runner, or from within visual studio. +Golem is a simple build tool for Microsoft .NET inspired by Rake and NUnit. It lets you write useful build scripts in regular c# code and run them during development. -Advantages include: +Here is a taste of some Golem recipes and their tasks (this is what you type into the command line): + + golem test:units # Run all unit NUnit tests in the solution + golem logs:clear # Clear all log files that my app generates + golem iis:restart # Restarts IIS + golem ndepend:top10 # Print out NDepend top 10 problems report + golem nhib:mappings # Summarise NHibernate mappings (class -> table) + golem nhib:dbreset # Drop and recreate the development database using NHibernate Mappings + golem stats:code # Print out a count of LOC, classes and functions. + golem solution:clone # Clone a new copy of this solution, pass in NS=newnamespace + golem deploy:staging # Push solution live to staging servers + +The plan is to have recipes for all sorts of useful things. Including NUnit, NHibernate, Linq 2 SQL, code metrics, log files you name it!... + +Visual Studio integration is also being considered, so that you can run tasks from there. Also, a pretty GUI is in the pipe-line too. + +Why Golem? +---------- + +Golem lets you do a few useful things: * Create custom tasks and recipes in good old c# or VB.NET code. - * Flexible. Create tasks for any purpose (testing, build, deployment, nhibernate, db, documentation, code metrics, reporting etc) + * Create tasks for any purpose + * ..Testing, build, deployment, nhibernate, db, documentation, code metrics, reporting etc). + * ..If you can write it in .NET code, you can automate it with Golem! * No learning new build languages or tools * Quick and easy to write * Tasks are easy to run. Invoke from the command line or GUI runner. * Share recipes between projects * Share recipes with the community -Golem is currently under development by Tobin Harris, and was inspired by Ruby Rake. +Golem is an experiment with writing a build system, but it will mature if people like it! Other cool looking Open Source build systems include [Psake](http://code.google.com/p/psake/) which uses Powershell, [Boobs](http://code.google.com/p/boo-build-system/) which uses the Boo language, and [Rake](http://rake.rubyforge.org/) which uses Ruby. -Build Recipes & Tasks ---------------------- +Writing Build Recipes & Tasks +----------------------------- -If you've used a unit testing framework, then Golem code will be familiar. +If you've used a unit testing framework, then Golem will be familiar territory. Just as NUnit has Test Fixtures and Tests, Golem has Build Recipes and Tasks. Here is a Golem recipe in c# code: // //include this anywhere in your solution // [Recipe(Description="Database Build Tasks")] public class DbRecipe { [Task(Description="Drop the development database"] public void Drop() { //some regular c# code drop the db //...load and execute the SQL drop script Console.WriteLine("Database Schema Dropped"); } [Task(Description="Create the development database") public void Create() { //some regular c# code to create the database //...load and execute the SQL create script Console.WriteLine("Database Schema Created"); } [Task(Description="Drop, create and populat the development database", After=new[]{"Drop","Create"}) public void Reset() { //some regular code to populate data (Drop and Create called automatically) //...load and execute the insert SQL script Console.WriteLine("Sample Dev Data Loaded"); } } Build your solution, and then type this at the command line: cd c:\Code\FooBar golem -T ...which lists available build commands: Golem (Beta) 2008 Your friendly executable .NET build tool. golem db:drop # Drop the development database golem db:create # Create the development database golem db:reset # Drop, create and populat the development database You could now type: > golem db:reset ... to quickly drop, creat and populate your development database. Cool huh? The Sky is the Limit -------------------- Writing your own build tasks is cool, but you find it better to reuse ones already published in the community. Watch out for some cool build tasks in the making... golem nhib:mappings # Lists NHibernate classes and associated tables golem nhib:reset # Drops and recreates db objects for the current environment using NHibernate mapping golem test:all # Runs all NUnit tests in the test solution golem build:all # Runs MSBuild on the solution golem swiss:guid # Generates a new GUID golem swiss:secret # Generates a cryptographically secure secret. golem mvc:routes # List ASP.NET MVC routes and controllers golem mvc:scaffold # Creates an ASP.NET MVC controller and view with given name golem mvc:checklinks # Checks for broken links in current running web site golem stress:db # Runs custom stress test against dev DB and outputs report golem stress:web # Runs custom stress test against web site and outputs report golem ndepend:all # Generate all stats for the project as HTML file and show in browser golem ndepend:critical # Generate critical fixes report from NDepend golem config:reset # Clears config files and replaces them with master copy golem config:init # Copies config files needed to correct places golem config:clear # Deletes copies of Windsor and Hibernate config files from projects golem recipes:list # List available community recipes on public server golem recipes:install # Install a community recipe for use in this project golem recipes:submit # Submit a recipe to the community golem system:update # Update to latest version of Rakish. Pass VERSION for specific version. golem iis:restart # Restart local IIS (Use IP=X.X.X.X for remote golem iis:backupconfigs # Backup IIS configuration files (into project folder here) -Ready for Shaping ------------------ -Golem is still in BETA. I'm getting some value from it in my personal projects right now, and you can too. +Early Days +---------- +**WARNING:** Golem is still in early development. I'm getting some value from it in my personal projects right now, and you can too. BUT, it's probably not not quite ready for use on commercial projects yet. The code base is still unstable. -Coders Needed -------------- -If you're interested in helping with Golem, then let me know. +Get Involved +------------ +Download and try it out. If you're interested in helping with Golem, then let me know. Also, feel free to send your ideas, thoughts or findings to [[email protected]]([email protected]). - -
tobinharris/golem
bd3fd642f2a942860d272ed1418e53176df4b9ff
Use of Recipe Search Cache is disabled until referenced assemblies can be loaded dynamically.
diff --git a/Golem.Core/RecipeCataloger.cs b/Golem.Core/RecipeCataloger.cs index 07e1fba..51893f4 100644 --- a/Golem.Core/RecipeCataloger.cs +++ b/Golem.Core/RecipeCataloger.cs @@ -1,255 +1,254 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; using Golem.Core; namespace Golem.Core { public class RecipeCatalogue { public RecipeCatalogue(List<LoadedAssemblyInfo> found) { } } /// <summary> /// /// </summary> public class RecipeCataloger { //loads assemblies //building tree of recipes //reflecting on types private readonly string[] _searchPaths; private readonly List<LoadedAssemblyInfo> _loadedAssemblies; public RecipeCataloger(params string[] searchPaths) { _searchPaths = searchPaths; _loadedAssemblies = new List<LoadedAssemblyInfo>(); } public ReadOnlyCollection<LoadedAssemblyInfo> LoadedAssemblies { get { return _loadedAssemblies.AsReadOnly(); } } /// <summary> /// Queries loaded assembly info to list all assemblies examined /// </summary> public ReadOnlyCollection<Assembly> AssembliesExamined { get { return (from la in _loadedAssemblies select la.Assembly).ToList().AsReadOnly(); } } /// <summary> /// Queries loaded assembly info to list the associated recipes with each /// </summary> public ReadOnlyCollection<Recipe> Recipes { get { return (from la in _loadedAssemblies from r in la.FoundRecipes select r).ToList().AsReadOnly(); } } /// <summary> /// Lists assemblies that contained recipes /// </summary> public List<LoadedAssemblyInfo> LoadedAssembliesContainingRecipes { get { return (from la in _loadedAssemblies where la.FoundRecipes.Count > 0 select la).ToList(); } } /// <summary> /// /// </summary> /// <returns></returns> public IList<Recipe> CatalogueRecipes() { var fileSearch = new RecipeFileSearch(_searchPaths); fileSearch.BuildFileList(); PreLoadAssembliesToPreventAssemblyNotFoundError( fileSearch.FoundAssemblyFiles.ToArray() ); ExtractRecipesFromPreLoadedAssemblies(); return Recipes.ToArray(); } private void PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] assemblyFiles) { //TODO: Preloading all assemblies in the solution is BRUTE FORCE! Should separate discovery of recipes // from invocation. Perhpas use LoadForReflection during discovery. We'd then need to have // Assemblies loaded for real before invokation (see TaskRunner), along with satellite assemblies. foreach (var file in assemblyFiles) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail if( ! file.Name.StartsWith("Golem.Core") && ! LoadedAssemblies.Any(la=>la.File.Name == file.Name)) { try { - Console.WriteLine("Loading " + file.FullName); var i = new LoadedAssemblyInfo { Assembly = Assembly.LoadFrom(file.FullName), File = file }; _loadedAssemblies.Add(i); } catch (Exception e) { - Console.WriteLine("Ooops: " + e.Message); + //Console.WriteLine("Ooops: " + e.Message); } } } private void ExtractRecipesFromPreLoadedAssemblies() { foreach(var la in LoadedAssemblies) try { foreach (var type in la.Assembly.GetTypes()) ExtractRecipesFromType(type, la); } catch (ReflectionTypeLoadException e) { // foreach(var ex in e.LoaderExceptions) // Console.WriteLine("Load Exception: " + ex.Message); } } public RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } private void ExtractRecipesFromType(Type type, LoadedAssemblyInfo la) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //associate recipe with assembly la.FoundRecipes.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task task) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); task.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } } } \ No newline at end of file diff --git a/Golem.Runner/Program.cs b/Golem.Runner/Program.cs index a9aa978..0aca69e 100644 --- a/Golem.Runner/Program.cs +++ b/Golem.Runner/Program.cs @@ -1,96 +1,97 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Golem.Core; using Golem.Core; namespace Golem.Runner { public class Program { public static void Main(string[] args) { Console.WriteLine("Golem (Beta) 2008\nYour friendly executable .NET build tool. \n"); IList<Recipe> found; - RecipeCataloger finder = BuildCatalog(out found); + RecipeCataloger finder = CreateCataloger(out found); if(args.Length > 0) { if(args[0] == "-T") { ShowList(found); return; } else if(args[0].ToLower() == "-?") { Console.WriteLine("Help: \n"); Console.WriteLine("golem -T # List build tasks"); Console.WriteLine("golem -? # Show this help"); Console.WriteLine("golem -? # Show this help"); return; } var parts = args[0].Split(':'); var runner = new TaskRunner(finder); if(parts.Length == 2) runner.Run(parts[0],parts[1]); else { Console.WriteLine("Type golem -? for help, or try one of the following tasks:\n"); ShowList(found); } } else { ShowList(found); } } - private static RecipeCataloger BuildCatalog(out IList<Recipe> found) + private static RecipeCataloger CreateCataloger(out IList<Recipe> found) { RecipeCataloger finder; var config = new Configuration(); - if (config.SearchPaths.Count > 0) + //TODO: Remove false when ready. Caching location of recipes isn't going to be useful until we can dynamically load dependant assemblies on the fly + if (false && config.SearchPaths.Count > 0) finder = new RecipeCataloger(config.SearchPaths.ToArray()); else { Console.WriteLine("Scanning directories for Build Recipes (could take a while)..."); finder = new RecipeCataloger(Environment.CurrentDirectory); } found = finder.CatalogueRecipes(); if(config.SearchPaths.Count == 0) { config.SearchPaths.AddRange(finder.LoadedAssemblies.Select(s=>s.File.FullName)); config.Save(); } return finder; } private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { //Console.WriteLine("\n{0}\n",!String.IsNullOrEmpty(recipe.Description) ? recipe.Description : recipe.Name); foreach(var task in recipe.Tasks) { var start = "golem " + recipe.Name + ":" + task.Name; Console.WriteLine(start.PadRight(30) +"# " + task.Description); } } if (found.Count == 0) Console.WriteLine("No recipes found under {0}", new DirectoryInfo(Environment.CurrentDirectory).Name); } } }
tobinharris/golem
6b846f75c43ea119eba51857d4917b07deda8388
RecipeFileSearch can now list distinct recipe directories. TaskRunner has TODOs added.
diff --git a/Golem.Core/Golem.Core.csproj b/Golem.Core/Golem.Core.csproj index beffffb..981354c 100644 --- a/Golem.Core/Golem.Core.csproj +++ b/Golem.Core/Golem.Core.csproj @@ -1,68 +1,68 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{267A8DF5-2B11-470E-8878-BE6E7244B713}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golem.Core</RootNamespace> <AssemblyName>Golem.Core</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Configuration.cs" /> - <Compile Include="FileSearch.cs" /> <Compile Include="LoadedAssemblyInfo.cs" /> <Compile Include="Locations.cs" /> <Compile Include="Recipe.cs" /> + <Compile Include="RecipeFileSearch.cs" /> <Compile Include="Task.cs" /> <Compile Include="TaskAttribute.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RecipeAttribute.cs" /> <Compile Include="RecipeCataloger.cs" /> <Compile Include="TaskRunner.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Golem.Core/RecipeCataloger.cs b/Golem.Core/RecipeCataloger.cs index 37e68b8..07e1fba 100644 --- a/Golem.Core/RecipeCataloger.cs +++ b/Golem.Core/RecipeCataloger.cs @@ -1,269 +1,255 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; using Golem.Core; namespace Golem.Core { public class RecipeCatalogue { public RecipeCatalogue(List<LoadedAssemblyInfo> found) { } } /// <summary> /// /// </summary> public class RecipeCataloger { //loads assemblies //building tree of recipes //reflecting on types private readonly string[] _searchPaths; private readonly List<LoadedAssemblyInfo> _loadedAssemblies; public RecipeCataloger(params string[] searchPaths) { _searchPaths = searchPaths; _loadedAssemblies = new List<LoadedAssemblyInfo>(); } public ReadOnlyCollection<LoadedAssemblyInfo> LoadedAssemblies { get { return _loadedAssemblies.AsReadOnly(); } } /// <summary> /// Queries loaded assembly info to list all assemblies examined /// </summary> public ReadOnlyCollection<Assembly> AssembliesExamined { get { return (from la in _loadedAssemblies select la.Assembly).ToList().AsReadOnly(); } } /// <summary> /// Queries loaded assembly info to list the associated recipes with each /// </summary> public ReadOnlyCollection<Recipe> Recipes { get { return (from la in _loadedAssemblies from r in la.FoundRecipes select r).ToList().AsReadOnly(); } } /// <summary> /// Lists assemblies that contained recipes /// </summary> public List<LoadedAssemblyInfo> LoadedAssembliesContainingRecipes { get { return (from la in _loadedAssemblies where la.FoundRecipes.Count > 0 select la).ToList(); } } /// <summary> /// /// </summary> /// <returns></returns> public IList<Recipe> CatalogueRecipes() { var fileSearch = new RecipeFileSearch(_searchPaths); fileSearch.BuildFileList(); - - PreLoadAssembliesToPreventAssemblyNotFoundError( - fileSearch.FoundAssemblyFiles.ToArray() - ); - - ExtractRecipesFromPreLoadedAssemblies(); - return Recipes.ToArray(); - } - - public IList<Recipe> CatalogueRecipesHowItShouldBeDone() - { - var fileSearch = new RecipeFileSearch(_searchPaths); - fileSearch.BuildFileList(); - PreLoadAssembliesToPreventAssemblyNotFoundError( fileSearch.FoundAssemblyFiles.ToArray() ); - + ExtractRecipesFromPreLoadedAssemblies(); return Recipes.ToArray(); } - - private void PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] assemblyFiles) { //TODO: Preloading all assemblies in the solution is BRUTE FORCE! Should separate discovery of recipes - // from invocation. Perhpas use LoadForReflection during discovery. + // from invocation. Perhpas use LoadForReflection during discovery. We'd then need to have + // Assemblies loaded for real before invokation (see TaskRunner), along with satellite assemblies. foreach (var file in assemblyFiles) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail - if( ! file.Name.StartsWith("Golem.Core") && ! LoadedAssemblies.Any(la=>la.File.FullName == file.FullName)) + if( ! file.Name.StartsWith("Golem.Core") && ! LoadedAssemblies.Any(la=>la.File.Name == file.Name)) { try { + Console.WriteLine("Loading " + file.FullName); var i = new LoadedAssemblyInfo { Assembly = Assembly.LoadFrom(file.FullName), File = file }; _loadedAssemblies.Add(i); } catch (Exception e) { Console.WriteLine("Ooops: " + e.Message); } } } private void ExtractRecipesFromPreLoadedAssemblies() { foreach(var la in LoadedAssemblies) try { foreach (var type in la.Assembly.GetTypes()) ExtractRecipesFromType(type, la); } catch (ReflectionTypeLoadException e) { // foreach(var ex in e.LoaderExceptions) // Console.WriteLine("Load Exception: " + ex.Message); } } public RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } private void ExtractRecipesFromType(Type type, LoadedAssemblyInfo la) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //associate recipe with assembly la.FoundRecipes.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task task) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); task.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } } } \ No newline at end of file diff --git a/Golem.Core/RecipeFileSearch.cs b/Golem.Core/RecipeFileSearch.cs index 347de4d..482fa70 100644 --- a/Golem.Core/RecipeFileSearch.cs +++ b/Golem.Core/RecipeFileSearch.cs @@ -1,56 +1,63 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; +using System.Linq; namespace Golem.Core { - public class FileSearch + public class RecipeFileSearch { private string[] startDirs; public List<FileInfo> FoundAssemblyFiles = new List<FileInfo>(); + public ReadOnlyCollection<string> DistinctAssemblyFolders; - public FileSearch() + public RecipeFileSearch() { startDirs = new[] { Environment.CurrentDirectory }; } - public FileSearch(params string[] startDirs) + public RecipeFileSearch(params string[] startDirs) { this.startDirs = startDirs; } public void BuildFileList() { FoundAssemblyFiles.Clear(); foreach (var startDir in startDirs) { FileInfo[] dlls = FindFilesExcludingDuplicates(startDir); FoundAssemblyFiles.AddRange(dlls); } + + var tmp = FoundAssemblyFiles.GroupBy(s => s.Directory.FullName); + DistinctAssemblyFolders = tmp.Select(s => s.Key).ToList().AsReadOnly(); + } private FileInfo[] FindFilesExcludingDuplicates(string startDir) { //if a file, then return var tmp = new FileInfo(startDir); if( tmp.Exists ) { return new[]{tmp}; } var found = new DirectoryInfo(startDir) .GetFiles("*.dll", SearchOption.AllDirectories); var valid = new List<FileInfo>(); foreach (var fileInfo in found) if (!fileInfo.Directory.FullName.Contains("\\obj\\") && ! FoundAssemblyFiles.Contains(fileInfo)) valid.Add(fileInfo); return valid.ToArray(); } } } \ No newline at end of file diff --git a/Golem.Core/TaskRunner.cs b/Golem.Core/TaskRunner.cs index d8f73bb..ebe93e9 100644 --- a/Golem.Core/TaskRunner.cs +++ b/Golem.Core/TaskRunner.cs @@ -1,125 +1,130 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; +using System.Linq; namespace Golem.Core { public class RecipeBase { public IList<Assembly> AllAssemblies = new List<Assembly>(); public IList<Recipe> AllRecipes = new List<Recipe>(); } public class TaskRunner { private RecipeCataloger cataloger; public TaskRunner(RecipeCataloger aCataloger) { cataloger = aCataloger; } public void Run(Recipe recipe, Task task) { + //TODO: Tasks should run in their own appdomain. + // We need to create an app domain that has the + // base dir the same as the target assembly + var recipeInstance = Activator.CreateInstance(recipe.Class); SetContextualInformationIfInheritsRecipeBase(recipeInstance); task.Method.Invoke(recipeInstance, null); } private void SetContextualInformationIfInheritsRecipeBase(object recipeInstance) { var tmpRecipe = recipeInstance as RecipeBase; if(tmpRecipe == null) return; tmpRecipe.AllAssemblies = cataloger.AssembliesExamined; tmpRecipe.AllRecipes = cataloger.Recipes; } //TODO: Run is Too long //TODO: Nesting depth is too deep public void Run(string recipeName, string taskName) { if(cataloger.Recipes.Count==0) cataloger.CatalogueRecipes(); foreach (var r in cataloger.Recipes) { if(r.Name.ToLower() == recipeName.ToLower()) { foreach(var t in r.Tasks) { if(t.Name.ToLower() == taskName.ToLower()) { foreach(var methodInfo in t.DependsOnMethods) { Run(r, r.GetTaskForMethod(methodInfo)); } Run(r, t); return; } } } } } // public RunManifest BuildRunManifest(string recipeName, string taskName) // { // var manifest = new RunManifest(); // var cataloger = new RecipeCataloger(); // var found = cataloger.CatalogueRecipes(); // // foreach (var r in found) // { // if (r.Name.ToLower() == recipeName.ToLower()) // { // foreach (var t in r.Tasks) // { // if (t.Name.ToLower() == taskName.ToLower()) // { // foreach(var d in t.DependsOnMethods) // { // manifest.Add(null); // } // manifest.Add(t); // // } // } // } // } // return manifest; // } } public class RunManifest { public OrderedDictionary ToRun; public void Add(Task t) { if(! ToRun.Contains(t)) { ToRun.Add(t,new RunManifestItem{Task=t}); } } public RunManifest() { ToRun = new OrderedDictionary(); } public Task TaskAt(int position) { return (Task) ToRun[position]; } } public class RunManifestItem { public Task Task; public bool HasRun; } } \ No newline at end of file
tobinharris/golem
2cacfab5eabfdb2697715fe4e31796737f5aeb4a
I am Refactoring to make stuff read better
diff --git a/Golem.Core/RecipeCataloger.cs b/Golem.Core/RecipeCataloger.cs index aee1e2a..37e68b8 100644 --- a/Golem.Core/RecipeCataloger.cs +++ b/Golem.Core/RecipeCataloger.cs @@ -1,252 +1,269 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; using Golem.Core; namespace Golem.Core { public class RecipeCatalogue { public RecipeCatalogue(List<LoadedAssemblyInfo> found) { } } /// <summary> /// /// </summary> public class RecipeCataloger { //loads assemblies //building tree of recipes //reflecting on types private readonly string[] _searchPaths; private readonly List<LoadedAssemblyInfo> _loadedAssemblies; public RecipeCataloger(params string[] searchPaths) { _searchPaths = searchPaths; _loadedAssemblies = new List<LoadedAssemblyInfo>(); } public ReadOnlyCollection<LoadedAssemblyInfo> LoadedAssemblies { get { return _loadedAssemblies.AsReadOnly(); } } /// <summary> /// Queries loaded assembly info to list all assemblies examined /// </summary> public ReadOnlyCollection<Assembly> AssembliesExamined { get { return (from la in _loadedAssemblies select la.Assembly).ToList().AsReadOnly(); } } /// <summary> /// Queries loaded assembly info to list the associated recipes with each /// </summary> public ReadOnlyCollection<Recipe> Recipes { get { return (from la in _loadedAssemblies from r in la.FoundRecipes select r).ToList().AsReadOnly(); } } /// <summary> /// Lists assemblies that contained recipes /// </summary> public List<LoadedAssemblyInfo> LoadedAssembliesContainingRecipes { get { return (from la in _loadedAssemblies where la.FoundRecipes.Count > 0 select la).ToList(); } } /// <summary> /// /// </summary> /// <returns></returns> public IList<Recipe> CatalogueRecipes() { - var fileSearch = new FileSearch(_searchPaths); + var fileSearch = new RecipeFileSearch(_searchPaths); fileSearch.BuildFileList(); - + PreLoadAssembliesToPreventAssemblyNotFoundError( fileSearch.FoundAssemblyFiles.ToArray() ); ExtractRecipesFromPreLoadedAssemblies(); return Recipes.ToArray(); } + public IList<Recipe> CatalogueRecipesHowItShouldBeDone() + { + var fileSearch = new RecipeFileSearch(_searchPaths); + fileSearch.BuildFileList(); + + + PreLoadAssembliesToPreventAssemblyNotFoundError( + fileSearch.FoundAssemblyFiles.ToArray() + ); + + ExtractRecipesFromPreLoadedAssemblies(); + return Recipes.ToArray(); + } + private void PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] assemblyFiles) { + //TODO: Preloading all assemblies in the solution is BRUTE FORCE! Should separate discovery of recipes + // from invocation. Perhpas use LoadForReflection during discovery. + foreach (var file in assemblyFiles) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail if( ! file.Name.StartsWith("Golem.Core") && ! LoadedAssemblies.Any(la=>la.File.FullName == file.FullName)) { try { var i = new LoadedAssemblyInfo { Assembly = Assembly.LoadFrom(file.FullName), File = file }; _loadedAssemblies.Add(i); } catch (Exception e) { Console.WriteLine("Ooops: " + e.Message); } } } private void ExtractRecipesFromPreLoadedAssemblies() { foreach(var la in LoadedAssemblies) try { foreach (var type in la.Assembly.GetTypes()) ExtractRecipesFromType(type, la); } catch (ReflectionTypeLoadException e) { // foreach(var ex in e.LoaderExceptions) // Console.WriteLine("Load Exception: " + ex.Message); } } public RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } private void ExtractRecipesFromType(Type type, LoadedAssemblyInfo la) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //associate recipe with assembly la.FoundRecipes.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task task) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); task.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } } } \ No newline at end of file diff --git a/Golem.Core/FileSearch.cs b/Golem.Core/RecipeFileSearch.cs similarity index 100% rename from Golem.Core/FileSearch.cs rename to Golem.Core/RecipeFileSearch.cs
tobinharris/golem
dc05ac19768e0c13634741954ca85c9501377334
tweaking README
diff --git a/README.markdown b/README.markdown index ff66307..e9304cd 100644 --- a/README.markdown +++ b/README.markdown @@ -1,120 +1,130 @@ Golem .NET Build Tool ====================================================================== By Tobin Harris [http://www.tobinharris.com](http://www.tobinharris.com) About Golem ----------- Golem is a simple build tool for Microsoft .NET 3.5. It lets you specify build tasks in regular c# code. You can run those in various ways: from the command line, a GUI runner, or from within visual studio. Advantages include: * Create custom tasks and recipes in good old c# or VB.NET code. * Flexible. Create tasks for any purpose (testing, build, deployment, nhibernate, db, documentation, code metrics, reporting etc) * No learning new build languages or tools * Quick and easy to write * Tasks are easy to run. Invoke from the command line or GUI runner. * Share recipes between projects * Share recipes with the community Golem is currently under development by Tobin Harris, and was inspired by Ruby Rake. Build Recipes & Tasks --------------------- If you've used a unit testing framework, then Golem code will be familiar. Just as NUnit has Test Fixtures and Tests, Golem has Build Recipes and Tasks. Here is a Golem recipe in c# code: // //include this anywhere in your solution // [Recipe(Description="Database Build Tasks")] public class DbRecipe { [Task(Description="Drop the development database"] public void Drop() { //some regular c# code drop the db //...load and execute the SQL drop script Console.WriteLine("Database Schema Dropped"); } [Task(Description="Create the development database") public void Create() { //some regular c# code to create the database //...load and execute the SQL create script Console.WriteLine("Database Schema Created"); } [Task(Description="Drop, create and populat the development database", After=new[]{"Drop","Create"}) public void Reset() { //some regular code to populate data (Drop and Create called automatically) //...load and execute the insert SQL script Console.WriteLine("Sample Dev Data Loaded"); } } Build your solution, and then type this at the command line: cd c:\Code\FooBar golem -T ...which lists available build commands: Golem (Beta) 2008 Your friendly executable .NET build tool. golem db:drop # Drop the development database golem db:create # Create the development database golem db:reset # Drop, create and populat the development database You could now type: > golem db:reset ... to quickly drop, creat and populate your development database. Cool huh? The Sky is the Limit -------------------- Writing your own build tasks is cool, but you find it better to reuse ones already published in the community. Watch out for some cool build tasks in the making... golem nhib:mappings # Lists NHibernate classes and associated tables golem nhib:reset # Drops and recreates db objects for the current environment using NHibernate mapping golem test:all # Runs all NUnit tests in the test solution golem build:all # Runs MSBuild on the solution golem swiss:guid # Generates a new GUID golem swiss:secret # Generates a cryptographically secure secret. golem mvc:routes # List ASP.NET MVC routes and controllers golem mvc:scaffold # Creates an ASP.NET MVC controller and view with given name golem mvc:checklinks # Checks for broken links in current running web site golem stress:db # Runs custom stress test against dev DB and outputs report golem stress:web # Runs custom stress test against web site and outputs report golem ndepend:all # Generate all stats for the project as HTML file and show in browser golem ndepend:critical # Generate critical fixes report from NDepend golem config:reset # Clears config files and replaces them with master copy golem config:init # Copies config files needed to correct places golem config:clear # Deletes copies of Windsor and Hibernate config files from projects golem recipes:list # List available community recipes on public server golem recipes:install # Install a community recipe for use in this project golem recipes:submit # Submit a recipe to the community golem system:update # Update to latest version of Rakish. Pass VERSION for specific version. golem iis:restart # Restart local IIS (Use IP=X.X.X.X for remote golem iis:backupconfigs # Backup IIS configuration files (into project folder here) + +Ready for Shaping +----------------- +Golem is still in BETA. I'm getting some value from it in my personal projects right now, and you can too. +BUT, it's probably not not quite ready for use on commercial projects yet. The code base is still unstable. + +Coders Needed +------------- +If you're interested in helping with Golem, then let me know. +Also, feel free to send your ideas, thoughts or findings to [[email protected]]([email protected]).
tobinharris/golem
29e32c17dfca7239442695c6de2d0ce379019756
tweaking README
diff --git a/README.markdown b/README.markdown index 189e19e..ff66307 100644 --- a/README.markdown +++ b/README.markdown @@ -1,120 +1,120 @@ Golem .NET Build Tool ====================================================================== By Tobin Harris [http://www.tobinharris.com](http://www.tobinharris.com) About Golem ----------- Golem is a simple build tool for Microsoft .NET 3.5. It lets you specify build tasks in regular c# code. You can run those in various ways: from the command line, a GUI runner, or from within visual studio. Advantages include: * Create custom tasks and recipes in good old c# or VB.NET code. * Flexible. Create tasks for any purpose (testing, build, deployment, nhibernate, db, documentation, code metrics, reporting etc) * No learning new build languages or tools * Quick and easy to write * Tasks are easy to run. Invoke from the command line or GUI runner. * Share recipes between projects * Share recipes with the community Golem is currently under development by Tobin Harris, and was inspired by Ruby Rake. Build Recipes & Tasks --------------------- If you've used a unit testing framework, then Golem code will be familiar. Just as NUnit has Test Fixtures and Tests, Golem has Build Recipes and Tasks. Here is a Golem recipe in c# code: // //include this anywhere in your solution // [Recipe(Description="Database Build Tasks")] public class DbRecipe { [Task(Description="Drop the development database"] public void Drop() { //some regular c# code drop the db //...load and execute the SQL drop script Console.WriteLine("Database Schema Dropped"); } [Task(Description="Create the development database") public void Create() { //some regular c# code to create the database //...load and execute the SQL create script Console.WriteLine("Database Schema Created"); } [Task(Description="Drop, create and populat the development database", After=new[]{"Drop","Create"}) public void Reset() { //some regular code to populate data (Drop and Create called automatically) //...load and execute the insert SQL script Console.WriteLine("Sample Dev Data Loaded"); } } Build your solution, and then type this at the command line: cd c:\Code\FooBar golem -T ...which lists available build commands: Golem (Beta) 2008 Your friendly executable .NET build tool. golem db:drop # Drop the development database golem db:create # Create the development database golem db:reset # Drop, create and populat the development database You could now type: - > golem db:reet + > golem db:reset ... to quickly drop, creat and populate your development database. Cool huh? The Sky is the Limit -------------------- Writing your own build tasks is cool, but you find it better to reuse ones already published in the community. Watch out for some cool build tasks in the making... golem nhib:mappings # Lists NHibernate classes and associated tables golem nhib:reset # Drops and recreates db objects for the current environment using NHibernate mapping golem test:all # Runs all NUnit tests in the test solution golem build:all # Runs MSBuild on the solution golem swiss:guid # Generates a new GUID golem swiss:secret # Generates a cryptographically secure secret. golem mvc:routes # List ASP.NET MVC routes and controllers golem mvc:scaffold # Creates an ASP.NET MVC controller and view with given name golem mvc:checklinks # Checks for broken links in current running web site golem stress:db # Runs custom stress test against dev DB and outputs report golem stress:web # Runs custom stress test against web site and outputs report golem ndepend:all # Generate all stats for the project as HTML file and show in browser golem ndepend:critical # Generate critical fixes report from NDepend golem config:reset # Clears config files and replaces them with master copy golem config:init # Copies config files needed to correct places golem config:clear # Deletes copies of Windsor and Hibernate config files from projects golem recipes:list # List available community recipes on public server golem recipes:install # Install a community recipe for use in this project golem recipes:submit # Submit a recipe to the community golem system:update # Update to latest version of Rakish. Pass VERSION for specific version. golem iis:restart # Restart local IIS (Use IP=X.X.X.X for remote golem iis:backupconfigs # Backup IIS configuration files (into project folder here)
tobinharris/golem
0c07ef91170ab31995dfe006d8fe459d8e4c791b
tweaking README
diff --git a/README.markdown b/README.markdown index d2a1c97..189e19e 100644 --- a/README.markdown +++ b/README.markdown @@ -1,115 +1,120 @@ -====================================================================== Golem .NET Build Tool -By Tobin Harris (http://www.tobinharris.com) ====================================================================== -= About = +By Tobin Harris [http://www.tobinharris.com](http://www.tobinharris.com) + +About Golem +----------- Golem is a simple build tool for Microsoft .NET 3.5. -It lets you specify build tasks in regular c# code, and then run them from the command line (see the list at the bottom of the file). -Inspired by Ruby Rake. +It lets you specify build tasks in regular c# code. +You can run those in various ways: from the command line, a GUI runner, or from within visual studio. Advantages include: * Create custom tasks and recipes in good old c# or VB.NET code. * Flexible. Create tasks for any purpose (testing, build, deployment, nhibernate, db, documentation, code metrics, reporting etc) * No learning new build languages or tools - * Can be run from the command line * Quick and easy to write + * Tasks are easy to run. Invoke from the command line or GUI runner. * Share recipes between projects - * Share recipes with the community + * Share recipes with the community + +Golem is currently under development by Tobin Harris, and was inspired by Ruby Rake. -= Build Recipes = +Build Recipes & Tasks +--------------------- If you've used a unit testing framework, then Golem code will be familiar. Just as NUnit has Test Fixtures and Tests, Golem has Build Recipes and Tasks. Here is a Golem recipe in c# code: // //include this anywhere in your solution // [Recipe(Description="Database Build Tasks")] public class DbRecipe { [Task(Description="Drop the development database"] public void Drop() { //some regular c# code drop the db //...load and execute the SQL drop script Console.WriteLine("Database Schema Dropped"); } [Task(Description="Create the development database") public void Create() { //some regular c# code to create the database //...load and execute the SQL create script Console.WriteLine("Database Schema Created"); } [Task(Description="Drop, create and populat the development database", After=new[]{"Drop","Create"}) public void Reset() { //some regular code to populate data (Drop and Create called automatically) //...load and execute the insert SQL script Console.WriteLine("Sample Dev Data Loaded"); } } Build your solution, and then type this at the command line: cd c:\Code\FooBar golem -T ...which lists available build commands: Golem (Beta) 2008 Your friendly executable .NET build tool. golem db:drop # Drop the development database golem db:create # Create the development database golem db:reset # Drop, create and populat the development database You could now type: > golem db:reet ... to quickly drop, creat and populate your development database. Cool huh? -= The Sky is the Limit = +The Sky is the Limit +-------------------- Writing your own build tasks is cool, but you find it better to reuse ones already published in the community. Watch out for some cool build tasks in the making... golem nhib:mappings # Lists NHibernate classes and associated tables golem nhib:reset # Drops and recreates db objects for the current environment using NHibernate mapping golem test:all # Runs all NUnit tests in the test solution golem build:all # Runs MSBuild on the solution golem swiss:guid # Generates a new GUID golem swiss:secret # Generates a cryptographically secure secret. golem mvc:routes # List ASP.NET MVC routes and controllers golem mvc:scaffold # Creates an ASP.NET MVC controller and view with given name golem mvc:checklinks # Checks for broken links in current running web site golem stress:db # Runs custom stress test against dev DB and outputs report golem stress:web # Runs custom stress test against web site and outputs report golem ndepend:all # Generate all stats for the project as HTML file and show in browser golem ndepend:critical # Generate critical fixes report from NDepend golem config:reset # Clears config files and replaces them with master copy golem config:init # Copies config files needed to correct places golem config:clear # Deletes copies of Windsor and Hibernate config files from projects golem recipes:list # List available community recipes on public server golem recipes:install # Install a community recipe for use in this project golem recipes:submit # Submit a recipe to the community golem system:update # Update to latest version of Rakish. Pass VERSION for specific version. golem iis:restart # Restart local IIS (Use IP=X.X.X.X for remote golem iis:backupconfigs # Backup IIS configuration files (into project folder here)
tobinharris/golem
402f9b3a90cb9bc67b9f99bbc6623b4c92d7659c
added README
diff --git a/Golem.sln b/Golem.sln index 1a7d524..0569a09 100644 --- a/Golem.sln +++ b/Golem.sln @@ -1,38 +1,43 @@  Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Core", "Golem.Core\Golem.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Test", "Golem.Test\Golem.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Runner", "Golem.Runner\Golem.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Build", "Golem.Build\Golem.Build.csproj", "{9F3F3B09-AB90-42E0-B099-81E8BB505954}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Readme", "Readme", "{5ADDCA30-41AD-4EFD-BC98-08C7924EADC7}" + ProjectSection(SolutionItems) = preProject + README.txt = README.txt + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.Build.0 = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.ActiveCfg = Release|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.Build.0 = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.Build.0 = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.Build.0 = Release|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.Build.0 = Debug|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.ActiveCfg = Release|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..d2a1c97 --- /dev/null +++ b/README.txt @@ -0,0 +1,115 @@ +====================================================================== +Golem .NET Build Tool +By Tobin Harris (http://www.tobinharris.com) +====================================================================== + += About = + +Golem is a simple build tool for Microsoft .NET 3.5. +It lets you specify build tasks in regular c# code, and then run them from the command line (see the list at the bottom of the file). +Inspired by Ruby Rake. + +Advantages include: + + * Create custom tasks and recipes in good old c# or VB.NET code. + * Flexible. Create tasks for any purpose (testing, build, deployment, nhibernate, db, documentation, code metrics, reporting etc) + * No learning new build languages or tools + * Can be run from the command line + * Quick and easy to write + * Share recipes between projects + * Share recipes with the community + += Build Recipes = + +If you've used a unit testing framework, then Golem code will be familiar. + +Just as NUnit has Test Fixtures and Tests, Golem has Build Recipes and Tasks. + +Here is a Golem recipe in c# code: + + // + //include this anywhere in your solution + // + + [Recipe(Description="Database Build Tasks")] + public class DbRecipe + { + [Task(Description="Drop the development database"] + public void Drop() + { + //some regular c# code drop the db + //...load and execute the SQL drop script + + Console.WriteLine("Database Schema Dropped"); + + } + [Task(Description="Create the development database") + public void Create() + { + //some regular c# code to create the database + //...load and execute the SQL create script + + Console.WriteLine("Database Schema Created"); + } + + [Task(Description="Drop, create and populat the development database", After=new[]{"Drop","Create"}) + public void Reset() + { + //some regular code to populate data (Drop and Create called automatically) + //...load and execute the insert SQL script + + Console.WriteLine("Sample Dev Data Loaded"); + } + } + +Build your solution, and then type this at the command line: + + cd c:\Code\FooBar + golem -T + +...which lists available build commands: + + Golem (Beta) 2008 + Your friendly executable .NET build tool. + + golem db:drop # Drop the development database + golem db:create # Create the development database + golem db:reset # Drop, create and populat the development database + +You could now type: + + > golem db:reet + +... to quickly drop, creat and populate your development database. Cool huh? + += The Sky is the Limit = + +Writing your own build tasks is cool, but you find it better to reuse ones already published in the community. +Watch out for some cool build tasks in the making... + + golem nhib:mappings # Lists NHibernate classes and associated tables + golem nhib:reset # Drops and recreates db objects for the current environment using NHibernate mapping + golem test:all # Runs all NUnit tests in the test solution + golem build:all # Runs MSBuild on the solution + golem swiss:guid # Generates a new GUID + golem swiss:secret # Generates a cryptographically secure secret. + golem mvc:routes # List ASP.NET MVC routes and controllers + golem mvc:scaffold # Creates an ASP.NET MVC controller and view with given name + golem mvc:checklinks # Checks for broken links in current running web site + golem stress:db # Runs custom stress test against dev DB and outputs report + golem stress:web # Runs custom stress test against web site and outputs report + golem ndepend:all # Generate all stats for the project as HTML file and show in browser + golem ndepend:critical # Generate critical fixes report from NDepend + golem config:reset # Clears config files and replaces them with master copy + golem config:init # Copies config files needed to correct places + golem config:clear # Deletes copies of Windsor and Hibernate config files from projects + golem recipes:list # List available community recipes on public server + golem recipes:install # Install a community recipe for use in this project + golem recipes:submit # Submit a recipe to the community + golem system:update # Update to latest version of Rakish. Pass VERSION for specific version. + golem iis:restart # Restart local IIS (Use IP=X.X.X.X for remote + golem iis:backupconfigs # Backup IIS configuration files (into project folder here) + + + +
tobinharris/golem
812d35ac117220d91a5e73f75ba9bb23672442d7
working on assembly loading
diff --git a/Golem.Core/Configuration.cs b/Golem.Core/Configuration.cs index 17fcdbb..ad80a82 100644 --- a/Golem.Core/Configuration.cs +++ b/Golem.Core/Configuration.cs @@ -1,81 +1,81 @@ using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace Golem.Core { public class Configuration { public static bool ConfigFileExists { get { return File.Exists(Environment.CurrentDirectory + "\\" + DEFAULT_FILE_NAME); } } public static readonly string DEFAULT_FILE_NAME = "golem.xml"; private FileInfo _file; private ConfigurationMemento _memento; public Configuration() { _memento = new ConfigurationMemento(); _file = new FileInfo(Environment.CurrentDirectory + "\\" + DEFAULT_FILE_NAME); if (_file.Exists) LoadFrom(_file); else CreateNew(_file); } public bool IsNew{ get; set;} /// <summary> /// Paths where DLLs or EXEs containing recipes are. /// Can be relative or absolute,and contain * wildcard /// </summary> - public List<string> RecipeSearchHints { get { return _memento.RecipeSearchHints; } } + public List<string> SearchPaths { get { return _memento.RecipeSearchHints; } } private void CreateNew(FileInfo file) { WriteFile(file); IsNew = true; } private void WriteFile(FileInfo file) { using(TextWriter writer = file.CreateText()) { var s = new XmlSerializer(typeof (ConfigurationMemento)); s.Serialize(writer,_memento); } } private void LoadFrom(FileInfo file) { IsNew = false; var s = new XmlSerializer(typeof(ConfigurationMemento)); using(var reader = file.OpenText()) { _memento = (ConfigurationMemento) s.Deserialize(reader); } } public void Save() { WriteFile(_file); } } public class ConfigurationMemento { public ConfigurationMemento() { RecipeSearchHints = new List<string>(); } public List<string> RecipeSearchHints { get; set; } } } \ No newline at end of file diff --git a/Golem.Core/RecipeCataloger.cs b/Golem.Core/RecipeCataloger.cs index 5a532a9..aee1e2a 100644 --- a/Golem.Core/RecipeCataloger.cs +++ b/Golem.Core/RecipeCataloger.cs @@ -1,237 +1,252 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; using Golem.Core; namespace Golem.Core { public class RecipeCatalogue { public RecipeCatalogue(List<LoadedAssemblyInfo> found) { } } /// <summary> /// /// </summary> public class RecipeCataloger { //loads assemblies //building tree of recipes //reflecting on types private readonly string[] _searchPaths; private readonly List<LoadedAssemblyInfo> _loadedAssemblies; public RecipeCataloger(params string[] searchPaths) { _searchPaths = searchPaths; _loadedAssemblies = new List<LoadedAssemblyInfo>(); } public ReadOnlyCollection<LoadedAssemblyInfo> LoadedAssemblies { get { return _loadedAssemblies.AsReadOnly(); } } /// <summary> /// Queries loaded assembly info to list all assemblies examined /// </summary> public ReadOnlyCollection<Assembly> AssembliesExamined { get { return (from la in _loadedAssemblies select la.Assembly).ToList().AsReadOnly(); } } /// <summary> /// Queries loaded assembly info to list the associated recipes with each /// </summary> public ReadOnlyCollection<Recipe> Recipes { get { return (from la in _loadedAssemblies from r in la.FoundRecipes select r).ToList().AsReadOnly(); } } /// <summary> /// Lists assemblies that contained recipes /// </summary> public List<LoadedAssemblyInfo> LoadedAssembliesContainingRecipes { get { return (from la in _loadedAssemblies where la.FoundRecipes.Count > 0 select la).ToList(); } } /// <summary> /// /// </summary> /// <returns></returns> public IList<Recipe> CatalogueRecipes() { var fileSearch = new FileSearch(_searchPaths); fileSearch.BuildFileList(); PreLoadAssembliesToPreventAssemblyNotFoundError( fileSearch.FoundAssemblyFiles.ToArray() ); ExtractRecipesFromPreLoadedAssemblies(); return Recipes.ToArray(); } private void PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] assemblyFiles) { foreach (var file in assemblyFiles) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail if( ! file.Name.StartsWith("Golem.Core") && ! LoadedAssemblies.Any(la=>la.File.FullName == file.FullName)) { - _loadedAssemblies.Add( - new LoadedAssemblyInfo - { - Assembly = Assembly.LoadFrom(file.FullName), - File = file - }); + try + { + var i = new LoadedAssemblyInfo + { + Assembly = Assembly.LoadFrom(file.FullName), + File = file + }; + _loadedAssemblies.Add(i); + } + catch (Exception e) + { + Console.WriteLine("Ooops: " + e.Message); + } } } private void ExtractRecipesFromPreLoadedAssemblies() { foreach(var la in LoadedAssemblies) - foreach (var type in la.Assembly.GetTypes()) - ExtractRecipesFromType(type, la); + try + { + foreach (var type in la.Assembly.GetTypes()) + ExtractRecipesFromType(type, la); + } + catch (ReflectionTypeLoadException e) + { +// foreach(var ex in e.LoaderExceptions) +// Console.WriteLine("Load Exception: " + ex.Message); + } } public RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } private void ExtractRecipesFromType(Type type, LoadedAssemblyInfo la) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //associate recipe with assembly la.FoundRecipes.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task task) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); task.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } } } \ No newline at end of file diff --git a/Golem.Runner/Program.cs b/Golem.Runner/Program.cs index e18af35..a9aa978 100644 --- a/Golem.Runner/Program.cs +++ b/Golem.Runner/Program.cs @@ -1,58 +1,96 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Golem.Core; using Golem.Core; namespace Golem.Runner { public class Program { public static void Main(string[] args) { - var finder = new RecipeCataloger(Environment.CurrentDirectory); - var found = finder.CatalogueRecipes(); + Console.WriteLine("Golem (Beta) 2008\nYour friendly executable .NET build tool. \n"); + IList<Recipe> found; + RecipeCataloger finder = BuildCatalog(out found); + if(args.Length > 0) { - if(args[0].ToLower() == "-t") + if(args[0] == "-T") { + ShowList(found); return; } + else if(args[0].ToLower() == "-?") + { + Console.WriteLine("Help: \n"); + Console.WriteLine("golem -T # List build tasks"); + Console.WriteLine("golem -? # Show this help"); + Console.WriteLine("golem -? # Show this help"); + return; + } var parts = args[0].Split(':'); var runner = new TaskRunner(finder); if(parts.Length == 2) runner.Run(parts[0],parts[1]); else - Console.WriteLine("Error: don't know what to do with that. \n\nTry: golem -t\n\n...to see commands."); + { + Console.WriteLine("Type golem -? for help, or try one of the following tasks:\n"); + ShowList(found); + } } else { - Console.WriteLine("Golem (Beta) - Your friendly executable .NET build tool."); + ShowList(found); } } + private static RecipeCataloger BuildCatalog(out IList<Recipe> found) + { + RecipeCataloger finder; + + var config = new Configuration(); + + if (config.SearchPaths.Count > 0) + finder = new RecipeCataloger(config.SearchPaths.ToArray()); + else + { + Console.WriteLine("Scanning directories for Build Recipes (could take a while)..."); + finder = new RecipeCataloger(Environment.CurrentDirectory); + } + + found = finder.CatalogueRecipes(); + + if(config.SearchPaths.Count == 0) + { + config.SearchPaths.AddRange(finder.LoadedAssemblies.Select(s=>s.File.FullName)); + config.Save(); + } + return finder; + } + private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { //Console.WriteLine("\n{0}\n",!String.IsNullOrEmpty(recipe.Description) ? recipe.Description : recipe.Name); foreach(var task in recipe.Tasks) { var start = "golem " + recipe.Name + ":" + task.Name; Console.WriteLine(start.PadRight(30) +"# " + task.Description); } } if (found.Count == 0) Console.WriteLine("No recipes found under {0}", new DirectoryInfo(Environment.CurrentDirectory).Name); } } } diff --git a/Golem.Test/FinderConfigurationFixture.cs b/Golem.Test/FinderConfigurationFixture.cs index a2f52c5..09bbb71 100644 --- a/Golem.Test/FinderConfigurationFixture.cs +++ b/Golem.Test/FinderConfigurationFixture.cs @@ -1,70 +1,70 @@ using System; using System.IO; using System.Linq; using Golem.Core; using NUnit.Framework; namespace Golem.Test { [TestFixture] public class FinderConfigurationFixture { [SetUp] public void Before_Each_Test() { if(File.Exists(Configuration.DEFAULT_FILE_NAME)) File.Delete(Configuration.DEFAULT_FILE_NAME); } [Test] public void Finder_Caches_Assemblies_Containing_Recipes() { var cataloger = new RecipeCataloger(Environment.CurrentDirectory); cataloger.CatalogueRecipes(); Assert.AreEqual(1, cataloger.LoadedAssembliesContainingRecipes.Count); } [Test] public void Can_Automatically_Generate_First_Config_File() { Assert.IsFalse(Configuration.ConfigFileExists); var config = new Configuration(); Assert.IsTrue(config.IsNew); Assert.IsTrue(Configuration.ConfigFileExists); var cataloger = new RecipeCataloger(Environment.CurrentDirectory); cataloger.CatalogueRecipes(); if(config.IsNew) - config.RecipeSearchHints.AddRange( + config.SearchPaths.AddRange( cataloger.LoadedAssembliesContainingRecipes.Select(la=>la.Assembly.FullName) ); config.Save(); var config2 = new Configuration(); Assert.IsFalse(config2.IsNew); - Assert.AreEqual(1, config2.RecipeSearchHints.Count); + Assert.AreEqual(1, config2.SearchPaths.Count); } [Test] public void Cataloger_Uses_Search_Locations() { var config = new Configuration(); var cataloger = new RecipeCataloger(Environment.CurrentDirectory); cataloger.CatalogueRecipes(); - config.RecipeSearchHints.AddRange(cataloger.LoadedAssembliesContainingRecipes.Select(la => la.File.FullName)); + config.SearchPaths.AddRange(cataloger.LoadedAssembliesContainingRecipes.Select(la => la.File.FullName)); Assert.Greater(cataloger.AssembliesExamined.Count, 1); - var cataloger2 = new RecipeCataloger(config.RecipeSearchHints.ToArray()); + var cataloger2 = new RecipeCataloger(config.SearchPaths.ToArray()); cataloger2.CatalogueRecipes(); Assert.AreEqual(1, cataloger2.AssembliesExamined.Count); } } } \ No newline at end of file
tobinharris/golem
251798e670381f986f35518d2a8bb94f35f87fbf
refactoring, renaming
diff --git a/Golem.Core/Configuration.cs b/Golem.Core/Configuration.cs index 9ae1455..17fcdbb 100644 --- a/Golem.Core/Configuration.cs +++ b/Golem.Core/Configuration.cs @@ -1,73 +1,81 @@ using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace Golem.Core { public class Configuration { - public static readonly string DefaultFileName = "golem.xml"; + public static bool ConfigFileExists + { + get + { + return File.Exists(Environment.CurrentDirectory + "\\" + DEFAULT_FILE_NAME); + } + } + public static readonly string DEFAULT_FILE_NAME = "golem.xml"; + private FileInfo _file; private ConfigurationMemento _memento; - + public Configuration() { _memento = new ConfigurationMemento(); - _file = new FileInfo(Environment.CurrentDirectory + "\\" + DefaultFileName); + _file = new FileInfo(Environment.CurrentDirectory + "\\" + DEFAULT_FILE_NAME); if (_file.Exists) LoadFrom(_file); else CreateNew(_file); } public bool IsNew{ get; set;} /// <summary> /// Paths where DLLs or EXEs containing recipes are. /// Can be relative or absolute,and contain * wildcard /// </summary> public List<string> RecipeSearchHints { get { return _memento.RecipeSearchHints; } } private void CreateNew(FileInfo file) { WriteFile(file); IsNew = true; } private void WriteFile(FileInfo file) { using(TextWriter writer = file.CreateText()) { var s = new XmlSerializer(typeof (ConfigurationMemento)); s.Serialize(writer,_memento); } } private void LoadFrom(FileInfo file) { IsNew = false; var s = new XmlSerializer(typeof(ConfigurationMemento)); using(var reader = file.OpenText()) { _memento = (ConfigurationMemento) s.Deserialize(reader); } } public void Save() { WriteFile(_file); } } public class ConfigurationMemento { public ConfigurationMemento() { RecipeSearchHints = new List<string>(); } public List<string> RecipeSearchHints { get; set; } } } \ No newline at end of file diff --git a/Golem.Core/AssemblySearch.cs b/Golem.Core/FileSearch.cs similarity index 78% rename from Golem.Core/AssemblySearch.cs rename to Golem.Core/FileSearch.cs index d1bc439..347de4d 100644 --- a/Golem.Core/AssemblySearch.cs +++ b/Golem.Core/FileSearch.cs @@ -1,52 +1,56 @@ using System; using System.Collections.Generic; using System.IO; namespace Golem.Core { - public class AssemblySearch + public class FileSearch { private string[] startDirs; public List<FileInfo> FoundAssemblyFiles = new List<FileInfo>(); - public AssemblySearch() + public FileSearch() { startDirs = new[] { Environment.CurrentDirectory }; } - public AssemblySearch(params string[] startDirs) + public FileSearch(params string[] startDirs) { this.startDirs = startDirs; - if (startDirs == null) - startDirs = new[]{Environment.CurrentDirectory}; } - public void Scan() + public void BuildFileList() { FoundAssemblyFiles.Clear(); foreach (var startDir in startDirs) { FileInfo[] dlls = FindFilesExcludingDuplicates(startDir); FoundAssemblyFiles.AddRange(dlls); } } private FileInfo[] FindFilesExcludingDuplicates(string startDir) { + //if a file, then return + var tmp = new FileInfo(startDir); + if( tmp.Exists ) + { + return new[]{tmp}; + } var found = new DirectoryInfo(startDir) .GetFiles("*.dll", SearchOption.AllDirectories); var valid = new List<FileInfo>(); foreach (var fileInfo in found) if (!fileInfo.Directory.FullName.Contains("\\obj\\") && ! FoundAssemblyFiles.Contains(fileInfo)) valid.Add(fileInfo); return valid.ToArray(); } } } \ No newline at end of file diff --git a/Golem.Core/Golem.Core.csproj b/Golem.Core/Golem.Core.csproj index 24bee74..beffffb 100644 --- a/Golem.Core/Golem.Core.csproj +++ b/Golem.Core/Golem.Core.csproj @@ -1,67 +1,68 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{267A8DF5-2B11-470E-8878-BE6E7244B713}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golem.Core</RootNamespace> <AssemblyName>Golem.Core</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Configuration.cs" /> - <Compile Include="AssemblySearch.cs" /> + <Compile Include="FileSearch.cs" /> + <Compile Include="LoadedAssemblyInfo.cs" /> <Compile Include="Locations.cs" /> <Compile Include="Recipe.cs" /> <Compile Include="Task.cs" /> <Compile Include="TaskAttribute.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RecipeAttribute.cs" /> - <Compile Include="RecipeSearch.cs" /> + <Compile Include="RecipeCataloger.cs" /> <Compile Include="TaskRunner.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Golem.Core/LoadedAssemblyInfo.cs b/Golem.Core/LoadedAssemblyInfo.cs new file mode 100644 index 0000000..37ec4de --- /dev/null +++ b/Golem.Core/LoadedAssemblyInfo.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using System.IO; +using System.Reflection; + +namespace Golem.Core +{ + public class LoadedAssemblyInfo + { + public Assembly Assembly { get; set; } + public FileInfo File { get; set; } + public List<Recipe> FoundRecipes{get; set;} + + public LoadedAssemblyInfo() + { + FoundRecipes = new List<Recipe>(); + } + } +} \ No newline at end of file diff --git a/Golem.Core/RecipeSearch.cs b/Golem.Core/RecipeCataloger.cs similarity index 71% rename from Golem.Core/RecipeSearch.cs rename to Golem.Core/RecipeCataloger.cs index 5f77b65..5a532a9 100644 --- a/Golem.Core/RecipeSearch.cs +++ b/Golem.Core/RecipeCataloger.cs @@ -1,224 +1,237 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; using Golem.Core; namespace Golem.Core { - public class LoadedAssembly + + public class RecipeCatalogue { - public Assembly Assembly { get; set; } - public FileInfo LoadedFrom { get; set; } - public List<Recipe> FoundRecipes{get; set;} - - public LoadedAssembly() + public RecipeCatalogue(List<LoadedAssemblyInfo> found) { - FoundRecipes = new List<Recipe>(); + } } /// <summary> /// /// </summary> - public class RecipeSearch + public class RecipeCataloger { - //scanning directories - //loading assemblies + //loads assemblies //building tree of recipes //reflecting on types - private readonly AssemblySearch assemblySearch; + private readonly string[] _searchPaths; + private readonly List<LoadedAssemblyInfo> _loadedAssemblies; - public RecipeSearch() + public RecipeCataloger(params string[] searchPaths) { - assemblySearch = new AssemblySearch(); + _searchPaths = searchPaths; + _loadedAssemblies = new List<LoadedAssemblyInfo>(); } - public RecipeSearch(params string[] searchLocations) + public ReadOnlyCollection<LoadedAssemblyInfo> LoadedAssemblies { get { return _loadedAssemblies.AsReadOnly(); } } + + + /// <summary> + /// Queries loaded assembly info to list all assemblies examined + /// </summary> + public ReadOnlyCollection<Assembly> AssembliesExamined { - assemblySearch = new AssemblySearch(searchLocations); + get + { + return (from la in _loadedAssemblies select la.Assembly).ToList().AsReadOnly(); + } } - public ReadOnlyCollection<Assembly> AssembliesExamined { get; private set; } - public List<Recipe> Recipes { get; private set; } - - public List<Assembly> RecipeAssemblies { get; private set; } - public List<FileInfo> FilesContainingRecipes = new List<FileInfo>(); + /// <summary> + /// Queries loaded assembly info to list the associated recipes with each + /// </summary> + public ReadOnlyCollection<Recipe> Recipes + { + get + { + return (from la in _loadedAssemblies from r in la.FoundRecipes select r).ToList().AsReadOnly(); + } + } + + /// <summary> + /// Lists assemblies that contained recipes + /// </summary> + public List<LoadedAssemblyInfo> LoadedAssembliesContainingRecipes + { + get + { + return (from la in _loadedAssemblies where la.FoundRecipes.Count > 0 select la).ToList(); + } + } - public List<LoadedAssembly> LoadedAssemblies = new List<LoadedAssembly>(); - public IList<Recipe> FindRecipesInFiles() + + /// <summary> + /// + /// </summary> + /// <returns></returns> + public IList<Recipe> CatalogueRecipes() { - - assemblySearch.Scan(); + var fileSearch = new FileSearch(_searchPaths); + fileSearch.BuildFileList(); + PreLoadAssembliesToPreventAssemblyNotFoundError( - assemblySearch.FoundAssemblyFiles.ToArray() + fileSearch.FoundAssemblyFiles.ToArray() ); - - ExtractAndFlag(); - - AssembliesExamined = (from la in LoadedAssemblies select la.Assembly).ToList().AsReadOnly(); - - Recipes = (from la in LoadedAssemblies from r in la.FoundRecipes select r).ToList(); - + ExtractRecipesFromPreLoadedAssemblies(); return Recipes.ToArray(); } private void PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] assemblyFiles) { foreach (var file in assemblyFiles) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail - if( ! file.Name.StartsWith("Golem.Core") && ! LoadedAssemblies.Any(la=>la.LoadedFrom.FullName == file.FullName)) + if( ! file.Name.StartsWith("Golem.Core") && ! LoadedAssemblies.Any(la=>la.File.FullName == file.FullName)) { - LoadedAssemblies.Add( - new LoadedAssembly + _loadedAssemblies.Add( + new LoadedAssemblyInfo { Assembly = Assembly.LoadFrom(file.FullName), - LoadedFrom = file + File = file }); } } - private void ExtractAndFlag() + private void ExtractRecipesFromPreLoadedAssemblies() { foreach(var la in LoadedAssemblies) foreach (var type in la.Assembly.GetTypes()) ExtractRecipesFromType(type, la); } public RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; - if(RecipeAssemblies == null) - RecipeAssemblies = new List<Assembly>(); - - if (! RecipeAssemblies.Contains(type.Assembly)) - RecipeAssemblies.Add(type.Assembly); + var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } - //TODO: ExtractRecipesFromType is Too long and - //TODO: too many IL Instructions - //TODO: Nesting is too deep - //TODO: Not enough comments - //TODO: Too many variables - // - private void ExtractRecipesFromType(Type type, LoadedAssembly la) + + private void ExtractRecipesFromType(Type type, LoadedAssemblyInfo la) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //associate recipe with assembly la.FoundRecipes.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } - private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task t) + private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task task) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); - t.DependsOnMethods.Add(dependee); + task.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } } } \ No newline at end of file diff --git a/Golem.Core/TaskRunner.cs b/Golem.Core/TaskRunner.cs index 13ab9f0..d8f73bb 100644 --- a/Golem.Core/TaskRunner.cs +++ b/Golem.Core/TaskRunner.cs @@ -1,125 +1,125 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; namespace Golem.Core { public class RecipeBase { public IList<Assembly> AllAssemblies = new List<Assembly>(); public IList<Recipe> AllRecipes = new List<Recipe>(); } public class TaskRunner { - private RecipeSearch search; + private RecipeCataloger cataloger; - public TaskRunner(RecipeSearch aSearch) + public TaskRunner(RecipeCataloger aCataloger) { - search = aSearch; + cataloger = aCataloger; } public void Run(Recipe recipe, Task task) { var recipeInstance = Activator.CreateInstance(recipe.Class); SetContextualInformationIfInheritsRecipeBase(recipeInstance); task.Method.Invoke(recipeInstance, null); } private void SetContextualInformationIfInheritsRecipeBase(object recipeInstance) { var tmpRecipe = recipeInstance as RecipeBase; if(tmpRecipe == null) return; - tmpRecipe.AllAssemblies = search.AssembliesExamined; - tmpRecipe.AllRecipes = search.Recipes; + tmpRecipe.AllAssemblies = cataloger.AssembliesExamined; + tmpRecipe.AllRecipes = cataloger.Recipes; } //TODO: Run is Too long //TODO: Nesting depth is too deep public void Run(string recipeName, string taskName) { - if(search.Recipes.Count==0) - search.FindRecipesInFiles(); + if(cataloger.Recipes.Count==0) + cataloger.CatalogueRecipes(); - foreach (var r in search.Recipes) + foreach (var r in cataloger.Recipes) { if(r.Name.ToLower() == recipeName.ToLower()) { foreach(var t in r.Tasks) { if(t.Name.ToLower() == taskName.ToLower()) { foreach(var methodInfo in t.DependsOnMethods) { Run(r, r.GetTaskForMethod(methodInfo)); } Run(r, t); return; } } } } } // public RunManifest BuildRunManifest(string recipeName, string taskName) // { // var manifest = new RunManifest(); -// var search = new RecipeSearch(); -// var found = search.FindRecipesInFiles(); +// var cataloger = new RecipeCataloger(); +// var found = cataloger.CatalogueRecipes(); // // foreach (var r in found) // { // if (r.Name.ToLower() == recipeName.ToLower()) // { // foreach (var t in r.Tasks) // { // if (t.Name.ToLower() == taskName.ToLower()) // { // foreach(var d in t.DependsOnMethods) // { // manifest.Add(null); // } // manifest.Add(t); // // } // } // } // } // return manifest; // } } public class RunManifest { public OrderedDictionary ToRun; public void Add(Task t) { if(! ToRun.Contains(t)) { ToRun.Add(t,new RunManifestItem{Task=t}); } } public RunManifest() { ToRun = new OrderedDictionary(); } public Task TaskAt(int position) { return (Task) ToRun[position]; } } public class RunManifestItem { public Task Task; public bool HasRun; } } \ No newline at end of file diff --git a/Golem.Runner/Program.cs b/Golem.Runner/Program.cs index 14ec5e8..e18af35 100644 --- a/Golem.Runner/Program.cs +++ b/Golem.Runner/Program.cs @@ -1,58 +1,58 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Golem.Core; using Golem.Core; namespace Golem.Runner { public class Program { public static void Main(string[] args) { - var finder = new RecipeSearch(Environment.CurrentDirectory); - var found = finder.FindRecipesInFiles(); + var finder = new RecipeCataloger(Environment.CurrentDirectory); + var found = finder.CatalogueRecipes(); if(args.Length > 0) { if(args[0].ToLower() == "-t") { ShowList(found); return; } var parts = args[0].Split(':'); var runner = new TaskRunner(finder); if(parts.Length == 2) runner.Run(parts[0],parts[1]); else Console.WriteLine("Error: don't know what to do with that. \n\nTry: golem -t\n\n...to see commands."); } else { Console.WriteLine("Golem (Beta) - Your friendly executable .NET build tool."); ShowList(found); } } private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { //Console.WriteLine("\n{0}\n",!String.IsNullOrEmpty(recipe.Description) ? recipe.Description : recipe.Name); foreach(var task in recipe.Tasks) { var start = "golem " + recipe.Name + ":" + task.Name; Console.WriteLine(start.PadRight(30) +"# " + task.Description); } } if (found.Count == 0) Console.WriteLine("No recipes found under {0}", new DirectoryInfo(Environment.CurrentDirectory).Name); } } } diff --git a/Golem.Test/FinderConfigurationFixture.cs b/Golem.Test/FinderConfigurationFixture.cs new file mode 100644 index 0000000..a2f52c5 --- /dev/null +++ b/Golem.Test/FinderConfigurationFixture.cs @@ -0,0 +1,70 @@ +using System; +using System.IO; +using System.Linq; +using Golem.Core; +using NUnit.Framework; + +namespace Golem.Test +{ + [TestFixture] + public class FinderConfigurationFixture + { + [SetUp] + public void Before_Each_Test() + { + if(File.Exists(Configuration.DEFAULT_FILE_NAME)) + File.Delete(Configuration.DEFAULT_FILE_NAME); + } + + + + [Test] + public void Finder_Caches_Assemblies_Containing_Recipes() + { + var cataloger = new RecipeCataloger(Environment.CurrentDirectory); + cataloger.CatalogueRecipes(); + Assert.AreEqual(1, cataloger.LoadedAssembliesContainingRecipes.Count); + } + + [Test] + public void Can_Automatically_Generate_First_Config_File() + { + Assert.IsFalse(Configuration.ConfigFileExists); + + var config = new Configuration(); + + Assert.IsTrue(config.IsNew); + Assert.IsTrue(Configuration.ConfigFileExists); + + var cataloger = new RecipeCataloger(Environment.CurrentDirectory); + cataloger.CatalogueRecipes(); + + if(config.IsNew) + config.RecipeSearchHints.AddRange( + cataloger.LoadedAssembliesContainingRecipes.Select(la=>la.Assembly.FullName) + ); + + config.Save(); + + var config2 = new Configuration(); + Assert.IsFalse(config2.IsNew); + Assert.AreEqual(1, config2.RecipeSearchHints.Count); + } + + [Test] + public void Cataloger_Uses_Search_Locations() + { + var config = new Configuration(); + var cataloger = new RecipeCataloger(Environment.CurrentDirectory); + cataloger.CatalogueRecipes(); + config.RecipeSearchHints.AddRange(cataloger.LoadedAssembliesContainingRecipes.Select(la => la.File.FullName)); + Assert.Greater(cataloger.AssembliesExamined.Count, 1); + + var cataloger2 = new RecipeCataloger(config.RecipeSearchHints.ToArray()); + cataloger2.CatalogueRecipes(); + Assert.AreEqual(1, cataloger2.AssembliesExamined.Count); + + } + + } +} \ No newline at end of file diff --git a/Golem.Test/Golem.Test.csproj b/Golem.Test/Golem.Test.csproj index 2d39424..5982907 100644 --- a/Golem.Test/Golem.Test.csproj +++ b/Golem.Test/Golem.Test.csproj @@ -1,70 +1,71 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golem.Test</RootNamespace> <AssemblyName>Golem.Test</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="nunit.framework, Version=2.4.7.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\..\Program Files\NUnit 2.4.7\bin\nunit.framework.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="DemoRecipe.cs" /> + <Compile Include="FinderConfigurationFixture.cs" /> <Compile Include="RecipeDiscoveryFixture.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Golem.Core\Golem.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> <Name>Golem.Core</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Golem.Test/RecipeDiscoveryFixture.cs b/Golem.Test/RecipeDiscoveryFixture.cs index f64b31a..da17f17 100644 --- a/Golem.Test/RecipeDiscoveryFixture.cs +++ b/Golem.Test/RecipeDiscoveryFixture.cs @@ -1,169 +1,122 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; using System.Text; using Golem.Core; using NUnit.Framework; using Golem.Core; namespace Golem.Test { [TestFixture] public class RecipeDiscoveryFixture { - private RecipeSearch search; + private RecipeCataloger cataloger; IList<Recipe> found; [SetUp] public void Before_Each_Test_Is_Run() { - search = new RecipeSearch(Environment.CurrentDirectory + "..\\..\\..\\..\\"); - found = search.FindRecipesInFiles(); + cataloger = new RecipeCataloger(Environment.CurrentDirectory + "..\\..\\..\\..\\"); + found = cataloger.CatalogueRecipes(); } [Test] public void Can_Discover_Recipes() { foreach(var r in found) { Console.WriteLine(r.Name); } Assert.AreEqual(4, found.Count); } [Test] public void Can_Discover_Recipe_Details() { var recipeInfo = found[1]; Assert.AreEqual("demo", recipeInfo.Name); } [Test] public void Can_Discover_Tasks_And_Details() { var recipeInfo = found[1]; Assert.AreEqual(3, recipeInfo.Tasks.Count); Assert.AreEqual("list", recipeInfo.Tasks[1].Name); Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); } [Test] public void Can_Run_Task() { var recipeInfo = found[1]; - var runner = new TaskRunner(search); + var runner = new TaskRunner(cataloger); runner.Run(recipeInfo, recipeInfo.Tasks[0]); Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } [Test] public void Can_Run_Task_By_Name() { - var runner = new TaskRunner(search); + var runner = new TaskRunner(cataloger); Locations.StartDirs = new[] {Environment.CurrentDirectory + "..\\..\\..\\..\\"}; runner.Run("demo","list"); Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); } [Test, Ignore] public void Can_Run_All_Default_Tasks() { Assert.Fail(); } [Test] public void Can_Set_Dependencies() { var demo2 = found[0]; Assert.AreEqual("demo2", demo2.Name); Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); } [Test] public void Functions_Are_Called_In_Correct_Order_With_Dependencies() { - var runner = new TaskRunner(search); + var runner = new TaskRunner(cataloger); runner.Run("demo2", "one"); } [Test] public void Can_Infer_Recipe_Category_And_Task_Name() { - var runner = new TaskRunner(search); + var runner = new TaskRunner(cataloger); runner.Run("demo3", "hello"); } [Test, Ignore] public void Can_Override_Current_Root_Folder() { Assert.Fail(); } [Test, Ignore] public void Can_Fetch_List_Of_Available_Recipes_From_Server() { Assert.Fail(); } [Test] public void Recipes_Inheriting_RecipeBase_Have_Contextual_Information() { var demo4 = found[3]; - var runner = new TaskRunner(search); + var runner = new TaskRunner(cataloger); runner.Run(demo4,demo4.Tasks[0]); } } - - [TestFixture] - public class FinderConfigurationFixture - { - [SetUp] - public void Before_Each_Test() - { - if(File.Exists(Configuration.DefaultFileName)) - File.Delete(Configuration.DefaultFileName); - } - - - - [Test] - public void Finder_Caches_Assemblies_Containing_Recipes() - { - var finder = new RecipeSearch(); - finder.FindRecipesInFiles(); - Assert.AreEqual(1, finder.RecipeAssemblies.Count); - } - - [Test] - public void Can_Automatically_Generate_First_Config_File() - { - Assert.IsFalse(File.Exists("\\" + Configuration.DefaultFileName)); - var config = new Configuration(); - Assert.IsTrue(config.IsNew); - Assert.IsFalse(File.Exists("\\" + Configuration.DefaultFileName)); - - var finder = new RecipeSearch(); - finder.FindRecipesInFiles(); - - if(config.IsNew) - config.RecipeSearchHints.AddRange((from la in finder.LoadedAssemblies where la.FoundRecipes.Count > 0 select la.LoadedFrom.FullName)); - - config.Save(); - - var config2 = new Configuration(); - Assert.IsFalse(config2.IsNew); - Assert.AreEqual(1, config2.RecipeSearchHints.Count); - - - } - - } }
tobinharris/golem
1814bddc4fe895bd26222cd1c09d46c6c52011db
added LoadedAssemblies
diff --git a/Golem.Core/RecipeSearch.cs b/Golem.Core/RecipeSearch.cs index 6f27692..5f77b65 100644 --- a/Golem.Core/RecipeSearch.cs +++ b/Golem.Core/RecipeSearch.cs @@ -1,228 +1,224 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; using Golem.Core; namespace Golem.Core { - + public class LoadedAssembly + { + public Assembly Assembly { get; set; } + public FileInfo LoadedFrom { get; set; } + public List<Recipe> FoundRecipes{get; set;} + + public LoadedAssembly() + { + FoundRecipes = new List<Recipe>(); + } + } + /// <summary> /// /// </summary> public class RecipeSearch { //scanning directories //loading assemblies //building tree of recipes //reflecting on types private readonly AssemblySearch assemblySearch; public RecipeSearch() { assemblySearch = new AssemblySearch(); } public RecipeSearch(params string[] searchLocations) { assemblySearch = new AssemblySearch(searchLocations); } public ReadOnlyCollection<Assembly> AssembliesExamined { get; private set; } - public ReadOnlyCollection<Recipe> Recipes { get; private set; } + public List<Recipe> Recipes { get; private set; } public List<Assembly> RecipeAssemblies { get; private set; } public List<FileInfo> FilesContainingRecipes = new List<FileInfo>(); - + + public List<LoadedAssembly> LoadedAssemblies = new List<LoadedAssembly>(); public IList<Recipe> FindRecipesInFiles() { - var recipeClasses = new List<Recipe>(); + assemblySearch.Scan(); - var loadedAssemblies = - PreLoadAssembliesToPreventAssemblyNotFoundError( - assemblySearch.FoundAssemblyFiles.ToArray() - ); + PreLoadAssembliesToPreventAssemblyNotFoundError( + assemblySearch.FoundAssemblyFiles.ToArray() + ); - foreach(var assembly in loadedAssemblies) - FindRecipesInAssembly(assembly, recipeClasses); + + ExtractAndFlag(); - AssembliesExamined = loadedAssemblies.AsReadOnly(); - Recipes = recipeClasses.AsReadOnly(); + AssembliesExamined = (from la in LoadedAssemblies select la.Assembly).ToList().AsReadOnly(); + Recipes = (from la in LoadedAssemblies from r in la.FoundRecipes select r).ToList(); - return recipeClasses.AsReadOnly(); + return Recipes.ToArray(); } - private List<Assembly> PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] dllFiles) - { - var loaded = new List<Assembly>(); - - foreach (var dllFile in dllFiles) + private void PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] assemblyFiles) + { + foreach (var file in assemblyFiles) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail - if( ! dllFile.Name.StartsWith("Golem.Core") - && ! FilesContainingRecipes.Any(file=>file.FullName == dllFile.FullName) - && ! loaded.Any(a=>a.CodeBase == dllFile.FullName) - ) + if( ! file.Name.StartsWith("Golem.Core") && ! LoadedAssemblies.Any(la=>la.LoadedFrom.FullName == file.FullName)) { - loaded.Add(Assembly.LoadFrom(dllFile.FullName)); - FilesContainingRecipes.Add(dllFile); + LoadedAssemblies.Add( + new LoadedAssembly + { + Assembly = Assembly.LoadFrom(file.FullName), + LoadedFrom = file + }); } - return loaded; + } - private void FindRecipesInAssembly(Assembly loaded, List<Recipe> recipeClasses) + private void ExtractAndFlag() { - try - { - var types = loaded.GetTypes(); - - foreach (var type in types) - FindRecipeInType(type, recipeClasses); - } - catch(ReflectionTypeLoadException ex) - { - foreach(var e in ex.LoaderExceptions) - { - //Console.WriteLine(e.Message); - } - - } - - + foreach(var la in LoadedAssemblies) + foreach (var type in la.Assembly.GetTypes()) + ExtractRecipesFromType(type, la); } public RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; if(RecipeAssemblies == null) RecipeAssemblies = new List<Assembly>(); if (! RecipeAssemblies.Contains(type.Assembly)) RecipeAssemblies.Add(type.Assembly); var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } - //TODO: FindRecipeInType is Too long and + //TODO: ExtractRecipesFromType is Too long and //TODO: too many IL Instructions //TODO: Nesting is too deep //TODO: Not enough comments //TODO: Too many variables // - private void FindRecipeInType(Type type, List<Recipe> manifest) + private void ExtractRecipesFromType(Type type, LoadedAssembly la) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); - //add to manifest - manifest.Add(recipe); + //associate recipe with assembly + la.FoundRecipes.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task t) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); t.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } } } \ No newline at end of file diff --git a/Golem.Test/RecipeDiscoveryFixture.cs b/Golem.Test/RecipeDiscoveryFixture.cs index 471c732..f64b31a 100644 --- a/Golem.Test/RecipeDiscoveryFixture.cs +++ b/Golem.Test/RecipeDiscoveryFixture.cs @@ -1,169 +1,169 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Golem.Core; using NUnit.Framework; using Golem.Core; namespace Golem.Test { [TestFixture] public class RecipeDiscoveryFixture { private RecipeSearch search; IList<Recipe> found; [SetUp] public void Before_Each_Test_Is_Run() { search = new RecipeSearch(Environment.CurrentDirectory + "..\\..\\..\\..\\"); found = search.FindRecipesInFiles(); } [Test] public void Can_Discover_Recipes() { foreach(var r in found) { Console.WriteLine(r.Name); } Assert.AreEqual(4, found.Count); } [Test] public void Can_Discover_Recipe_Details() { var recipeInfo = found[1]; Assert.AreEqual("demo", recipeInfo.Name); } [Test] public void Can_Discover_Tasks_And_Details() { var recipeInfo = found[1]; Assert.AreEqual(3, recipeInfo.Tasks.Count); Assert.AreEqual("list", recipeInfo.Tasks[1].Name); Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); } [Test] public void Can_Run_Task() { var recipeInfo = found[1]; var runner = new TaskRunner(search); runner.Run(recipeInfo, recipeInfo.Tasks[0]); Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } [Test] public void Can_Run_Task_By_Name() { var runner = new TaskRunner(search); Locations.StartDirs = new[] {Environment.CurrentDirectory + "..\\..\\..\\..\\"}; runner.Run("demo","list"); Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); } [Test, Ignore] public void Can_Run_All_Default_Tasks() { Assert.Fail(); } [Test] public void Can_Set_Dependencies() { var demo2 = found[0]; Assert.AreEqual("demo2", demo2.Name); Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); } [Test] public void Functions_Are_Called_In_Correct_Order_With_Dependencies() { var runner = new TaskRunner(search); runner.Run("demo2", "one"); } [Test] public void Can_Infer_Recipe_Category_And_Task_Name() { var runner = new TaskRunner(search); runner.Run("demo3", "hello"); } [Test, Ignore] public void Can_Override_Current_Root_Folder() { Assert.Fail(); } [Test, Ignore] public void Can_Fetch_List_Of_Available_Recipes_From_Server() { Assert.Fail(); } [Test] public void Recipes_Inheriting_RecipeBase_Have_Contextual_Information() { var demo4 = found[3]; var runner = new TaskRunner(search); runner.Run(demo4,demo4.Tasks[0]); } } [TestFixture] public class FinderConfigurationFixture { [SetUp] public void Before_Each_Test() { if(File.Exists(Configuration.DefaultFileName)) File.Delete(Configuration.DefaultFileName); } [Test] public void Finder_Caches_Assemblies_Containing_Recipes() { var finder = new RecipeSearch(); finder.FindRecipesInFiles(); Assert.AreEqual(1, finder.RecipeAssemblies.Count); } - [Test,Ignore] + [Test] public void Can_Automatically_Generate_First_Config_File() { Assert.IsFalse(File.Exists("\\" + Configuration.DefaultFileName)); var config = new Configuration(); Assert.IsTrue(config.IsNew); Assert.IsFalse(File.Exists("\\" + Configuration.DefaultFileName)); var finder = new RecipeSearch(); finder.FindRecipesInFiles(); if(config.IsNew) - config.RecipeSearchHints.AddRange(finder.FilesContainingRecipes.Select(s=>s.FullName)); + config.RecipeSearchHints.AddRange((from la in finder.LoadedAssemblies where la.FoundRecipes.Count > 0 select la.LoadedFrom.FullName)); config.Save(); var config2 = new Configuration(); Assert.IsFalse(config2.IsNew); Assert.AreEqual(1, config2.RecipeSearchHints.Count); } } }
tobinharris/golem
5551d82399f52569565520db8b1297edd0f8108f
making dll search separate from assembly search
diff --git a/Golem.Core/AssemblySearch.cs b/Golem.Core/AssemblySearch.cs new file mode 100644 index 0000000..d1bc439 --- /dev/null +++ b/Golem.Core/AssemblySearch.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace Golem.Core +{ + public class AssemblySearch + { + private string[] startDirs; + public List<FileInfo> FoundAssemblyFiles = new List<FileInfo>(); + + public AssemblySearch() + { + startDirs = new[] { Environment.CurrentDirectory }; + } + + public AssemblySearch(params string[] startDirs) + { + this.startDirs = startDirs; + if (startDirs == null) + startDirs = new[]{Environment.CurrentDirectory}; + } + + public void Scan() + { + FoundAssemblyFiles.Clear(); + + foreach (var startDir in startDirs) + { + FileInfo[] dlls = FindFilesExcludingDuplicates(startDir); + FoundAssemblyFiles.AddRange(dlls); + } + } + + private FileInfo[] FindFilesExcludingDuplicates(string startDir) + { + + var found = new DirectoryInfo(startDir) + .GetFiles("*.dll", SearchOption.AllDirectories); + + var valid = new List<FileInfo>(); + + foreach (var fileInfo in found) + if (!fileInfo.Directory.FullName.Contains("\\obj\\") && ! FoundAssemblyFiles.Contains(fileInfo)) + valid.Add(fileInfo); + + return valid.ToArray(); + + } + + } +} \ No newline at end of file diff --git a/Golem.Core/Golem.Core.csproj b/Golem.Core/Golem.Core.csproj index c4828ec..24bee74 100644 --- a/Golem.Core/Golem.Core.csproj +++ b/Golem.Core/Golem.Core.csproj @@ -1,66 +1,67 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{267A8DF5-2B11-470E-8878-BE6E7244B713}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golem.Core</RootNamespace> <AssemblyName>Golem.Core</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Configuration.cs" /> + <Compile Include="AssemblySearch.cs" /> <Compile Include="Locations.cs" /> <Compile Include="Recipe.cs" /> <Compile Include="Task.cs" /> <Compile Include="TaskAttribute.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RecipeAttribute.cs" /> - <Compile Include="RecipeFinder.cs" /> + <Compile Include="RecipeSearch.cs" /> <Compile Include="TaskRunner.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Golem.Core/Locations.cs b/Golem.Core/Locations.cs index 450b684..82705e9 100644 --- a/Golem.Core/Locations.cs +++ b/Golem.Core/Locations.cs @@ -1,8 +1,7 @@ namespace Golem.Core { public class Locations { - public static string[] StartDirs; } } \ No newline at end of file diff --git a/Golem.Core/RecipeSearch.cs b/Golem.Core/RecipeSearch.cs index 56029ca..6f27692 100644 --- a/Golem.Core/RecipeSearch.cs +++ b/Golem.Core/RecipeSearch.cs @@ -1,253 +1,228 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; using Golem.Core; namespace Golem.Core { + /// <summary> /// /// </summary> public class RecipeSearch { - //scanning directories //loading assemblies //building tree of recipes //reflecting on types - private string[] startDirs; - + private readonly AssemblySearch assemblySearch; + public RecipeSearch() { - this.startDirs = new string[]{Environment.CurrentDirectory}; + assemblySearch = new AssemblySearch(); } - - - public RecipeSearch(params string[] startDirs) : this() + public RecipeSearch(params string[] searchLocations) { - this.startDirs = startDirs; - - if(startDirs == null) - { - Locations.StartDirs = new string[] { Environment.CurrentDirectory }; - this.startDirs = Locations.StartDirs; - } - - + assemblySearch = new AssemblySearch(searchLocations); } - public ReadOnlyCollection<Assembly> AllAssembliesFound { get; private set; } - public ReadOnlyCollection<Recipe> AllRecipesFound { get; private set; } + public ReadOnlyCollection<Assembly> AssembliesExamined { get; private set; } + public ReadOnlyCollection<Recipe> Recipes { get; private set; } - public List<Assembly> AssembliesContainingRecipes { get; private set; } + public List<Assembly> RecipeAssemblies { get; private set; } public List<FileInfo> FilesContainingRecipes = new List<FileInfo>(); - //TODO: Too many variables + public IList<Recipe> FindRecipesInFiles() { var recipeClasses = new List<Recipe>(); - - //TODO: Fix this - Locations.StartDirs = startDirs; + assemblySearch.Scan(); + var loadedAssemblies = + PreLoadAssembliesToPreventAssemblyNotFoundError( + assemblySearch.FoundAssemblyFiles.ToArray() + ); - foreach (var startDir in startDirs) - { - FileInfo[] dlls = FindAllDlls(startDir); - var loadedAssemblies = PreLoadAssembliesToPreventAssemblyNotFoundError(dlls); - - foreach(var assembly in loadedAssemblies) - FindRecipesInAssembly(assembly, recipeClasses); + foreach(var assembly in loadedAssemblies) + FindRecipesInAssembly(assembly, recipeClasses); - AllAssembliesFound = loadedAssemblies.AsReadOnly(); - AllRecipesFound = recipeClasses.AsReadOnly(); - } + AssembliesExamined = loadedAssemblies.AsReadOnly(); + Recipes = recipeClasses.AsReadOnly(); + return recipeClasses.AsReadOnly(); } - private List<Assembly> PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] dllFile) + private List<Assembly> PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] dllFiles) { var loaded = new List<Assembly>(); - foreach (var dll in dllFile) + foreach (var dllFile in dllFiles) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail - if(! dll.Name.StartsWith("Golem.Core") && ! FilesContainingRecipes.Any(file=>file.FullName == dll.FullName)) + if( ! dllFile.Name.StartsWith("Golem.Core") + && ! FilesContainingRecipes.Any(file=>file.FullName == dllFile.FullName) + && ! loaded.Any(a=>a.CodeBase == dllFile.FullName) + ) { - loaded.Add(Assembly.LoadFrom(dll.FullName)); - FilesContainingRecipes.Add(dll); + loaded.Add(Assembly.LoadFrom(dllFile.FullName)); + FilesContainingRecipes.Add(dllFile); } return loaded; } private void FindRecipesInAssembly(Assembly loaded, List<Recipe> recipeClasses) { try { var types = loaded.GetTypes(); foreach (var type in types) FindRecipeInType(type, recipeClasses); } catch(ReflectionTypeLoadException ex) { foreach(var e in ex.LoaderExceptions) { //Console.WriteLine(e.Message); } } } public RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; - if(AssembliesContainingRecipes == null) - AssembliesContainingRecipes = new List<Assembly>(); + if(RecipeAssemblies == null) + RecipeAssemblies = new List<Assembly>(); - if (! AssembliesContainingRecipes.Contains(type.Assembly)) - AssembliesContainingRecipes.Add(type.Assembly); + if (! RecipeAssemblies.Contains(type.Assembly)) + RecipeAssemblies.Add(type.Assembly); var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } //TODO: FindRecipeInType is Too long and //TODO: too many IL Instructions //TODO: Nesting is too deep //TODO: Not enough comments //TODO: Too many variables // private void FindRecipeInType(Type type, List<Recipe> manifest) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //add to manifest manifest.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task t) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); t.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } - private FileInfo[] FindAllDlls(string startDir) - { - - var found = new DirectoryInfo(startDir) - .GetFiles("*.dll", SearchOption.AllDirectories); - - var deduped = new List<FileInfo>(); - - foreach(var fileInfo in found) - if(! fileInfo.Directory.FullName.Contains("\\obj\\")) - deduped.Add(fileInfo); - - return deduped.ToArray(); - - - } + } } \ No newline at end of file diff --git a/Golem.Core/TaskRunner.cs b/Golem.Core/TaskRunner.cs index b57abcd..13ab9f0 100644 --- a/Golem.Core/TaskRunner.cs +++ b/Golem.Core/TaskRunner.cs @@ -1,125 +1,125 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; namespace Golem.Core { public class RecipeBase { public IList<Assembly> AllAssemblies = new List<Assembly>(); public IList<Recipe> AllRecipes = new List<Recipe>(); } public class TaskRunner { - private RecipeFinder finder; + private RecipeSearch search; - public TaskRunner(RecipeFinder aFinder) + public TaskRunner(RecipeSearch aSearch) { - finder = aFinder; + search = aSearch; } public void Run(Recipe recipe, Task task) { var recipeInstance = Activator.CreateInstance(recipe.Class); SetContextualInformationIfInheritsRecipeBase(recipeInstance); task.Method.Invoke(recipeInstance, null); } private void SetContextualInformationIfInheritsRecipeBase(object recipeInstance) { var tmpRecipe = recipeInstance as RecipeBase; if(tmpRecipe == null) return; - tmpRecipe.AllAssemblies = finder.AllAssembliesFound; - tmpRecipe.AllRecipes = finder.AllRecipesFound; + tmpRecipe.AllAssemblies = search.AssembliesExamined; + tmpRecipe.AllRecipes = search.Recipes; } //TODO: Run is Too long //TODO: Nesting depth is too deep public void Run(string recipeName, string taskName) { - if(finder.AllRecipesFound.Count==0) - finder.FindRecipesInFiles(); + if(search.Recipes.Count==0) + search.FindRecipesInFiles(); - foreach (var r in finder.AllRecipesFound) + foreach (var r in search.Recipes) { if(r.Name.ToLower() == recipeName.ToLower()) { foreach(var t in r.Tasks) { if(t.Name.ToLower() == taskName.ToLower()) { foreach(var methodInfo in t.DependsOnMethods) { Run(r, r.GetTaskForMethod(methodInfo)); } Run(r, t); return; } } } } } // public RunManifest BuildRunManifest(string recipeName, string taskName) // { // var manifest = new RunManifest(); -// var finder = new RecipeFinder(); -// var found = finder.FindRecipesInFiles(); +// var search = new RecipeSearch(); +// var found = search.FindRecipesInFiles(); // // foreach (var r in found) // { // if (r.Name.ToLower() == recipeName.ToLower()) // { // foreach (var t in r.Tasks) // { // if (t.Name.ToLower() == taskName.ToLower()) // { // foreach(var d in t.DependsOnMethods) // { // manifest.Add(null); // } // manifest.Add(t); // // } // } // } // } // return manifest; // } } public class RunManifest { public OrderedDictionary ToRun; public void Add(Task t) { if(! ToRun.Contains(t)) { ToRun.Add(t,new RunManifestItem{Task=t}); } } public RunManifest() { ToRun = new OrderedDictionary(); } public Task TaskAt(int position) { return (Task) ToRun[position]; } } public class RunManifestItem { public Task Task; public bool HasRun; } } \ No newline at end of file diff --git a/Golem.Runner/Program.cs b/Golem.Runner/Program.cs index 53bbf7c..14ec5e8 100644 --- a/Golem.Runner/Program.cs +++ b/Golem.Runner/Program.cs @@ -1,58 +1,58 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Golem.Core; using Golem.Core; namespace Golem.Runner { public class Program { public static void Main(string[] args) { - var finder = new RecipeFinder(Environment.CurrentDirectory); + var finder = new RecipeSearch(Environment.CurrentDirectory); var found = finder.FindRecipesInFiles(); if(args.Length > 0) { if(args[0].ToLower() == "-t") { ShowList(found); return; } var parts = args[0].Split(':'); var runner = new TaskRunner(finder); if(parts.Length == 2) runner.Run(parts[0],parts[1]); else Console.WriteLine("Error: don't know what to do with that. \n\nTry: golem -t\n\n...to see commands."); } else { Console.WriteLine("Golem (Beta) - Your friendly executable .NET build tool."); ShowList(found); } } private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { //Console.WriteLine("\n{0}\n",!String.IsNullOrEmpty(recipe.Description) ? recipe.Description : recipe.Name); foreach(var task in recipe.Tasks) { var start = "golem " + recipe.Name + ":" + task.Name; Console.WriteLine(start.PadRight(30) +"# " + task.Description); } } if (found.Count == 0) Console.WriteLine("No recipes found under {0}", new DirectoryInfo(Environment.CurrentDirectory).Name); } } } diff --git a/Golem.Test/RecipeDiscoveryFixture.cs b/Golem.Test/RecipeDiscoveryFixture.cs index 99b6393..471c732 100644 --- a/Golem.Test/RecipeDiscoveryFixture.cs +++ b/Golem.Test/RecipeDiscoveryFixture.cs @@ -1,167 +1,169 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Text; using Golem.Core; using NUnit.Framework; using Golem.Core; namespace Golem.Test { [TestFixture] public class RecipeDiscoveryFixture { - private RecipeFinder finder; + private RecipeSearch search; IList<Recipe> found; [SetUp] public void Before_Each_Test_Is_Run() { - finder = new RecipeFinder(Environment.CurrentDirectory + "..\\..\\..\\..\\"); - found = finder.FindRecipesInFiles(); + search = new RecipeSearch(Environment.CurrentDirectory + "..\\..\\..\\..\\"); + found = search.FindRecipesInFiles(); } [Test] public void Can_Discover_Recipes() { foreach(var r in found) { Console.WriteLine(r.Name); } Assert.AreEqual(4, found.Count); } [Test] public void Can_Discover_Recipe_Details() { var recipeInfo = found[1]; Assert.AreEqual("demo", recipeInfo.Name); } [Test] public void Can_Discover_Tasks_And_Details() { var recipeInfo = found[1]; Assert.AreEqual(3, recipeInfo.Tasks.Count); Assert.AreEqual("list", recipeInfo.Tasks[1].Name); Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); } [Test] public void Can_Run_Task() { var recipeInfo = found[1]; - var runner = new TaskRunner(finder); + var runner = new TaskRunner(search); runner.Run(recipeInfo, recipeInfo.Tasks[0]); Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } [Test] public void Can_Run_Task_By_Name() { - var runner = new TaskRunner(finder); + + var runner = new TaskRunner(search); + Locations.StartDirs = new[] {Environment.CurrentDirectory + "..\\..\\..\\..\\"}; runner.Run("demo","list"); Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); - runner.Run("demo", "stats"); } [Test, Ignore] public void Can_Run_All_Default_Tasks() { Assert.Fail(); } [Test] public void Can_Set_Dependencies() { var demo2 = found[0]; Assert.AreEqual("demo2", demo2.Name); Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); } [Test] public void Functions_Are_Called_In_Correct_Order_With_Dependencies() { - var runner = new TaskRunner(finder); + var runner = new TaskRunner(search); runner.Run("demo2", "one"); } [Test] public void Can_Infer_Recipe_Category_And_Task_Name() { - var runner = new TaskRunner(finder); + var runner = new TaskRunner(search); runner.Run("demo3", "hello"); } [Test, Ignore] public void Can_Override_Current_Root_Folder() { Assert.Fail(); } [Test, Ignore] public void Can_Fetch_List_Of_Available_Recipes_From_Server() { Assert.Fail(); } [Test] public void Recipes_Inheriting_RecipeBase_Have_Contextual_Information() { var demo4 = found[3]; - var runner = new TaskRunner(finder); + var runner = new TaskRunner(search); runner.Run(demo4,demo4.Tasks[0]); } } [TestFixture] public class FinderConfigurationFixture { [SetUp] public void Before_Each_Test() { if(File.Exists(Configuration.DefaultFileName)) File.Delete(Configuration.DefaultFileName); } [Test] public void Finder_Caches_Assemblies_Containing_Recipes() { - var finder = new RecipeFinder(); + var finder = new RecipeSearch(); finder.FindRecipesInFiles(); - Assert.AreEqual(1, finder.AssembliesContainingRecipes.Count); + Assert.AreEqual(1, finder.RecipeAssemblies.Count); } - [Test] + [Test,Ignore] public void Can_Automatically_Generate_First_Config_File() { Assert.IsFalse(File.Exists("\\" + Configuration.DefaultFileName)); var config = new Configuration(); Assert.IsTrue(config.IsNew); Assert.IsFalse(File.Exists("\\" + Configuration.DefaultFileName)); - var finder = new RecipeFinder(); + var finder = new RecipeSearch(); finder.FindRecipesInFiles(); if(config.IsNew) config.RecipeSearchHints.AddRange(finder.FilesContainingRecipes.Select(s=>s.FullName)); config.Save(); var config2 = new Configuration(); Assert.IsFalse(config2.IsNew); Assert.AreEqual(1, config2.RecipeSearchHints.Count); } } }
tobinharris/golem
add1d4fa06cd01c2a8ac5e95d72dacc79290e686
working on cofig
diff --git a/Golem.Build/Golem.Build.csproj b/Golem.Build/Golem.Build.csproj index 9c91af7..800331d 100644 --- a/Golem.Build/Golem.Build.csproj +++ b/Golem.Build/Golem.Build.csproj @@ -1,67 +1,68 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{9F3F3B09-AB90-42E0-B099-81E8BB505954}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golum.Build</RootNamespace> <AssemblyName>Golum.Build</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <Content Include="Docs\Rake Examples.txt" /> + <Content Include="Docs\Welcome.htm" /> </ItemGroup> <ItemGroup> <Folder Include="Configs\" /> <Folder Include="Libs\" /> <Folder Include="Recipes\" /> <Folder Include="Resources\" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Golem.Build/Libs/YAML.NET.dll b/Golem.Build/Libs/YAML.NET.dll new file mode 100644 index 0000000..b455d97 Binary files /dev/null and b/Golem.Build/Libs/YAML.NET.dll differ diff --git a/Golem.Core/Configuration.cs b/Golem.Core/Configuration.cs new file mode 100644 index 0000000..9ae1455 --- /dev/null +++ b/Golem.Core/Configuration.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Xml.Serialization; + +namespace Golem.Core +{ + public class Configuration + { + public static readonly string DefaultFileName = "golem.xml"; + private FileInfo _file; + private ConfigurationMemento _memento; + + public Configuration() + { + _memento = new ConfigurationMemento(); + _file = new FileInfo(Environment.CurrentDirectory + "\\" + DefaultFileName); + + if (_file.Exists) + LoadFrom(_file); + else + CreateNew(_file); + + } + + public bool IsNew{ get; set;} + + /// <summary> + /// Paths where DLLs or EXEs containing recipes are. + /// Can be relative or absolute,and contain * wildcard + /// </summary> + public List<string> RecipeSearchHints { get { return _memento.RecipeSearchHints; } } + + private void CreateNew(FileInfo file) + { + WriteFile(file); + IsNew = true; + } + + private void WriteFile(FileInfo file) + { + using(TextWriter writer = file.CreateText()) + { + var s = new XmlSerializer(typeof (ConfigurationMemento)); + s.Serialize(writer,_memento); + } + } + + private void LoadFrom(FileInfo file) + { + IsNew = false; + var s = new XmlSerializer(typeof(ConfigurationMemento)); + using(var reader = file.OpenText()) + { + _memento = (ConfigurationMemento) s.Deserialize(reader); + } + } + + public void Save() + { + WriteFile(_file); + } + } + + public class ConfigurationMemento + { + public ConfigurationMemento() + { + RecipeSearchHints = new List<string>(); + } + public List<string> RecipeSearchHints { get; set; } + } +} \ No newline at end of file diff --git a/Golem.Core/Golem.Core.csproj b/Golem.Core/Golem.Core.csproj index 144c282..c4828ec 100644 --- a/Golem.Core/Golem.Core.csproj +++ b/Golem.Core/Golem.Core.csproj @@ -1,65 +1,66 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{267A8DF5-2B11-470E-8878-BE6E7244B713}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golem.Core</RootNamespace> <AssemblyName>Golem.Core</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> + <Compile Include="Configuration.cs" /> <Compile Include="Locations.cs" /> <Compile Include="Recipe.cs" /> <Compile Include="Task.cs" /> <Compile Include="TaskAttribute.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RecipeAttribute.cs" /> <Compile Include="RecipeFinder.cs" /> <Compile Include="TaskRunner.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Golem.Core/RecipeFinder.cs b/Golem.Core/RecipeFinder.cs index 8a0e60c..5958f27 100644 --- a/Golem.Core/RecipeFinder.cs +++ b/Golem.Core/RecipeFinder.cs @@ -1,240 +1,253 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; using Golem.Core; namespace Golem.Core -{ - +{ /// <summary> /// /// </summary> public class RecipeFinder { //scanning directories //loading assemblies //building tree of recipes //reflecting on types private string[] startDirs; public RecipeFinder() { + this.startDirs = new string[]{Environment.CurrentDirectory}; } + + public RecipeFinder(params string[] startDirs) : this() { this.startDirs = startDirs; if(startDirs == null) { Locations.StartDirs = new string[] { Environment.CurrentDirectory }; this.startDirs = Locations.StartDirs; } } public ReadOnlyCollection<Assembly> AllAssembliesFound { get; private set; } public ReadOnlyCollection<Recipe> AllRecipesFound { get; private set; } + + public List<Assembly> AssembliesContainingRecipes { get; private set; } + public List<FileInfo> FilesContainingRecipes = new List<FileInfo>(); //TODO: Too many variables public IList<Recipe> FindRecipesInFiles() { var recipeClasses = new List<Recipe>(); //TODO: Fix this Locations.StartDirs = startDirs; foreach (var startDir in startDirs) { FileInfo[] dlls = FindAllDlls(startDir); var loadedAssemblies = PreLoadAssembliesToPreventAssemblyNotFoundError(dlls); foreach(var assembly in loadedAssemblies) FindRecipesInAssembly(assembly, recipeClasses); AllAssembliesFound = loadedAssemblies.AsReadOnly(); AllRecipesFound = recipeClasses.AsReadOnly(); - - - } return recipeClasses.AsReadOnly(); } + + private List<Assembly> PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] dllFile) { var loaded = new List<Assembly>(); foreach (var dll in dllFile) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail - if(! dll.Name.StartsWith("Golem.Core")) + if(! dll.Name.StartsWith("Golem.Core") && ! FilesContainingRecipes.Any(file=>file.FullName == dll.FullName)) + { loaded.Add(Assembly.LoadFrom(dll.FullName)); + FilesContainingRecipes.Add(dll); + } return loaded; } - private static void FindRecipesInAssembly(Assembly loaded, List<Recipe> recipeClasses) + private void FindRecipesInAssembly(Assembly loaded, List<Recipe> recipeClasses) { try { var types = loaded.GetTypes(); foreach (var type in types) FindRecipeInType(type, recipeClasses); } catch(ReflectionTypeLoadException ex) { foreach(var e in ex.LoaderExceptions) { //Console.WriteLine(e.Message); } } } - public static RecipeAttribute GetRecipeAttributeOrNull(Type type) + public RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; + if(AssembliesContainingRecipes == null) + AssembliesContainingRecipes = new List<Assembly>(); + + if (! AssembliesContainingRecipes.Contains(type.Assembly)) + AssembliesContainingRecipes.Add(type.Assembly); + var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } //TODO: FindRecipeInType is Too long and //TODO: too many IL Instructions //TODO: Nesting is too deep //TODO: Not enough comments //TODO: Too many variables // - private static void FindRecipeInType(Type type, List<Recipe> manifest) + private void FindRecipeInType(Type type, List<Recipe> manifest) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //add to manifest manifest.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task t) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); t.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } private FileInfo[] FindAllDlls(string startDir) { var found = new DirectoryInfo(startDir) .GetFiles("*.dll", SearchOption.AllDirectories); var deduped = new List<FileInfo>(); foreach(var fileInfo in found) if(! fileInfo.Directory.FullName.Contains("\\obj\\")) deduped.Add(fileInfo); return deduped.ToArray(); } } } \ No newline at end of file diff --git a/Golem.Core/TaskRunner.cs b/Golem.Core/TaskRunner.cs index 8a6fdf0..b57abcd 100644 --- a/Golem.Core/TaskRunner.cs +++ b/Golem.Core/TaskRunner.cs @@ -1,124 +1,125 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; namespace Golem.Core { public class RecipeBase { public IList<Assembly> AllAssemblies = new List<Assembly>(); public IList<Recipe> AllRecipes = new List<Recipe>(); } public class TaskRunner { private RecipeFinder finder; public TaskRunner(RecipeFinder aFinder) { finder = aFinder; } public void Run(Recipe recipe, Task task) { var recipeInstance = Activator.CreateInstance(recipe.Class); SetContextualInformationIfInheritsRecipeBase(recipeInstance); task.Method.Invoke(recipeInstance, null); } private void SetContextualInformationIfInheritsRecipeBase(object recipeInstance) { var tmpRecipe = recipeInstance as RecipeBase; if(tmpRecipe == null) return; tmpRecipe.AllAssemblies = finder.AllAssembliesFound; tmpRecipe.AllRecipes = finder.AllRecipesFound; } //TODO: Run is Too long //TODO: Nesting depth is too deep public void Run(string recipeName, string taskName) { - var found = finder.FindRecipesInFiles(); - - foreach(var r in found) + if(finder.AllRecipesFound.Count==0) + finder.FindRecipesInFiles(); + + foreach (var r in finder.AllRecipesFound) { if(r.Name.ToLower() == recipeName.ToLower()) { foreach(var t in r.Tasks) { if(t.Name.ToLower() == taskName.ToLower()) { foreach(var methodInfo in t.DependsOnMethods) { Run(r, r.GetTaskForMethod(methodInfo)); } Run(r, t); return; } } } } } // public RunManifest BuildRunManifest(string recipeName, string taskName) // { // var manifest = new RunManifest(); // var finder = new RecipeFinder(); // var found = finder.FindRecipesInFiles(); // // foreach (var r in found) // { // if (r.Name.ToLower() == recipeName.ToLower()) // { // foreach (var t in r.Tasks) // { // if (t.Name.ToLower() == taskName.ToLower()) // { // foreach(var d in t.DependsOnMethods) // { // manifest.Add(null); // } // manifest.Add(t); // // } // } // } // } // return manifest; // } } public class RunManifest { public OrderedDictionary ToRun; public void Add(Task t) { if(! ToRun.Contains(t)) { ToRun.Add(t,new RunManifestItem{Task=t}); } } public RunManifest() { ToRun = new OrderedDictionary(); } public Task TaskAt(int position) { return (Task) ToRun[position]; } } public class RunManifestItem { public Task Task; public bool HasRun; } } \ No newline at end of file diff --git a/Golem.Test/RecipeDiscoveryFixture.cs b/Golem.Test/RecipeDiscoveryFixture.cs index 1a376fa..99b6393 100644 --- a/Golem.Test/RecipeDiscoveryFixture.cs +++ b/Golem.Test/RecipeDiscoveryFixture.cs @@ -1,121 +1,167 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using Golem.Core; using NUnit.Framework; using Golem.Core; namespace Golem.Test { [TestFixture] public class RecipeDiscoveryFixture { private RecipeFinder finder; IList<Recipe> found; [SetUp] public void Before_Each_Test_Is_Run() { finder = new RecipeFinder(Environment.CurrentDirectory + "..\\..\\..\\..\\"); found = finder.FindRecipesInFiles(); } [Test] public void Can_Discover_Recipes() { foreach(var r in found) { Console.WriteLine(r.Name); } Assert.AreEqual(4, found.Count); } [Test] public void Can_Discover_Recipe_Details() { var recipeInfo = found[1]; Assert.AreEqual("demo", recipeInfo.Name); } [Test] public void Can_Discover_Tasks_And_Details() { var recipeInfo = found[1]; Assert.AreEqual(3, recipeInfo.Tasks.Count); Assert.AreEqual("list", recipeInfo.Tasks[1].Name); Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); } [Test] public void Can_Run_Task() { var recipeInfo = found[1]; var runner = new TaskRunner(finder); runner.Run(recipeInfo, recipeInfo.Tasks[0]); Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } [Test] public void Can_Run_Task_By_Name() { var runner = new TaskRunner(finder); runner.Run("demo","list"); Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); runner.Run("demo", "stats"); } [Test, Ignore] public void Can_Run_All_Default_Tasks() { Assert.Fail(); } [Test] public void Can_Set_Dependencies() { var demo2 = found[0]; Assert.AreEqual("demo2", demo2.Name); Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); } [Test] public void Functions_Are_Called_In_Correct_Order_With_Dependencies() { var runner = new TaskRunner(finder); runner.Run("demo2", "one"); } [Test] public void Can_Infer_Recipe_Category_And_Task_Name() { var runner = new TaskRunner(finder); runner.Run("demo3", "hello"); } [Test, Ignore] public void Can_Override_Current_Root_Folder() { Assert.Fail(); } [Test, Ignore] public void Can_Fetch_List_Of_Available_Recipes_From_Server() { Assert.Fail(); } [Test] public void Recipes_Inheriting_RecipeBase_Have_Contextual_Information() { var demo4 = found[3]; var runner = new TaskRunner(finder); runner.Run(demo4,demo4.Tasks[0]); } } + + [TestFixture] + public class FinderConfigurationFixture + { + [SetUp] + public void Before_Each_Test() + { + if(File.Exists(Configuration.DefaultFileName)) + File.Delete(Configuration.DefaultFileName); + } + + + + [Test] + public void Finder_Caches_Assemblies_Containing_Recipes() + { + var finder = new RecipeFinder(); + finder.FindRecipesInFiles(); + Assert.AreEqual(1, finder.AssembliesContainingRecipes.Count); + } + + [Test] + public void Can_Automatically_Generate_First_Config_File() + { + Assert.IsFalse(File.Exists("\\" + Configuration.DefaultFileName)); + var config = new Configuration(); + Assert.IsTrue(config.IsNew); + Assert.IsFalse(File.Exists("\\" + Configuration.DefaultFileName)); + + var finder = new RecipeFinder(); + finder.FindRecipesInFiles(); + + if(config.IsNew) + config.RecipeSearchHints.AddRange(finder.FilesContainingRecipes.Select(s=>s.FullName)); + + config.Save(); + + var config2 = new Configuration(); + Assert.IsFalse(config2.IsNew); + Assert.AreEqual(1, config2.RecipeSearchHints.Count); + + + } + + } } diff --git a/Golem.sln b/Golem.sln index a59fee5..1a7d524 100644 --- a/Golem.sln +++ b/Golem.sln @@ -1,43 +1,38 @@  Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Core", "Golem.Core\Golem.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Test", "Golem.Test\Golem.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Runner", "Golem.Runner\Golem.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Build", "Golem.Build\Golem.Build.csproj", "{9F3F3B09-AB90-42E0-B099-81E8BB505954}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{2CFC9ECF-8ED3-4B98-8C5B-7FA5580F34C3}" - ProjectSection(SolutionItems) = preProject - Welcome.htm = Welcome.htm - EndProjectSection -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.Build.0 = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.ActiveCfg = Release|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.Build.0 = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.Build.0 = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.Build.0 = Release|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.Build.0 = Debug|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.ActiveCfg = Release|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
tobinharris/golem
978f2065b9601bb4d85273587a9234c41fe9b7f4
tidy up
diff --git a/Golum.Build/Docs/Rake Examples.txt b/Golem.Build/Docs/Rake Examples.txt similarity index 100% rename from Golum.Build/Docs/Rake Examples.txt rename to Golem.Build/Docs/Rake Examples.txt diff --git a/Golem.Build/Docs/Welcome.htm b/Golem.Build/Docs/Welcome.htm new file mode 100644 index 0000000..2ea2da6 --- /dev/null +++ b/Golem.Build/Docs/Welcome.htm @@ -0,0 +1,9 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" > +<head> + <title>Untitled Page</title> +</head> +<body> + +</body> +</html> diff --git a/Golum.Build/Golum.Build.csproj b/Golem.Build/Golem.Build.csproj similarity index 100% rename from Golum.Build/Golum.Build.csproj rename to Golem.Build/Golem.Build.csproj diff --git a/Golum.Build/Properties/AssemblyInfo.cs b/Golem.Build/Properties/AssemblyInfo.cs similarity index 100% rename from Golum.Build/Properties/AssemblyInfo.cs rename to Golem.Build/Properties/AssemblyInfo.cs diff --git a/Golem.sln b/Golem.sln index 25910bd..a59fee5 100644 --- a/Golem.sln +++ b/Golem.sln @@ -1,38 +1,43 @@  Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Core", "Golem.Core\Golem.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Test", "Golem.Test\Golem.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Runner", "Golem.Runner\Golem.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golum.Build", "Golum.Build\Golum.Build.csproj", "{9F3F3B09-AB90-42E0-B099-81E8BB505954}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Build", "Golem.Build\Golem.Build.csproj", "{9F3F3B09-AB90-42E0-B099-81E8BB505954}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{2CFC9ECF-8ED3-4B98-8C5B-7FA5580F34C3}" + ProjectSection(SolutionItems) = preProject + Welcome.htm = Welcome.htm + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.Build.0 = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.ActiveCfg = Release|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.Build.0 = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.Build.0 = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.Build.0 = Release|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.Build.0 = Debug|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.ActiveCfg = Release|Any CPU {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Rake.txt b/Rake.txt deleted file mode 100644 index 2aacc41..0000000 --- a/Rake.txt +++ /dev/null @@ -1,114 +0,0 @@ - --classic-namespace (-C) - Put Task and FileTask in the top level namespace - --describe (-D) - Describe the tasks (matching optional PATTERN), then exit. - --dry-run (-n) - Do a dry run without executing actions. - --help (-h) - 0 - --libdir=LIBDIR (-I) - Include LIBDIR in the search path for required modules. - --nosearch (-N) - Do not search parent directories for the Rakefile. - --prereqs (-P) - Display the tasks and dependencies, then exit. - --quiet (-q) - Do not log messages to standard output. - --rakefile (-f) - Use FILE as the rakefile. - --rakelibdir=RAKELIBDIR (-R) - Auto-import any .rake files in RAKELIBDIR. (default is 'rakelib') - --require=MODULE (-r) - Require MODULE before executing rakefile. - --silent (-s) - Like --quiet, but also suppresses the 'in directory' announcement. - --tasks (-T) - Display the tasks (matching optional PATTERN) with descriptions, then exit. - --trace (-t) - Turn on invoke/execute tracing, enable full backtrace. - --verbose (-v) - Log message to standard output (default). - --version (-V) - Display the program version. - - -rake db:abort_if_pending_migrations # Raises an error if there are pending... -rake db:charset # Retrieves the charset for the curren... -rake db:collation # Retrieves the collation for the curr... -rake db:create # Create the database defined in confi... -rake db:create:all # Create all the local databases defin... -rake db:drop # Drops the database for the current R... -rake db:drop:all # Drops all the local databases define... -rake db:fixtures:identify # Search for a fixture given a LABEL o... -rake db:fixtures:load # Load fixtures into the current envir... -rake db:migrate # Migrate the database through scripts... -rake db:migrate:redo # Rollbacks the database one migration... -rake db:migrate:reset # Resets your database using your migr... -rake db:reset # Drops and recreates the database fro... -rake db:rollback # Rolls the schema back to the previou... -rake db:schema:dump # Create a db/schema.rb file that can ... -rake db:schema:load # Load a schema.rb file into the database -rake db:sessions:clear # Clear the sessions table -rake db:sessions:create # Creates a sessions migration for use... -rake db:structure:dump # Dump the database structure to a SQL... -rake db:test:clone # Recreate the test database from the ... -rake db:test:clone_structure # Recreate the test databases from the... -rake db:test:prepare # Prepare the test database and load t... -rake db:test:purge # Empty the test database -rake db:version # Retrieves the current schema version... -rake deprecated # Checks your app and gently warns you... -rake doc:app # Build the app HTML Files -rake doc:clobber_app # Remove rdoc products -rake doc:clobber_plugins # Remove plugin documentation -rake doc:clobber_rails # Remove rdoc products -rake doc:plugins # Generate documentation for all insta... -rake doc:rails # Build the rails HTML Files -rake doc:reapp # Force a rebuild of the RDOC files -rake doc:rerails # Force a rebuild of the RDOC files -rake fckeditor:download # Update the FCKEditor code to the lat... -rake fckeditor:install # Install the FCKEditor components -rake log:clear # Truncates all *.log files in log/ to... -rake notes # Enumerate all annotations -rake notes:fixme # Enumerate all FIXME annotations -rake notes:optimize # Enumerate all OPTIMIZE annotations -rake notes:todo # Enumerate all TODO annotations -rake rails:freeze:edge # Lock to latest Edge Rails or a speci... -rake rails:freeze:gems # Lock this application to the current... -rake rails:unfreeze # Unlock this application from freeze ... -rake rails:update # Update both configs, scripts and pub... -rake rails:update:configs # Update config/boot.rb from your curr... -rake rails:update:javascripts # Update your javascripts from your cu... -rake rails:update:scripts # Add new scripts to the application s... -rake routes # Print out all defined routes in matc... -rake secret # Generate a crytographically secure s... -rake spec # Run all specs in spec directory (exc... -rake spec:clobber_rcov # Remove rcov products for rcov -rake spec:controllers # Run the specs under spec/controllers -rake spec:db:fixtures:load # Load fixtures (from spec/fixtures) i... -rake spec:doc # Print Specdoc for all specs (excludi... -rake spec:helpers # Run the specs under spec/helpers -rake spec:lib # Run the specs under spec/lib -rake spec:models # Run the specs under spec/models -rake spec:plugin_doc # Print Specdoc for all plugin specs -rake spec:plugins # Run the specs under vendor/plugins (... -rake spec:plugins:rspec_on_rails # Runs the examples for rspec_on_rails -rake spec:rcov # Run all specs in spec directory with... -rake spec:server:restart # reload spec_server. -rake spec:server:start # start spec_server. -rake spec:server:stop # stop spec_server. -rake spec:translate # Translate/upgrade specs using the bu... -rake spec:views # Run the specs under spec/views -rake stats # Report code statistics (KLOCs, etc) ... -rake test # Test all units and functionals -rake test:functionals # Run tests for functionalsdb:test:pre... -rake test:integration # Run tests for integrationdb:test:pre... -rake test:plugins # Run tests for pluginsenvironment / R... -rake test:recent # Run tests for recentdb:test:prepare ... -rake test:uncommitted # Run tests for uncommitteddb:test:pre... -rake test:units # Run tests for unitsdb:test:prepare /... -rake tmp:cache:clear # Clears all files and directories in ... -rake tmp:clear # Clear session, cache, and socket fil... -rake tmp:create # Creates tmp directories for sessions... -rake tmp:pids:clear # Clears all files in tmp/pids -rake tmp:sessions:clear # Clears all files in tmp/sessions -rake tmp:sockets:clear # Clears all files in tmp/sockets
tobinharris/golem
8173d3141478c283a7b49ffea70b3c95c79452e1
adding build project
diff --git a/Golem.Runner/Program.cs b/Golem.Runner/Program.cs index 71acd27..53bbf7c 100644 --- a/Golem.Runner/Program.cs +++ b/Golem.Runner/Program.cs @@ -1,53 +1,58 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using Golem.Core; using Golem.Core; namespace Golem.Runner { public class Program { public static void Main(string[] args) { var finder = new RecipeFinder(Environment.CurrentDirectory); var found = finder.FindRecipesInFiles(); if(args.Length > 0) { if(args[0].ToLower() == "-t") { ShowList(found); return; } var parts = args[0].Split(':'); var runner = new TaskRunner(finder); if(parts.Length == 2) runner.Run(parts[0],parts[1]); else Console.WriteLine("Error: don't know what to do with that. \n\nTry: golem -t\n\n...to see commands."); } else { + Console.WriteLine("Golem (Beta) - Your friendly executable .NET build tool."); ShowList(found); } } private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { //Console.WriteLine("\n{0}\n",!String.IsNullOrEmpty(recipe.Description) ? recipe.Description : recipe.Name); foreach(var task in recipe.Tasks) { var start = "golem " + recipe.Name + ":" + task.Name; Console.WriteLine(start.PadRight(30) +"# " + task.Description); } } + + if (found.Count == 0) + Console.WriteLine("No recipes found under {0}", new DirectoryInfo(Environment.CurrentDirectory).Name); } } } diff --git a/Golem.sln b/Golem.sln index 242efab..25910bd 100644 --- a/Golem.sln +++ b/Golem.sln @@ -1,39 +1,38 @@  Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Core", "Golem.Core\Golem.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Test", "Golem.Test\Golem.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External Libs", "External Libs", "{74E13096-F694-40BE-9F9A-D4EFD2A9E4AD}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Runner", "Golem.Runner\Golem.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{41F9F9EF-3D0E-4A05-A033-7DD77D040A1F}" - ProjectSection(SolutionItems) = preProject - Rake.txt = Rake.txt - EndProjectSection +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golum.Build", "Golum.Build\Golum.Build.csproj", "{9F3F3B09-AB90-42E0-B099-81E8BB505954}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.Build.0 = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.ActiveCfg = Release|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.Build.0 = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.Build.0 = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.Build.0 = Release|Any CPU + {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9F3F3B09-AB90-42E0-B099-81E8BB505954}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Golum.Build/Docs/Rake Examples.txt b/Golum.Build/Docs/Rake Examples.txt new file mode 100644 index 0000000..2aacc41 --- /dev/null +++ b/Golum.Build/Docs/Rake Examples.txt @@ -0,0 +1,114 @@ + --classic-namespace (-C) + Put Task and FileTask in the top level namespace + --describe (-D) + Describe the tasks (matching optional PATTERN), then exit. + --dry-run (-n) + Do a dry run without executing actions. + --help (-h) + 0 + --libdir=LIBDIR (-I) + Include LIBDIR in the search path for required modules. + --nosearch (-N) + Do not search parent directories for the Rakefile. + --prereqs (-P) + Display the tasks and dependencies, then exit. + --quiet (-q) + Do not log messages to standard output. + --rakefile (-f) + Use FILE as the rakefile. + --rakelibdir=RAKELIBDIR (-R) + Auto-import any .rake files in RAKELIBDIR. (default is 'rakelib') + --require=MODULE (-r) + Require MODULE before executing rakefile. + --silent (-s) + Like --quiet, but also suppresses the 'in directory' announcement. + --tasks (-T) + Display the tasks (matching optional PATTERN) with descriptions, then exit. + --trace (-t) + Turn on invoke/execute tracing, enable full backtrace. + --verbose (-v) + Log message to standard output (default). + --version (-V) + Display the program version. + + +rake db:abort_if_pending_migrations # Raises an error if there are pending... +rake db:charset # Retrieves the charset for the curren... +rake db:collation # Retrieves the collation for the curr... +rake db:create # Create the database defined in confi... +rake db:create:all # Create all the local databases defin... +rake db:drop # Drops the database for the current R... +rake db:drop:all # Drops all the local databases define... +rake db:fixtures:identify # Search for a fixture given a LABEL o... +rake db:fixtures:load # Load fixtures into the current envir... +rake db:migrate # Migrate the database through scripts... +rake db:migrate:redo # Rollbacks the database one migration... +rake db:migrate:reset # Resets your database using your migr... +rake db:reset # Drops and recreates the database fro... +rake db:rollback # Rolls the schema back to the previou... +rake db:schema:dump # Create a db/schema.rb file that can ... +rake db:schema:load # Load a schema.rb file into the database +rake db:sessions:clear # Clear the sessions table +rake db:sessions:create # Creates a sessions migration for use... +rake db:structure:dump # Dump the database structure to a SQL... +rake db:test:clone # Recreate the test database from the ... +rake db:test:clone_structure # Recreate the test databases from the... +rake db:test:prepare # Prepare the test database and load t... +rake db:test:purge # Empty the test database +rake db:version # Retrieves the current schema version... +rake deprecated # Checks your app and gently warns you... +rake doc:app # Build the app HTML Files +rake doc:clobber_app # Remove rdoc products +rake doc:clobber_plugins # Remove plugin documentation +rake doc:clobber_rails # Remove rdoc products +rake doc:plugins # Generate documentation for all insta... +rake doc:rails # Build the rails HTML Files +rake doc:reapp # Force a rebuild of the RDOC files +rake doc:rerails # Force a rebuild of the RDOC files +rake fckeditor:download # Update the FCKEditor code to the lat... +rake fckeditor:install # Install the FCKEditor components +rake log:clear # Truncates all *.log files in log/ to... +rake notes # Enumerate all annotations +rake notes:fixme # Enumerate all FIXME annotations +rake notes:optimize # Enumerate all OPTIMIZE annotations +rake notes:todo # Enumerate all TODO annotations +rake rails:freeze:edge # Lock to latest Edge Rails or a speci... +rake rails:freeze:gems # Lock this application to the current... +rake rails:unfreeze # Unlock this application from freeze ... +rake rails:update # Update both configs, scripts and pub... +rake rails:update:configs # Update config/boot.rb from your curr... +rake rails:update:javascripts # Update your javascripts from your cu... +rake rails:update:scripts # Add new scripts to the application s... +rake routes # Print out all defined routes in matc... +rake secret # Generate a crytographically secure s... +rake spec # Run all specs in spec directory (exc... +rake spec:clobber_rcov # Remove rcov products for rcov +rake spec:controllers # Run the specs under spec/controllers +rake spec:db:fixtures:load # Load fixtures (from spec/fixtures) i... +rake spec:doc # Print Specdoc for all specs (excludi... +rake spec:helpers # Run the specs under spec/helpers +rake spec:lib # Run the specs under spec/lib +rake spec:models # Run the specs under spec/models +rake spec:plugin_doc # Print Specdoc for all plugin specs +rake spec:plugins # Run the specs under vendor/plugins (... +rake spec:plugins:rspec_on_rails # Runs the examples for rspec_on_rails +rake spec:rcov # Run all specs in spec directory with... +rake spec:server:restart # reload spec_server. +rake spec:server:start # start spec_server. +rake spec:server:stop # stop spec_server. +rake spec:translate # Translate/upgrade specs using the bu... +rake spec:views # Run the specs under spec/views +rake stats # Report code statistics (KLOCs, etc) ... +rake test # Test all units and functionals +rake test:functionals # Run tests for functionalsdb:test:pre... +rake test:integration # Run tests for integrationdb:test:pre... +rake test:plugins # Run tests for pluginsenvironment / R... +rake test:recent # Run tests for recentdb:test:prepare ... +rake test:uncommitted # Run tests for uncommitteddb:test:pre... +rake test:units # Run tests for unitsdb:test:prepare /... +rake tmp:cache:clear # Clears all files and directories in ... +rake tmp:clear # Clear session, cache, and socket fil... +rake tmp:create # Creates tmp directories for sessions... +rake tmp:pids:clear # Clears all files in tmp/pids +rake tmp:sessions:clear # Clears all files in tmp/sessions +rake tmp:sockets:clear # Clears all files in tmp/sockets diff --git a/Golum.Build/Golum.Build.csproj b/Golum.Build/Golum.Build.csproj new file mode 100644 index 0000000..9c91af7 --- /dev/null +++ b/Golum.Build/Golum.Build.csproj @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.21022</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{9F3F3B09-AB90-42E0-B099-81E8BB505954}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>Golum.Build</RootNamespace> + <AssemblyName>Golum.Build</AssemblyName> + <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Xml.Linq"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data.DataSetExtensions"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <ItemGroup> + <Content Include="Docs\Rake Examples.txt" /> + </ItemGroup> + <ItemGroup> + <Folder Include="Configs\" /> + <Folder Include="Libs\" /> + <Folder Include="Recipes\" /> + <Folder Include="Resources\" /> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/Golum.Build/Properties/AssemblyInfo.cs b/Golum.Build/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c13dbf0 --- /dev/null +++ b/Golum.Build/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Golum.Build")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Golum.Build")] +[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("93c2ae1d-c115-421a-8992-ace1087be755")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")]
tobinharris/golem
0a9ca7c597e56520b578d340073182c713d313f9
renaming folders
diff --git a/Rakish.Core/Golem.Core.csproj b/Golem.Core/Golem.Core.csproj similarity index 100% rename from Rakish.Core/Golem.Core.csproj rename to Golem.Core/Golem.Core.csproj diff --git a/Rakish.Core/Locations.cs b/Golem.Core/Locations.cs similarity index 100% rename from Rakish.Core/Locations.cs rename to Golem.Core/Locations.cs diff --git a/Rakish.Core/Properties/AssemblyInfo.cs b/Golem.Core/Properties/AssemblyInfo.cs similarity index 100% rename from Rakish.Core/Properties/AssemblyInfo.cs rename to Golem.Core/Properties/AssemblyInfo.cs diff --git a/Rakish.Core/Recipe.cs b/Golem.Core/Recipe.cs similarity index 100% rename from Rakish.Core/Recipe.cs rename to Golem.Core/Recipe.cs diff --git a/Rakish.Core/RecipeAttribute.cs b/Golem.Core/RecipeAttribute.cs similarity index 100% rename from Rakish.Core/RecipeAttribute.cs rename to Golem.Core/RecipeAttribute.cs diff --git a/Rakish.Core/RecipeFinder.cs b/Golem.Core/RecipeFinder.cs similarity index 100% rename from Rakish.Core/RecipeFinder.cs rename to Golem.Core/RecipeFinder.cs diff --git a/Rakish.Core/Task.cs b/Golem.Core/Task.cs similarity index 100% rename from Rakish.Core/Task.cs rename to Golem.Core/Task.cs diff --git a/Rakish.Core/TaskAttribute.cs b/Golem.Core/TaskAttribute.cs similarity index 100% rename from Rakish.Core/TaskAttribute.cs rename to Golem.Core/TaskAttribute.cs diff --git a/Rakish.Core/TaskRunner.cs b/Golem.Core/TaskRunner.cs similarity index 100% rename from Rakish.Core/TaskRunner.cs rename to Golem.Core/TaskRunner.cs diff --git a/Rakish.Runner/Golem.Runner.csproj b/Golem.Runner/Golem.Runner.csproj similarity index 97% rename from Rakish.Runner/Golem.Runner.csproj rename to Golem.Runner/Golem.Runner.csproj index d3eed2f..07e27ed 100644 --- a/Rakish.Runner/Golem.Runner.csproj +++ b/Golem.Runner/Golem.Runner.csproj @@ -1,71 +1,71 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{AE3B1280-28A3-4E92-8970-DE3168A18676}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golem.Runner</RootNamespace> <AssemblyName>Golem.Runner</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <StartupObject>Golem.Runner.Program</StartupObject> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\Rakish.Core\Golem.Core.csproj"> + <ProjectReference Include="..\Golem.Core\Golem.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> <Name>Golem.Core</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <PropertyGroup> <PostBuildEvent>mkdir "C:\Program Files\Golem\" copy "$(TargetPath)" "C:\Program Files\Golem\golem.exe" copy "$(TargetDir)"*.dll "C:\Program Files\Golem"</PostBuildEvent> </PropertyGroup> </Project> \ No newline at end of file diff --git a/Rakish.Runner/Program.cs b/Golem.Runner/Program.cs similarity index 100% rename from Rakish.Runner/Program.cs rename to Golem.Runner/Program.cs diff --git a/Rakish.Runner/Properties/AssemblyInfo.cs b/Golem.Runner/Properties/AssemblyInfo.cs similarity index 100% rename from Rakish.Runner/Properties/AssemblyInfo.cs rename to Golem.Runner/Properties/AssemblyInfo.cs diff --git a/Rakish.Test/DemoRecipe.cs b/Golem.Test/DemoRecipe.cs similarity index 100% rename from Rakish.Test/DemoRecipe.cs rename to Golem.Test/DemoRecipe.cs diff --git a/Rakish.Test/Golem.Test.csproj b/Golem.Test/Golem.Test.csproj similarity index 97% rename from Rakish.Test/Golem.Test.csproj rename to Golem.Test/Golem.Test.csproj index ec2094c..2d39424 100644 --- a/Rakish.Test/Golem.Test.csproj +++ b/Golem.Test/Golem.Test.csproj @@ -1,70 +1,70 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Golem.Test</RootNamespace> <AssemblyName>Golem.Test</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="nunit.framework, Version=2.4.7.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\..\Program Files\NUnit 2.4.7\bin\nunit.framework.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="DemoRecipe.cs" /> <Compile Include="RecipeDiscoveryFixture.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\Rakish.Core\Golem.Core.csproj"> + <ProjectReference Include="..\Golem.Core\Golem.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> <Name>Golem.Core</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Rakish.Test/Properties/AssemblyInfo.cs b/Golem.Test/Properties/AssemblyInfo.cs similarity index 100% rename from Rakish.Test/Properties/AssemblyInfo.cs rename to Golem.Test/Properties/AssemblyInfo.cs diff --git a/Rakish.Test/RecipeDiscoveryFixture.cs b/Golem.Test/RecipeDiscoveryFixture.cs similarity index 100% rename from Rakish.Test/RecipeDiscoveryFixture.cs rename to Golem.Test/RecipeDiscoveryFixture.cs diff --git a/Golem.sln b/Golem.sln index 5f521dc..242efab 100644 --- a/Golem.sln +++ b/Golem.sln @@ -1,39 +1,39 @@  Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Core", "Rakish.Core\Golem.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Core", "Golem.Core\Golem.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Test", "Rakish.Test\Golem.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Test", "Golem.Test\Golem.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External Libs", "External Libs", "{74E13096-F694-40BE-9F9A-D4EFD2A9E4AD}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Runner", "Rakish.Runner\Golem.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Runner", "Golem.Runner\Golem.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{41F9F9EF-3D0E-4A05-A033-7DD77D040A1F}" ProjectSection(SolutionItems) = preProject Rake.txt = Rake.txt EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.Build.0 = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.ActiveCfg = Release|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.Build.0 = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.Build.0 = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
tobinharris/golem
b76b8d08c2846fb0e3da9cdcb682b73941138e69
first round of renames (not files))
diff --git a/Rakish.sln b/Golem.sln similarity index 80% rename from Rakish.sln rename to Golem.sln index 67d47a1..5f521dc 100644 --- a/Rakish.sln +++ b/Golem.sln @@ -1,39 +1,39 @@  Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rakish.Core", "Rakish.Core\Rakish.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Core", "Rakish.Core\Golem.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rakish.Test", "Rakish.Test\Rakish.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Test", "Rakish.Test\Golem.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External Libs", "External Libs", "{74E13096-F694-40BE-9F9A-D4EFD2A9E4AD}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rakish.Runner", "Rakish.Runner\Rakish.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Golem.Runner", "Rakish.Runner\Golem.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{41F9F9EF-3D0E-4A05-A033-7DD77D040A1F}" ProjectSection(SolutionItems) = preProject Rake.txt = Rake.txt EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.Build.0 = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.ActiveCfg = Release|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.Build.0 = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.Build.0 = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/Rakish.Core/Rakish.Core.csproj b/Rakish.Core/Golem.Core.csproj similarity index 96% rename from Rakish.Core/Rakish.Core.csproj rename to Rakish.Core/Golem.Core.csproj index a6e584c..144c282 100644 --- a/Rakish.Core/Rakish.Core.csproj +++ b/Rakish.Core/Golem.Core.csproj @@ -1,65 +1,65 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{267A8DF5-2B11-470E-8878-BE6E7244B713}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> - <RootNamespace>Rakish.Core</RootNamespace> - <AssemblyName>Rakish.Core</AssemblyName> + <RootNamespace>Golem.Core</RootNamespace> + <AssemblyName>Golem.Core</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Locations.cs" /> <Compile Include="Recipe.cs" /> <Compile Include="Task.cs" /> <Compile Include="TaskAttribute.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RecipeAttribute.cs" /> <Compile Include="RecipeFinder.cs" /> <Compile Include="TaskRunner.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Rakish.Core/Locations.cs b/Rakish.Core/Locations.cs index 9f6bf94..450b684 100644 --- a/Rakish.Core/Locations.cs +++ b/Rakish.Core/Locations.cs @@ -1,11 +1,8 @@ -namespace Rakish.Core +namespace Golem.Core { - //TODO: Not sure about the Locations class. Feels like a Global. - //TODO: Make static? - //Make into a Configuration class? public class Locations { public static string[] StartDirs; } } \ No newline at end of file diff --git a/Rakish.Core/Properties/AssemblyInfo.cs b/Rakish.Core/Properties/AssemblyInfo.cs index f0039ae..88f339d 100644 --- a/Rakish.Core/Properties/AssemblyInfo.cs +++ b/Rakish.Core/Properties/AssemblyInfo.cs @@ -1,36 +1,36 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Rakish.Core")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyTitle("Golem.Core")] +[assembly: AssemblyDescription("Executable Rake-like builds for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Rakish.Core")] -[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyProduct("Golem")] +[assembly: AssemblyCopyright("Copyright Tobin Harris © 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5f73858b-1ba3-46fd-a787-55830d1a6862")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Rakish.Core/Recipe.cs b/Rakish.Core/Recipe.cs index c1fa16d..4133881 100644 --- a/Rakish.Core/Recipe.cs +++ b/Rakish.Core/Recipe.cs @@ -1,31 +1,31 @@ using System; using System.Collections.Generic; using System.Reflection; -namespace Rakish.Core +namespace Golem.Core { public class Recipe { public string Name { get; set; } public string Description { get; set; } public List<Task> Tasks { get; private set; } public Type Class{ get; set;} public Recipe() { Tasks = new List<Task>(); } public Task GetTaskForMethod(MethodInfo methodInfo) { foreach(Task t in Tasks) { if (t.Method != null && t.Method.Name == methodInfo.Name) { return t; } } return null; } } } \ No newline at end of file diff --git a/Rakish.Core/RecipeAttribute.cs b/Rakish.Core/RecipeAttribute.cs index 11078ac..61777c5 100644 --- a/Rakish.Core/RecipeAttribute.cs +++ b/Rakish.Core/RecipeAttribute.cs @@ -1,13 +1,13 @@ using System; -namespace Rakish.Core +namespace Golem.Core { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class RecipeAttribute : Attribute { public string Name { get; set; } public string Description { get; set; } } } \ No newline at end of file diff --git a/Rakish.Core/RecipeFinder.cs b/Rakish.Core/RecipeFinder.cs index 6b7077e..8a0e60c 100644 --- a/Rakish.Core/RecipeFinder.cs +++ b/Rakish.Core/RecipeFinder.cs @@ -1,239 +1,240 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; +using Golem.Core; -namespace Rakish.Core +namespace Golem.Core { /// <summary> /// /// </summary> public class RecipeFinder { //scanning directories //loading assemblies //building tree of recipes //reflecting on types private string[] startDirs; public RecipeFinder() { } public RecipeFinder(params string[] startDirs) : this() { this.startDirs = startDirs; if(startDirs == null) { Locations.StartDirs = new string[] { Environment.CurrentDirectory }; this.startDirs = Locations.StartDirs; } } public ReadOnlyCollection<Assembly> AllAssembliesFound { get; private set; } public ReadOnlyCollection<Recipe> AllRecipesFound { get; private set; } //TODO: Too many variables public IList<Recipe> FindRecipesInFiles() { var recipeClasses = new List<Recipe>(); //TODO: Fix this Locations.StartDirs = startDirs; foreach (var startDir in startDirs) { FileInfo[] dlls = FindAllDlls(startDir); var loadedAssemblies = PreLoadAssembliesToPreventAssemblyNotFoundError(dlls); foreach(var assembly in loadedAssemblies) FindRecipesInAssembly(assembly, recipeClasses); AllAssembliesFound = loadedAssemblies.AsReadOnly(); AllRecipesFound = recipeClasses.AsReadOnly(); } return recipeClasses.AsReadOnly(); } private List<Assembly> PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] dllFile) { var loaded = new List<Assembly>(); foreach (var dll in dllFile) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail - if(! dll.Name.StartsWith("Rakish.Core")) + if(! dll.Name.StartsWith("Golem.Core")) loaded.Add(Assembly.LoadFrom(dll.FullName)); return loaded; } private static void FindRecipesInAssembly(Assembly loaded, List<Recipe> recipeClasses) { try { var types = loaded.GetTypes(); foreach (var type in types) FindRecipeInType(type, recipeClasses); } catch(ReflectionTypeLoadException ex) { foreach(var e in ex.LoaderExceptions) { //Console.WriteLine(e.Message); } } } public static RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } //TODO: FindRecipeInType is Too long and //TODO: too many IL Instructions //TODO: Nesting is too deep //TODO: Not enough comments //TODO: Too many variables // private static void FindRecipeInType(Type type, List<Recipe> manifest) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //add to manifest manifest.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task t) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); t.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; if(! String.IsNullOrEmpty(ta.Description)) t.Description = ta.Description; else t.Description = ""; return t; } private FileInfo[] FindAllDlls(string startDir) { var found = new DirectoryInfo(startDir) .GetFiles("*.dll", SearchOption.AllDirectories); var deduped = new List<FileInfo>(); foreach(var fileInfo in found) if(! fileInfo.Directory.FullName.Contains("\\obj\\")) deduped.Add(fileInfo); return deduped.ToArray(); } } } \ No newline at end of file diff --git a/Rakish.Core/Task.cs b/Rakish.Core/Task.cs index fb2f460..c382f8f 100644 --- a/Rakish.Core/Task.cs +++ b/Rakish.Core/Task.cs @@ -1,23 +1,23 @@ using System; using System.Collections.Generic; using System.Reflection; -namespace Rakish.Core +namespace Golem.Core { public class Task { public string Name { get; set; } public string Description { get; set; } public MethodInfo Method { get; set; } public IList<MethodInfo> DependsOnMethods { get; private set; } public Task() { DependsOnMethods = new List<MethodInfo>(); } } } \ No newline at end of file diff --git a/Rakish.Core/TaskAttribute.cs b/Rakish.Core/TaskAttribute.cs index 28f918b..baf5c5b 100644 --- a/Rakish.Core/TaskAttribute.cs +++ b/Rakish.Core/TaskAttribute.cs @@ -1,20 +1,20 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; -namespace Rakish.Core +namespace Golem.Core { public class TaskAttribute : Attribute { public string Name { get; set; } public string Description { get; set; } public string[] After{get;set;} public TaskAttribute() { After = new string[0]; } } } diff --git a/Rakish.Core/TaskRunner.cs b/Rakish.Core/TaskRunner.cs index 39dac9d..8a6fdf0 100644 --- a/Rakish.Core/TaskRunner.cs +++ b/Rakish.Core/TaskRunner.cs @@ -1,124 +1,124 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; -namespace Rakish.Core +namespace Golem.Core { public class RecipeBase { public IList<Assembly> AllAssemblies = new List<Assembly>(); public IList<Recipe> AllRecipes = new List<Recipe>(); } public class TaskRunner { private RecipeFinder finder; public TaskRunner(RecipeFinder aFinder) { finder = aFinder; } public void Run(Recipe recipe, Task task) { var recipeInstance = Activator.CreateInstance(recipe.Class); SetContextualInformationIfInheritsRecipeBase(recipeInstance); task.Method.Invoke(recipeInstance, null); } private void SetContextualInformationIfInheritsRecipeBase(object recipeInstance) { var tmpRecipe = recipeInstance as RecipeBase; if(tmpRecipe == null) return; tmpRecipe.AllAssemblies = finder.AllAssembliesFound; tmpRecipe.AllRecipes = finder.AllRecipesFound; } //TODO: Run is Too long //TODO: Nesting depth is too deep public void Run(string recipeName, string taskName) { var found = finder.FindRecipesInFiles(); foreach(var r in found) { if(r.Name.ToLower() == recipeName.ToLower()) { foreach(var t in r.Tasks) { if(t.Name.ToLower() == taskName.ToLower()) { foreach(var methodInfo in t.DependsOnMethods) { Run(r, r.GetTaskForMethod(methodInfo)); } Run(r, t); return; } } } } } // public RunManifest BuildRunManifest(string recipeName, string taskName) // { // var manifest = new RunManifest(); // var finder = new RecipeFinder(); // var found = finder.FindRecipesInFiles(); // // foreach (var r in found) // { // if (r.Name.ToLower() == recipeName.ToLower()) // { // foreach (var t in r.Tasks) // { // if (t.Name.ToLower() == taskName.ToLower()) // { // foreach(var d in t.DependsOnMethods) // { // manifest.Add(null); // } // manifest.Add(t); // // } // } // } // } // return manifest; // } } public class RunManifest { public OrderedDictionary ToRun; public void Add(Task t) { if(! ToRun.Contains(t)) { ToRun.Add(t,new RunManifestItem{Task=t}); } } public RunManifest() { ToRun = new OrderedDictionary(); } public Task TaskAt(int position) { return (Task) ToRun[position]; } } public class RunManifestItem { public Task Task; public bool HasRun; } } \ No newline at end of file diff --git a/Rakish.Runner/Rakish.Runner.csproj b/Rakish.Runner/Golem.Runner.csproj similarity index 85% rename from Rakish.Runner/Rakish.Runner.csproj rename to Rakish.Runner/Golem.Runner.csproj index 8cdc00c..d3eed2f 100644 --- a/Rakish.Runner/Rakish.Runner.csproj +++ b/Rakish.Runner/Golem.Runner.csproj @@ -1,70 +1,71 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{AE3B1280-28A3-4E92-8970-DE3168A18676}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> - <RootNamespace>Rakish.Runner</RootNamespace> - <AssemblyName>Rakish.Runner</AssemblyName> + <RootNamespace>Golem.Runner</RootNamespace> + <AssemblyName>Golem.Runner</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> - <StartupObject>Rakish.Runner.Program</StartupObject> + <StartupObject>Golem.Runner.Program</StartupObject> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\Rakish.Core\Rakish.Core.csproj"> + <ProjectReference Include="..\Rakish.Core\Golem.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> - <Name>Rakish.Core</Name> + <Name>Golem.Core</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <PropertyGroup> - <PostBuildEvent>copy "$(TargetPath)" "C:\Program Files\Rakish\rakish.exe" -copy "$(TargetDir)"*.dll "C:\Program Files\Rakish"</PostBuildEvent> + <PostBuildEvent>mkdir "C:\Program Files\Golem\" +copy "$(TargetPath)" "C:\Program Files\Golem\golem.exe" +copy "$(TargetDir)"*.dll "C:\Program Files\Golem"</PostBuildEvent> </PropertyGroup> </Project> \ No newline at end of file diff --git a/Rakish.Runner/Program.cs b/Rakish.Runner/Program.cs index 386def2..71acd27 100644 --- a/Rakish.Runner/Program.cs +++ b/Rakish.Runner/Program.cs @@ -1,52 +1,53 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; -using Rakish.Core; +using Golem.Core; +using Golem.Core; -namespace Rakish.Runner +namespace Golem.Runner { public class Program { public static void Main(string[] args) { var finder = new RecipeFinder(Environment.CurrentDirectory); var found = finder.FindRecipesInFiles(); if(args.Length > 0) { if(args[0].ToLower() == "-t") { ShowList(found); return; } var parts = args[0].Split(':'); var runner = new TaskRunner(finder); if(parts.Length == 2) runner.Run(parts[0],parts[1]); else - Console.WriteLine("Error: don't know what to do with that. \n\nTry: rakish -t\n\n...to see commands."); + Console.WriteLine("Error: don't know what to do with that. \n\nTry: golem -t\n\n...to see commands."); } else { ShowList(found); } } private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { //Console.WriteLine("\n{0}\n",!String.IsNullOrEmpty(recipe.Description) ? recipe.Description : recipe.Name); foreach(var task in recipe.Tasks) { - var start = "rakish " + recipe.Name + ":" + task.Name; + var start = "golem " + recipe.Name + ":" + task.Name; Console.WriteLine(start.PadRight(30) +"# " + task.Description); } } } } } diff --git a/Rakish.Runner/Properties/AssemblyInfo.cs b/Rakish.Runner/Properties/AssemblyInfo.cs index 1b19697..d2491ab 100644 --- a/Rakish.Runner/Properties/AssemblyInfo.cs +++ b/Rakish.Runner/Properties/AssemblyInfo.cs @@ -1,36 +1,36 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Rakish.Runner")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyTitle("Golem.Runner")] +[assembly: AssemblyDescription("Executable Rake-like builds for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Rakish.Runner")] -[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyProduct("Golem")] +[assembly: AssemblyCopyright("Copyright Tobin Harris © 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a981448a-bae0-4896-a00e-67d8b01b3274")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Rakish.Test/DemoRecipe.cs b/Rakish.Test/DemoRecipe.cs index 0604855..508b50c 100644 --- a/Rakish.Test/DemoRecipe.cs +++ b/Rakish.Test/DemoRecipe.cs @@ -1,120 +1,121 @@ using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; -using Rakish.Core; +using Golem.Core; +using Golem.Core; -namespace Rakish.Test +namespace Golem.Test { [Recipe(Name="demo2")] public class Demo2Recipe { [Task(Name = "one", After = new[] { "Three", "Two" })] public void One() { Console.WriteLine("One!"); } [Task(Name = "two")] public void Two() { Console.WriteLine("Two!"); } [Task(Name = "three")] public void Three() { Console.WriteLine("Three!"); } } [Recipe(Name = "demo")] public class DemoRecipe { [Task(Name = "run")] public void Default() { AppDomain.CurrentDomain.SetData("TEST", "TEST"); } [Task(Name="list", Description = "List all NUnit tests in solution")] public void List() { AppDomain.CurrentDomain.SetData("TEST", "LIST"); } [Task(Name="stats", Description="Lists line counts for all types of files")] public void Stats() { string rootDir = Locations.StartDirs[0]; Console.WriteLine(rootDir); var count = new Dictionary<string, long>() { { "lines", 0 }, { "classes", 0 }, { "files", 0 }, { "enums", 0 }, { "methods", 0 }, { "comments", 0 } }; GetLineCount(rootDir, "*.cs", count); Console.WriteLine("c# Files:\t\t{0}", count["files"]); Console.WriteLine("c# Classes: \t{0}", count["classes"]); Console.WriteLine("c# Methods: \t{0}", count["methods"]); Console.WriteLine("c# Lines:\t\t{0}", count["lines"]); Console.WriteLine("c# Comment Lines:\t\t{0}", count["comments"]); Console.WriteLine("Avg Methods Per Class:\t\t{0}", count["methods"]/count["classes"]); } private static void GetLineCount(string rootDir, string fileFilter, Dictionary<string,long> counts) { var files = Directory.GetFiles(rootDir, fileFilter, SearchOption.AllDirectories); long lineCount = 0; foreach(var file in files) { using(var r = File.OpenText(file)) { counts["files"] += 1; var line = r.ReadLine(); while(line != null) { if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+class.+").Length > 0) counts["classes"] += 1; if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+enum.+").Length > 0) counts["enums"] += 1; if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+\\(.*\\).+").Length > 0) counts["methods"] += 1; if (fileFilter == "*.cs" && Regex.Match(line, ".+//.+").Length > 0) counts["comments"] += 1; counts["lines"] += 1; line = r.ReadLine(); } } } } } [Recipe] public class Demo3Recipe { [Task] public void Hello() { Console.WriteLine("Hello"); } } [Recipe] public class Demo4Recipe : RecipeBase { [Task] public void Hello() { Console.WriteLine(this.AllAssemblies.Count); Console.WriteLine(this.AllRecipes.Count); } } } \ No newline at end of file diff --git a/Rakish.Test/Rakish.Test.csproj b/Rakish.Test/Golem.Test.csproj similarity index 93% rename from Rakish.Test/Rakish.Test.csproj rename to Rakish.Test/Golem.Test.csproj index 3f46374..ec2094c 100644 --- a/Rakish.Test/Rakish.Test.csproj +++ b/Rakish.Test/Golem.Test.csproj @@ -1,70 +1,70 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> - <RootNamespace>Rakish.Test</RootNamespace> - <AssemblyName>Rakish.Test</AssemblyName> + <RootNamespace>Golem.Test</RootNamespace> + <AssemblyName>Golem.Test</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="nunit.framework, Version=2.4.7.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\..\Program Files\NUnit 2.4.7\bin\nunit.framework.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="DemoRecipe.cs" /> <Compile Include="RecipeDiscoveryFixture.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\Rakish.Core\Rakish.Core.csproj"> + <ProjectReference Include="..\Rakish.Core\Golem.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> - <Name>Rakish.Core</Name> + <Name>Golem.Core</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Rakish.Test/Properties/AssemblyInfo.cs b/Rakish.Test/Properties/AssemblyInfo.cs index 5e93d21..cb183a5 100644 --- a/Rakish.Test/Properties/AssemblyInfo.cs +++ b/Rakish.Test/Properties/AssemblyInfo.cs @@ -1,36 +1,36 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Rakish.Test")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyTitle("Golem.Test")] +[assembly: AssemblyDescription("Executable Rake-like builds for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Rakish.Test")] -[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyProduct("Golem")] +[assembly: AssemblyCopyright("Copyright Tobin Harris © 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ab24db7a-685f-4a70-a136-26621f960aa8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Rakish.Test/RecipeDiscoveryFixture.cs b/Rakish.Test/RecipeDiscoveryFixture.cs index af6664d..1a376fa 100644 --- a/Rakish.Test/RecipeDiscoveryFixture.cs +++ b/Rakish.Test/RecipeDiscoveryFixture.cs @@ -1,120 +1,121 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Golem.Core; using NUnit.Framework; -using Rakish.Core; +using Golem.Core; -namespace Rakish.Test +namespace Golem.Test { [TestFixture] public class RecipeDiscoveryFixture { private RecipeFinder finder; IList<Recipe> found; [SetUp] public void Before_Each_Test_Is_Run() { finder = new RecipeFinder(Environment.CurrentDirectory + "..\\..\\..\\..\\"); found = finder.FindRecipesInFiles(); } [Test] public void Can_Discover_Recipes() { foreach(var r in found) { Console.WriteLine(r.Name); } Assert.AreEqual(4, found.Count); } [Test] public void Can_Discover_Recipe_Details() { var recipeInfo = found[1]; Assert.AreEqual("demo", recipeInfo.Name); } [Test] public void Can_Discover_Tasks_And_Details() { var recipeInfo = found[1]; Assert.AreEqual(3, recipeInfo.Tasks.Count); Assert.AreEqual("list", recipeInfo.Tasks[1].Name); Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); } [Test] public void Can_Run_Task() { var recipeInfo = found[1]; var runner = new TaskRunner(finder); runner.Run(recipeInfo, recipeInfo.Tasks[0]); Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } [Test] public void Can_Run_Task_By_Name() { var runner = new TaskRunner(finder); runner.Run("demo","list"); Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); runner.Run("demo", "stats"); } [Test, Ignore] public void Can_Run_All_Default_Tasks() { Assert.Fail(); } [Test] public void Can_Set_Dependencies() { var demo2 = found[0]; Assert.AreEqual("demo2", demo2.Name); Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); } [Test] public void Functions_Are_Called_In_Correct_Order_With_Dependencies() { var runner = new TaskRunner(finder); runner.Run("demo2", "one"); } [Test] public void Can_Infer_Recipe_Category_And_Task_Name() { var runner = new TaskRunner(finder); runner.Run("demo3", "hello"); } [Test, Ignore] public void Can_Override_Current_Root_Folder() { Assert.Fail(); } [Test, Ignore] public void Can_Fetch_List_Of_Available_Recipes_From_Server() { Assert.Fail(); } [Test] public void Recipes_Inheriting_RecipeBase_Have_Contextual_Information() { var demo4 = found[3]; var runner = new TaskRunner(finder); runner.Run(demo4,demo4.Tasks[0]); } } }
tobinharris/golem
467ddd6e66331230b717bf2f2eed63dc66a133f0
tweaks
diff --git a/Rake.txt b/Rake.txt new file mode 100644 index 0000000..2aacc41 --- /dev/null +++ b/Rake.txt @@ -0,0 +1,114 @@ + --classic-namespace (-C) + Put Task and FileTask in the top level namespace + --describe (-D) + Describe the tasks (matching optional PATTERN), then exit. + --dry-run (-n) + Do a dry run without executing actions. + --help (-h) + 0 + --libdir=LIBDIR (-I) + Include LIBDIR in the search path for required modules. + --nosearch (-N) + Do not search parent directories for the Rakefile. + --prereqs (-P) + Display the tasks and dependencies, then exit. + --quiet (-q) + Do not log messages to standard output. + --rakefile (-f) + Use FILE as the rakefile. + --rakelibdir=RAKELIBDIR (-R) + Auto-import any .rake files in RAKELIBDIR. (default is 'rakelib') + --require=MODULE (-r) + Require MODULE before executing rakefile. + --silent (-s) + Like --quiet, but also suppresses the 'in directory' announcement. + --tasks (-T) + Display the tasks (matching optional PATTERN) with descriptions, then exit. + --trace (-t) + Turn on invoke/execute tracing, enable full backtrace. + --verbose (-v) + Log message to standard output (default). + --version (-V) + Display the program version. + + +rake db:abort_if_pending_migrations # Raises an error if there are pending... +rake db:charset # Retrieves the charset for the curren... +rake db:collation # Retrieves the collation for the curr... +rake db:create # Create the database defined in confi... +rake db:create:all # Create all the local databases defin... +rake db:drop # Drops the database for the current R... +rake db:drop:all # Drops all the local databases define... +rake db:fixtures:identify # Search for a fixture given a LABEL o... +rake db:fixtures:load # Load fixtures into the current envir... +rake db:migrate # Migrate the database through scripts... +rake db:migrate:redo # Rollbacks the database one migration... +rake db:migrate:reset # Resets your database using your migr... +rake db:reset # Drops and recreates the database fro... +rake db:rollback # Rolls the schema back to the previou... +rake db:schema:dump # Create a db/schema.rb file that can ... +rake db:schema:load # Load a schema.rb file into the database +rake db:sessions:clear # Clear the sessions table +rake db:sessions:create # Creates a sessions migration for use... +rake db:structure:dump # Dump the database structure to a SQL... +rake db:test:clone # Recreate the test database from the ... +rake db:test:clone_structure # Recreate the test databases from the... +rake db:test:prepare # Prepare the test database and load t... +rake db:test:purge # Empty the test database +rake db:version # Retrieves the current schema version... +rake deprecated # Checks your app and gently warns you... +rake doc:app # Build the app HTML Files +rake doc:clobber_app # Remove rdoc products +rake doc:clobber_plugins # Remove plugin documentation +rake doc:clobber_rails # Remove rdoc products +rake doc:plugins # Generate documentation for all insta... +rake doc:rails # Build the rails HTML Files +rake doc:reapp # Force a rebuild of the RDOC files +rake doc:rerails # Force a rebuild of the RDOC files +rake fckeditor:download # Update the FCKEditor code to the lat... +rake fckeditor:install # Install the FCKEditor components +rake log:clear # Truncates all *.log files in log/ to... +rake notes # Enumerate all annotations +rake notes:fixme # Enumerate all FIXME annotations +rake notes:optimize # Enumerate all OPTIMIZE annotations +rake notes:todo # Enumerate all TODO annotations +rake rails:freeze:edge # Lock to latest Edge Rails or a speci... +rake rails:freeze:gems # Lock this application to the current... +rake rails:unfreeze # Unlock this application from freeze ... +rake rails:update # Update both configs, scripts and pub... +rake rails:update:configs # Update config/boot.rb from your curr... +rake rails:update:javascripts # Update your javascripts from your cu... +rake rails:update:scripts # Add new scripts to the application s... +rake routes # Print out all defined routes in matc... +rake secret # Generate a crytographically secure s... +rake spec # Run all specs in spec directory (exc... +rake spec:clobber_rcov # Remove rcov products for rcov +rake spec:controllers # Run the specs under spec/controllers +rake spec:db:fixtures:load # Load fixtures (from spec/fixtures) i... +rake spec:doc # Print Specdoc for all specs (excludi... +rake spec:helpers # Run the specs under spec/helpers +rake spec:lib # Run the specs under spec/lib +rake spec:models # Run the specs under spec/models +rake spec:plugin_doc # Print Specdoc for all plugin specs +rake spec:plugins # Run the specs under vendor/plugins (... +rake spec:plugins:rspec_on_rails # Runs the examples for rspec_on_rails +rake spec:rcov # Run all specs in spec directory with... +rake spec:server:restart # reload spec_server. +rake spec:server:start # start spec_server. +rake spec:server:stop # stop spec_server. +rake spec:translate # Translate/upgrade specs using the bu... +rake spec:views # Run the specs under spec/views +rake stats # Report code statistics (KLOCs, etc) ... +rake test # Test all units and functionals +rake test:functionals # Run tests for functionalsdb:test:pre... +rake test:integration # Run tests for integrationdb:test:pre... +rake test:plugins # Run tests for pluginsenvironment / R... +rake test:recent # Run tests for recentdb:test:prepare ... +rake test:uncommitted # Run tests for uncommitteddb:test:pre... +rake test:units # Run tests for unitsdb:test:prepare /... +rake tmp:cache:clear # Clears all files and directories in ... +rake tmp:clear # Clear session, cache, and socket fil... +rake tmp:create # Creates tmp directories for sessions... +rake tmp:pids:clear # Clears all files in tmp/pids +rake tmp:sessions:clear # Clears all files in tmp/sessions +rake tmp:sockets:clear # Clears all files in tmp/sockets diff --git a/Rakish.Core/Recipe.cs b/Rakish.Core/Recipe.cs index 9d58f2b..c1fa16d 100644 --- a/Rakish.Core/Recipe.cs +++ b/Rakish.Core/Recipe.cs @@ -1,30 +1,31 @@ using System; using System.Collections.Generic; using System.Reflection; namespace Rakish.Core { public class Recipe { public string Name { get; set; } + public string Description { get; set; } public List<Task> Tasks { get; private set; } public Type Class{ get; set;} public Recipe() { Tasks = new List<Task>(); } public Task GetTaskForMethod(MethodInfo methodInfo) { foreach(Task t in Tasks) { if (t.Method != null && t.Method.Name == methodInfo.Name) { return t; } } return null; } } } \ No newline at end of file diff --git a/Rakish.Core/RecipeAttribute.cs b/Rakish.Core/RecipeAttribute.cs index e80e6f2..11078ac 100644 --- a/Rakish.Core/RecipeAttribute.cs +++ b/Rakish.Core/RecipeAttribute.cs @@ -1,13 +1,13 @@ using System; namespace Rakish.Core { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class RecipeAttribute : Attribute { public string Name { get; set; } - + public string Description { get; set; } } } \ No newline at end of file diff --git a/Rakish.Core/RecipeFinder.cs b/Rakish.Core/RecipeFinder.cs index 7bf0dde..6b7077e 100644 --- a/Rakish.Core/RecipeFinder.cs +++ b/Rakish.Core/RecipeFinder.cs @@ -1,217 +1,239 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Linq; namespace Rakish.Core -{ - - +{ /// <summary> /// /// </summary> public class RecipeFinder { //scanning directories //loading assemblies //building tree of recipes //reflecting on types private string[] startDirs; public RecipeFinder() { - } + public RecipeFinder(params string[] startDirs) : this() { this.startDirs = startDirs; if(startDirs == null) { Locations.StartDirs = new string[] { Environment.CurrentDirectory }; this.startDirs = Locations.StartDirs; } } + + public ReadOnlyCollection<Assembly> AllAssembliesFound { get; private set; } + public ReadOnlyCollection<Recipe> AllRecipesFound { get; private set; } + //TODO: Too many variables public IList<Recipe> FindRecipesInFiles() { var recipeClasses = new List<Recipe>(); //TODO: Fix this Locations.StartDirs = startDirs; foreach (var startDir in startDirs) { FileInfo[] dlls = FindAllDlls(startDir); var loadedAssemblies = PreLoadAssembliesToPreventAssemblyNotFoundError(dlls); foreach(var assembly in loadedAssemblies) FindRecipesInAssembly(assembly, recipeClasses); + + AllAssembliesFound = loadedAssemblies.AsReadOnly(); + AllRecipesFound = recipeClasses.AsReadOnly(); + + } return recipeClasses.AsReadOnly(); } private List<Assembly> PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] dllFile) { var loaded = new List<Assembly>(); foreach (var dll in dllFile) //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail if(! dll.Name.StartsWith("Rakish.Core")) loaded.Add(Assembly.LoadFrom(dll.FullName)); return loaded; } private static void FindRecipesInAssembly(Assembly loaded, List<Recipe> recipeClasses) - { - var types = loaded.GetTypes(); - - foreach(var type in types) - FindRecipeInType(type, recipeClasses); + { + try + { + var types = loaded.GetTypes(); + + foreach (var type in types) + FindRecipeInType(type, recipeClasses); + } + catch(ReflectionTypeLoadException ex) + { + foreach(var e in ex.LoaderExceptions) + { + //Console.WriteLine(e.Message); + } + + } + + } public static RecipeAttribute GetRecipeAttributeOrNull(Type type) { //get recipe attributes for type var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); //should only be one per type if (atts.Length > 1) throw new Exception("Expected only 1 recipe attribute, but got more"); //return if none, we'll skip this class if (atts.Length == 0) return null; var recipeAtt = atts[0] as RecipeAttribute; //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) if (recipeAtt == null) throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); return recipeAtt; } //TODO: FindRecipeInType is Too long and //TODO: too many IL Instructions //TODO: Nesting is too deep //TODO: Not enough comments //TODO: Too many variables // private static void FindRecipeInType(Type type, List<Recipe> manifest) { //find the attribute on the assembly if there is one var recipeAtt = GetRecipeAttributeOrNull(type); //if not found, return if (recipeAtt == null) return; //create recipe details from attribute Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); //add to manifest manifest.Add(recipe); //trawl through and add the tasks AddTasksToRecipe(type, recipe); } private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) { return new Recipe { - Class = type, - Name = String.IsNullOrEmpty(recipeAtt.Name) ? type.Name.Replace("Recipe","").ToLower() : recipeAtt.Name + Class = type, + Name = String.IsNullOrEmpty(recipeAtt.Name) ? (type.Name == "RecipesRecipe" ? "recipes" : type.Name.Replace("Recipe", "").ToLower()) : recipeAtt.Name, + Description = ! String.IsNullOrEmpty(recipeAtt.Description) ? recipeAtt.Description : null }; } private static void AddTasksToRecipe(Type type, Recipe recipe) { //loop through methods in class foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { //get the custom attributes on the method var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); if(foundAttributes.Length > 1) throw new Exception("Should only be one task attribute on a method"); //if none, skp to the next method if (foundAttributes.Length == 0) continue; var taskAttribute = foundAttributes[0] as TaskAttribute; if (taskAttribute == null) throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); //get the task based on attribute contents Task t = CreateTaskFromAttribute(method, taskAttribute); //build list of dependent tasks CreateDependentTasks(type, taskAttribute, t); //add the task to the recipe recipe.Tasks.Add(t); } } private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task t) { foreach(string methodName in taskAttribute.After) { var dependee = type.GetMethod(methodName); if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); t.DependsOnMethods.Add(dependee); } } private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) { Task t = new Task(); if(! String.IsNullOrEmpty(ta.Name)) t.Name = ta.Name; else t.Name = method.Name.Replace("Task", "").ToLower(); t.Method = method; - if(! String.IsNullOrEmpty(ta.Help)) - t.Description = ta.Help; + if(! String.IsNullOrEmpty(ta.Description)) + t.Description = ta.Description; else - t.Description = "No description"; + t.Description = ""; return t; } private FileInfo[] FindAllDlls(string startDir) { var found = new DirectoryInfo(startDir) .GetFiles("*.dll", SearchOption.AllDirectories); var deduped = new List<FileInfo>(); foreach(var fileInfo in found) if(! fileInfo.Directory.FullName.Contains("\\obj\\")) deduped.Add(fileInfo); return deduped.ToArray(); } } } \ No newline at end of file diff --git a/Rakish.Core/TaskAttribute.cs b/Rakish.Core/TaskAttribute.cs index 6e107aa..28f918b 100644 --- a/Rakish.Core/TaskAttribute.cs +++ b/Rakish.Core/TaskAttribute.cs @@ -1,20 +1,20 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Rakish.Core { public class TaskAttribute : Attribute { public string Name { get; set; } - public string Help { get; set; } + public string Description { get; set; } public string[] After{get;set;} public TaskAttribute() { After = new string[0]; } } } diff --git a/Rakish.Core/TaskRunner.cs b/Rakish.Core/TaskRunner.cs index 2931f21..39dac9d 100644 --- a/Rakish.Core/TaskRunner.cs +++ b/Rakish.Core/TaskRunner.cs @@ -1,105 +1,124 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; +using System.Reflection; namespace Rakish.Core { + public class RecipeBase + { + public IList<Assembly> AllAssemblies = new List<Assembly>(); + public IList<Recipe> AllRecipes = new List<Recipe>(); + } + public class TaskRunner { private RecipeFinder finder; public TaskRunner(RecipeFinder aFinder) { finder = aFinder; } public void Run(Recipe recipe, Task task) { var recipeInstance = Activator.CreateInstance(recipe.Class); - + SetContextualInformationIfInheritsRecipeBase(recipeInstance); task.Method.Invoke(recipeInstance, null); } + private void SetContextualInformationIfInheritsRecipeBase(object recipeInstance) + { + var tmpRecipe = recipeInstance as RecipeBase; + + if(tmpRecipe == null) + return; + + tmpRecipe.AllAssemblies = finder.AllAssembliesFound; + tmpRecipe.AllRecipes = finder.AllRecipesFound; + + } + //TODO: Run is Too long //TODO: Nesting depth is too deep public void Run(string recipeName, string taskName) { var found = finder.FindRecipesInFiles(); foreach(var r in found) { if(r.Name.ToLower() == recipeName.ToLower()) { foreach(var t in r.Tasks) { if(t.Name.ToLower() == taskName.ToLower()) { foreach(var methodInfo in t.DependsOnMethods) { Run(r, r.GetTaskForMethod(methodInfo)); } Run(r, t); return; } } } } } // public RunManifest BuildRunManifest(string recipeName, string taskName) // { // var manifest = new RunManifest(); // var finder = new RecipeFinder(); // var found = finder.FindRecipesInFiles(); // // foreach (var r in found) // { // if (r.Name.ToLower() == recipeName.ToLower()) // { // foreach (var t in r.Tasks) // { // if (t.Name.ToLower() == taskName.ToLower()) // { // foreach(var d in t.DependsOnMethods) // { // manifest.Add(null); // } // manifest.Add(t); // // } // } // } // } // return manifest; // } } public class RunManifest { public OrderedDictionary ToRun; public void Add(Task t) { if(! ToRun.Contains(t)) { ToRun.Add(t,new RunManifestItem{Task=t}); } } public RunManifest() { ToRun = new OrderedDictionary(); } public Task TaskAt(int position) { return (Task) ToRun[position]; } } public class RunManifestItem { public Task Task; public bool HasRun; } } \ No newline at end of file diff --git a/Rakish.Runner/Program.cs b/Rakish.Runner/Program.cs index df1e864..386def2 100644 --- a/Rakish.Runner/Program.cs +++ b/Rakish.Runner/Program.cs @@ -1,50 +1,52 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Rakish.Core; namespace Rakish.Runner { public class Program { public static void Main(string[] args) { var finder = new RecipeFinder(Environment.CurrentDirectory); var found = finder.FindRecipesInFiles(); if(args.Length > 0) { if(args[0].ToLower() == "-t") { ShowList(found); return; } var parts = args[0].Split(':'); var runner = new TaskRunner(finder); if(parts.Length == 2) runner.Run(parts[0],parts[1]); else Console.WriteLine("Error: don't know what to do with that. \n\nTry: rakish -t\n\n...to see commands."); } else { ShowList(found); } } private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { + //Console.WriteLine("\n{0}\n",!String.IsNullOrEmpty(recipe.Description) ? recipe.Description : recipe.Name); foreach(var task in recipe.Tasks) { - Console.WriteLine("rakish " + recipe.Name + ":" + task.Name + " - " + task.Description); + var start = "rakish " + recipe.Name + ":" + task.Name; + Console.WriteLine(start.PadRight(30) +"# " + task.Description); } } } } } diff --git a/Rakish.Test/DemoRecipe.cs b/Rakish.Test/DemoRecipe.cs index fe706db..0604855 100644 --- a/Rakish.Test/DemoRecipe.cs +++ b/Rakish.Test/DemoRecipe.cs @@ -1,105 +1,120 @@ using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Rakish.Core; namespace Rakish.Test { [Recipe(Name="demo2")] - public class Demo2Recipe + public class Demo2Recipe { [Task(Name = "one", After = new[] { "Three", "Two" })] public void One() { Console.WriteLine("One!"); } [Task(Name = "two")] public void Two() { Console.WriteLine("Two!"); } [Task(Name = "three")] public void Three() { Console.WriteLine("Three!"); } } [Recipe(Name = "demo")] - public class DemoRecipe + public class DemoRecipe { [Task(Name = "run")] public void Default() { AppDomain.CurrentDomain.SetData("TEST", "TEST"); } - [Task(Name="list", Help = "List all NUnit tests in solution")] + [Task(Name="list", Description = "List all NUnit tests in solution")] public void List() { AppDomain.CurrentDomain.SetData("TEST", "LIST"); } - [Task(Name="stats", Help="Lists line counts for all types of files")] + [Task(Name="stats", Description="Lists line counts for all types of files")] public void Stats() { string rootDir = Locations.StartDirs[0]; Console.WriteLine(rootDir); - var count = new Dictionary<string, long>() { { "lines", 0 }, { "classes", 0 }, { "files", 0 }, { "enums", 0 }, { "methods", 0 } }; + var count = new Dictionary<string, long>() { { "lines", 0 }, { "classes", 0 }, { "files", 0 }, { "enums", 0 }, { "methods", 0 }, { "comments", 0 } }; GetLineCount(rootDir, "*.cs", count); Console.WriteLine("c# Files:\t\t{0}", count["files"]); Console.WriteLine("c# Classes: \t{0}", count["classes"]); Console.WriteLine("c# Methods: \t{0}", count["methods"]); Console.WriteLine("c# Lines:\t\t{0}", count["lines"]); + Console.WriteLine("c# Comment Lines:\t\t{0}", count["comments"]); Console.WriteLine("Avg Methods Per Class:\t\t{0}", count["methods"]/count["classes"]); } private static void GetLineCount(string rootDir, string fileFilter, Dictionary<string,long> counts) { var files = Directory.GetFiles(rootDir, fileFilter, SearchOption.AllDirectories); long lineCount = 0; foreach(var file in files) { using(var r = File.OpenText(file)) { counts["files"] += 1; var line = r.ReadLine(); while(line != null) { if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+class.+").Length > 0) counts["classes"] += 1; if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+enum.+").Length > 0) counts["enums"] += 1; if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+\\(.*\\).+").Length > 0) counts["methods"] += 1; + if (fileFilter == "*.cs" && Regex.Match(line, ".+//.+").Length > 0) + counts["comments"] += 1; + counts["lines"] += 1; line = r.ReadLine(); } } } } } [Recipe] - public class Demo3Recipe + public class Demo3Recipe { [Task] public void Hello() { Console.WriteLine("Hello"); } } + + [Recipe] + public class Demo4Recipe : RecipeBase + { + [Task] + public void Hello() + { + Console.WriteLine(this.AllAssemblies.Count); + Console.WriteLine(this.AllRecipes.Count); + } + } } \ No newline at end of file diff --git a/Rakish.Test/RecipeDiscoveryFixture.cs b/Rakish.Test/RecipeDiscoveryFixture.cs index 94a11de..af6664d 100644 --- a/Rakish.Test/RecipeDiscoveryFixture.cs +++ b/Rakish.Test/RecipeDiscoveryFixture.cs @@ -1,113 +1,120 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Rakish.Core; namespace Rakish.Test { [TestFixture] public class RecipeDiscoveryFixture { private RecipeFinder finder; IList<Recipe> found; [SetUp] public void Before_Each_Test_Is_Run() { finder = new RecipeFinder(Environment.CurrentDirectory + "..\\..\\..\\..\\"); found = finder.FindRecipesInFiles(); } [Test] public void Can_Discover_Recipes() { foreach(var r in found) { Console.WriteLine(r.Name); } - Assert.AreEqual(3, found.Count); + Assert.AreEqual(4, found.Count); } [Test] public void Can_Discover_Recipe_Details() { var recipeInfo = found[1]; Assert.AreEqual("demo", recipeInfo.Name); } [Test] public void Can_Discover_Tasks_And_Details() { var recipeInfo = found[1]; Assert.AreEqual(3, recipeInfo.Tasks.Count); Assert.AreEqual("list", recipeInfo.Tasks[1].Name); Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); } [Test] public void Can_Run_Task() { var recipeInfo = found[1]; var runner = new TaskRunner(finder); runner.Run(recipeInfo, recipeInfo.Tasks[0]); Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } [Test] public void Can_Run_Task_By_Name() { var runner = new TaskRunner(finder); runner.Run("demo","list"); Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); runner.Run("demo", "stats"); } [Test, Ignore] public void Can_Run_All_Default_Tasks() { Assert.Fail(); } [Test] public void Can_Set_Dependencies() { var demo2 = found[0]; Assert.AreEqual("demo2", demo2.Name); Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); } [Test] public void Functions_Are_Called_In_Correct_Order_With_Dependencies() { var runner = new TaskRunner(finder); runner.Run("demo2", "one"); } [Test] public void Can_Infer_Recipe_Category_And_Task_Name() { var runner = new TaskRunner(finder); runner.Run("demo3", "hello"); } [Test, Ignore] public void Can_Override_Current_Root_Folder() { Assert.Fail(); } [Test, Ignore] public void Can_Fetch_List_Of_Available_Recipes_From_Server() { Assert.Fail(); } + [Test] + public void Recipes_Inheriting_RecipeBase_Have_Contextual_Information() + { + var demo4 = found[3]; + var runner = new TaskRunner(finder); + runner.Run(demo4,demo4.Tasks[0]); + } } } diff --git a/Rakish.sln b/Rakish.sln index d9fa27c..67d47a1 100644 --- a/Rakish.sln +++ b/Rakish.sln @@ -1,34 +1,39 @@  Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rakish.Core", "Rakish.Core\Rakish.Core.csproj", "{267A8DF5-2B11-470E-8878-BE6E7244B713}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rakish.Test", "Rakish.Test\Rakish.Test.csproj", "{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External Libs", "External Libs", "{74E13096-F694-40BE-9F9A-D4EFD2A9E4AD}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rakish.Runner", "Rakish.Runner\Rakish.Runner.csproj", "{AE3B1280-28A3-4E92-8970-DE3168A18676}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{41F9F9EF-3D0E-4A05-A033-7DD77D040A1F}" + ProjectSection(SolutionItems) = preProject + Rake.txt = Rake.txt + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Debug|Any CPU.Build.0 = Debug|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.ActiveCfg = Release|Any CPU {267A8DF5-2B11-470E-8878-BE6E7244B713}.Release|Any CPU.Build.0 = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}.Release|Any CPU.Build.0 = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE3B1280-28A3-4E92-8970-DE3168A18676}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
tobinharris/golem
e68f88f96b7d7c8e8239a6b2ed720b3bd8cbc1f3
refactoring
diff --git a/.gitignore b/.gitignore index bb1e9d7..1d31ea9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ *_ReSharper* *_Resharper* */bin/* */obj/* *resharper.user* *.suo -*.resharper \ No newline at end of file +*.resharper +*.csproj.user \ No newline at end of file diff --git a/Rakish.Core/Locations.cs b/Rakish.Core/Locations.cs new file mode 100644 index 0000000..9f6bf94 --- /dev/null +++ b/Rakish.Core/Locations.cs @@ -0,0 +1,11 @@ +namespace Rakish.Core +{ + //TODO: Not sure about the Locations class. Feels like a Global. + //TODO: Make static? + //Make into a Configuration class? + public class Locations + { + + public static string[] StartDirs; + } +} \ No newline at end of file diff --git a/Rakish.Core/Rakish.Core.csproj b/Rakish.Core/Rakish.Core.csproj index fce1b42..a6e584c 100644 --- a/Rakish.Core/Rakish.Core.csproj +++ b/Rakish.Core/Rakish.Core.csproj @@ -1,64 +1,65 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{267A8DF5-2B11-470E-8878-BE6E7244B713}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Rakish.Core</RootNamespace> <AssemblyName>Rakish.Core</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> + <Compile Include="Locations.cs" /> <Compile Include="Recipe.cs" /> <Compile Include="Task.cs" /> <Compile Include="TaskAttribute.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RecipeAttribute.cs" /> <Compile Include="RecipeFinder.cs" /> <Compile Include="TaskRunner.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Rakish.Core/RecipeFinder.cs b/Rakish.Core/RecipeFinder.cs index f8a3826..7bf0dde 100644 --- a/Rakish.Core/RecipeFinder.cs +++ b/Rakish.Core/RecipeFinder.cs @@ -1,109 +1,217 @@ using System; using System.Collections.Generic; using System.IO; using System.Reflection; +using System.Linq; namespace Rakish.Core { + + + + /// <summary> + /// + /// </summary> public class RecipeFinder { - public IList<Recipe> FindRecipesInAssemblies() + + //scanning directories + //loading assemblies + //building tree of recipes + //reflecting on types + + private string[] startDirs; + + public RecipeFinder() { - var startDir = Environment.CurrentDirectory; - return FindRecipesInAssemblies(startDir); + } + public RecipeFinder(params string[] startDirs) : this() + { + this.startDirs = startDirs; - public IList<Recipe> FindRecipesInAssemblies(params string[] startDirs) + if(startDirs == null) + { + Locations.StartDirs = new string[] { Environment.CurrentDirectory }; + this.startDirs = Locations.StartDirs; + } + + + } + //TODO: Too many variables + public IList<Recipe> FindRecipesInFiles() { var recipeClasses = new List<Recipe>(); + + //TODO: Fix this + Locations.StartDirs = startDirs; - foreach(var startDir in startDirs) + foreach (var startDir in startDirs) { - FileInfo[] possibleContainers = GetPossibleContainers(startDir); + FileInfo[] dlls = FindAllDlls(startDir); + var loadedAssemblies = PreLoadAssembliesToPreventAssemblyNotFoundError(dlls); - foreach(var assemblyFile in possibleContainers) - { - FindRecipesInAssembly(assemblyFile, recipeClasses); - } + foreach(var assembly in loadedAssemblies) + FindRecipesInAssembly(assembly, recipeClasses); + } return recipeClasses.AsReadOnly(); } - private static void FindRecipesInAssembly(FileInfo file, List<Recipe> recipeClasses) + private List<Assembly> PreLoadAssembliesToPreventAssemblyNotFoundError(FileInfo[] dllFile) { - var loaded = Assembly.LoadFrom(file.FullName); + var loaded = new List<Assembly>(); + + foreach (var dll in dllFile) + //loading the core twice is BAD because "if(blah is RecipeAttribute)" etc will always fail + if(! dll.Name.StartsWith("Rakish.Core")) + loaded.Add(Assembly.LoadFrom(dll.FullName)); + + return loaded; + } + + private static void FindRecipesInAssembly(Assembly loaded, List<Recipe> recipeClasses) + { var types = loaded.GetTypes(); + foreach(var type in types) - { FindRecipeInType(type, recipeClasses); - } + } - private static void FindRecipeInType(Type type, List<Recipe> recipeClasses) + + public static RecipeAttribute GetRecipeAttributeOrNull(Type type) { - var atts = type.GetCustomAttributes(true); + //get recipe attributes for type + var atts = type.GetCustomAttributes(typeof(RecipeAttribute), true); + + //should only be one per type + if (atts.Length > 1) + throw new Exception("Expected only 1 recipe attribute, but got more"); + + //return if none, we'll skip this class + if (atts.Length == 0) + return null; - foreach(var att in atts) + var recipeAtt = atts[0] as RecipeAttribute; + + //throw if bad case. Should cast fine (if not, then might indicate 2 of the same assembly is loaded) + if (recipeAtt == null) + throw new Exception("Casting error for RecipeAttribute. Same assembly loaded more than once?"); + + return recipeAtt; + } + + //TODO: FindRecipeInType is Too long and + //TODO: too many IL Instructions + //TODO: Nesting is too deep + //TODO: Not enough comments + //TODO: Too many variables + // + private static void FindRecipeInType(Type type, List<Recipe> manifest) + { + //find the attribute on the assembly if there is one + var recipeAtt = GetRecipeAttributeOrNull(type); + + //if not found, return + if (recipeAtt == null) return; + + //create recipe details from attribute + Recipe recipe = CreateRecipeFromAttribute(type, recipeAtt); + + //add to manifest + manifest.Add(recipe); + + //trawl through and add the tasks + AddTasksToRecipe(type, recipe); + + } + + private static Recipe CreateRecipeFromAttribute(Type type, RecipeAttribute recipeAtt) + { + return new Recipe + { + Class = type, + Name = String.IsNullOrEmpty(recipeAtt.Name) ? type.Name.Replace("Recipe","").ToLower() : recipeAtt.Name + }; + } + + private static void AddTasksToRecipe(Type type, Recipe recipe) + { + //loop through methods in class + foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )) { - var recipeAtt = att as RecipeAttribute; + //get the custom attributes on the method + var foundAttributes = method.GetCustomAttributes(typeof(TaskAttribute), false); + + if(foundAttributes.Length > 1) + throw new Exception("Should only be one task attribute on a method"); - if (recipeAtt == null) + //if none, skp to the next method + if (foundAttributes.Length == 0) continue; + + var taskAttribute = foundAttributes[0] as TaskAttribute; + + if (taskAttribute == null) + throw new Exception("couldn't cast TaskAttribute correctly, more that one assembly loaded?"); + + //get the task based on attribute contents + Task t = CreateTaskFromAttribute(method, taskAttribute); - var recipe = new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? type.Name.Replace("Recipe","").ToLower() : recipeAtt.Name }; - recipeClasses.Add(recipe); - - foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) - { - var taskAttributes = method.GetCustomAttributes(true); - foreach(var taskAttribute in taskAttributes) - { - var ta = taskAttribute as TaskAttribute; - - if (ta == null) - continue; - - Task t = new Task(); - - if(! String.IsNullOrEmpty(ta.Name)) - { - t.Name = ta.Name; - } - else - { - t.Name = method.Name.Replace("Task", "").ToLower(); - } - - t.Method = method; - - if(! String.IsNullOrEmpty(ta.Help)) - { - t.Description = ta.Help; - } - else - { - t.Description = "No description"; - } - - foreach(string methodName in ta.After) - { - var dependee = type.GetMethod(methodName); - if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); - t.DependsOnMethods.Add(dependee); - } - - recipe.Tasks.Add(t); - - } - } + //build list of dependent tasks + CreateDependentTasks(type, taskAttribute, t); + + //add the task to the recipe + recipe.Tasks.Add(t); } } - private FileInfo[] GetPossibleContainers(string startDir) + private static void CreateDependentTasks(Type type, TaskAttribute taskAttribute, Task t) { - return new DirectoryInfo(startDir) + foreach(string methodName in taskAttribute.After) + { + var dependee = type.GetMethod(methodName); + if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); + t.DependsOnMethods.Add(dependee); + } + } + + private static Task CreateTaskFromAttribute(MethodInfo method, TaskAttribute ta) + { + Task t = new Task(); + + if(! String.IsNullOrEmpty(ta.Name)) + t.Name = ta.Name; + else + t.Name = method.Name.Replace("Task", "").ToLower(); + + + t.Method = method; + + if(! String.IsNullOrEmpty(ta.Help)) + t.Description = ta.Help; + else + t.Description = "No description"; + return t; + } + + private FileInfo[] FindAllDlls(string startDir) + { + + var found = new DirectoryInfo(startDir) .GetFiles("*.dll", SearchOption.AllDirectories); + + var deduped = new List<FileInfo>(); + + foreach(var fileInfo in found) + if(! fileInfo.Directory.FullName.Contains("\\obj\\")) + deduped.Add(fileInfo); + + return deduped.ToArray(); + + } } } \ No newline at end of file diff --git a/Rakish.Core/TaskRunner.cs b/Rakish.Core/TaskRunner.cs index b2b2dd6..2931f21 100644 --- a/Rakish.Core/TaskRunner.cs +++ b/Rakish.Core/TaskRunner.cs @@ -1,97 +1,105 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; namespace Rakish.Core { public class TaskRunner { + private RecipeFinder finder; + + public TaskRunner(RecipeFinder aFinder) + { + finder = aFinder; + } + public void Run(Recipe recipe, Task task) { var recipeInstance = Activator.CreateInstance(recipe.Class); task.Method.Invoke(recipeInstance, null); } + //TODO: Run is Too long + //TODO: Nesting depth is too deep public void Run(string recipeName, string taskName) { - var finder = new RecipeFinder(); - var found = finder.FindRecipesInAssemblies(); + var found = finder.FindRecipesInFiles(); foreach(var r in found) { if(r.Name.ToLower() == recipeName.ToLower()) { foreach(var t in r.Tasks) { if(t.Name.ToLower() == taskName.ToLower()) { foreach(var methodInfo in t.DependsOnMethods) { Run(r, r.GetTaskForMethod(methodInfo)); } Run(r, t); return; } } } } } // public RunManifest BuildRunManifest(string recipeName, string taskName) // { // var manifest = new RunManifest(); // var finder = new RecipeFinder(); -// var found = finder.FindRecipesInAssemblies(); +// var found = finder.FindRecipesInFiles(); // // foreach (var r in found) // { // if (r.Name.ToLower() == recipeName.ToLower()) // { // foreach (var t in r.Tasks) // { // if (t.Name.ToLower() == taskName.ToLower()) // { // foreach(var d in t.DependsOnMethods) // { // manifest.Add(null); // } // manifest.Add(t); // // } // } // } // } // return manifest; // } } public class RunManifest { public OrderedDictionary ToRun; public void Add(Task t) { if(! ToRun.Contains(t)) { ToRun.Add(t,new RunManifestItem{Task=t}); } } public RunManifest() { ToRun = new OrderedDictionary(); } public Task TaskAt(int position) { return (Task) ToRun[position]; } } public class RunManifestItem { public Task Task; public bool HasRun; } } \ No newline at end of file diff --git a/Rakish.Runner/Program.cs b/Rakish.Runner/Program.cs index 060cc00..df1e864 100644 --- a/Rakish.Runner/Program.cs +++ b/Rakish.Runner/Program.cs @@ -1,50 +1,50 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Rakish.Core; namespace Rakish.Runner { public class Program { public static void Main(string[] args) { - var finder = new RecipeFinder(); - var found = finder.FindRecipesInAssemblies(); + var finder = new RecipeFinder(Environment.CurrentDirectory); + var found = finder.FindRecipesInFiles(); if(args.Length > 0) { if(args[0].ToLower() == "-t") { ShowList(found); return; } var parts = args[0].Split(':'); - var runner = new TaskRunner(); + var runner = new TaskRunner(finder); if(parts.Length == 2) runner.Run(parts[0],parts[1]); else Console.WriteLine("Error: don't know what to do with that. \n\nTry: rakish -t\n\n...to see commands."); } else { ShowList(found); } } private static void ShowList(IList<Recipe> found) { foreach(var recipe in found) { foreach(var task in recipe.Tasks) { Console.WriteLine("rakish " + recipe.Name + ":" + task.Name + " - " + task.Description); } } } } } diff --git a/Rakish.Runner/Rakish.Runner.csproj b/Rakish.Runner/Rakish.Runner.csproj index bc4417a..8cdc00c 100644 --- a/Rakish.Runner/Rakish.Runner.csproj +++ b/Rakish.Runner/Rakish.Runner.csproj @@ -1,70 +1,70 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{AE3B1280-28A3-4E92-8970-DE3168A18676}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Rakish.Runner</RootNamespace> <AssemblyName>Rakish.Runner</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <StartupObject>Rakish.Runner.Program</StartupObject> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Rakish.Core\Rakish.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> <Name>Rakish.Core</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <PropertyGroup> - <PostBuildEvent>copy "$(TargetPath)" "$(SolutionDir)rakish.exe" -copy "$(TargetDir)"*.dll "$(SolutionDir)"</PostBuildEvent> + <PostBuildEvent>copy "$(TargetPath)" "C:\Program Files\Rakish\rakish.exe" +copy "$(TargetDir)"*.dll "C:\Program Files\Rakish"</PostBuildEvent> </PropertyGroup> </Project> \ No newline at end of file diff --git a/Rakish.Test/DemoRecipe.cs b/Rakish.Test/DemoRecipe.cs index a61122e..fe706db 100644 --- a/Rakish.Test/DemoRecipe.cs +++ b/Rakish.Test/DemoRecipe.cs @@ -1,103 +1,105 @@ using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Rakish.Core; namespace Rakish.Test { [Recipe(Name="demo2")] public class Demo2Recipe { [Task(Name = "one", After = new[] { "Three", "Two" })] public void One() { Console.WriteLine("One!"); } [Task(Name = "two")] public void Two() { Console.WriteLine("Two!"); } [Task(Name = "three")] public void Three() { Console.WriteLine("Three!"); } } [Recipe(Name = "demo")] public class DemoRecipe { [Task(Name = "run")] public void Default() { AppDomain.CurrentDomain.SetData("TEST", "TEST"); } [Task(Name="list", Help = "List all NUnit tests in solution")] public void List() { AppDomain.CurrentDomain.SetData("TEST", "LIST"); } [Task(Name="stats", Help="Lists line counts for all types of files")] public void Stats() { - string rootDir = Environment.CurrentDirectory;// +"..\\..\\..\\..\\"; + string rootDir = Locations.StartDirs[0]; + Console.WriteLine(rootDir); var count = new Dictionary<string, long>() { { "lines", 0 }, { "classes", 0 }, { "files", 0 }, { "enums", 0 }, { "methods", 0 } }; GetLineCount(rootDir, "*.cs", count); Console.WriteLine("c# Files:\t\t{0}", count["files"]); Console.WriteLine("c# Classes: \t{0}", count["classes"]); - Console.WriteLine("c# Methods:\t\t{0}", count["methods"]); + Console.WriteLine("c# Methods: \t{0}", count["methods"]); Console.WriteLine("c# Lines:\t\t{0}", count["lines"]); + Console.WriteLine("Avg Methods Per Class:\t\t{0}", count["methods"]/count["classes"]); } private static void GetLineCount(string rootDir, string fileFilter, Dictionary<string,long> counts) { var files = Directory.GetFiles(rootDir, fileFilter, SearchOption.AllDirectories); long lineCount = 0; foreach(var file in files) { using(var r = File.OpenText(file)) { counts["files"] += 1; var line = r.ReadLine(); while(line != null) { - if (fileFilter == "*.cs" && Regex.Match(line, ".+public|private|internal|protected.+class.+").Length > 0) + if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+class.+").Length > 0) counts["classes"] += 1; - if (fileFilter == "*.cs" && Regex.Match(line, ".+public|private|internal|protected.+enum.+").Length > 0) + if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+enum.+").Length > 0) counts["enums"] += 1; - if (fileFilter == "*.cs" && Regex.Match(line, ".+public|private|internal|protected.+\\(.*\\).+").Length > 0) + if (fileFilter == "*.cs" && Regex.Match(line, ".+[public|private|internal|protected].+\\(.*\\).+").Length > 0) counts["methods"] += 1; counts["lines"] += 1; line = r.ReadLine(); } } } } } [Recipe] public class Demo3Recipe { [Task] public void Hello() { Console.WriteLine("Hello"); } } } \ No newline at end of file diff --git a/Rakish.Test/RecipeDiscoveryFixture.cs b/Rakish.Test/RecipeDiscoveryFixture.cs index 3c0269f..94a11de 100644 --- a/Rakish.Test/RecipeDiscoveryFixture.cs +++ b/Rakish.Test/RecipeDiscoveryFixture.cs @@ -1,108 +1,113 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Rakish.Core; namespace Rakish.Test { [TestFixture] public class RecipeDiscoveryFixture { - readonly RecipeFinder finder = new RecipeFinder(); + private RecipeFinder finder; IList<Recipe> found; [SetUp] public void Before_Each_Test_Is_Run() { - found = finder.FindRecipesInAssemblies(); + finder = new RecipeFinder(Environment.CurrentDirectory + "..\\..\\..\\..\\"); + found = finder.FindRecipesInFiles(); } [Test] public void Can_Discover_Recipes() { + foreach(var r in found) + { + Console.WriteLine(r.Name); + } Assert.AreEqual(3, found.Count); } [Test] public void Can_Discover_Recipe_Details() { var recipeInfo = found[1]; Assert.AreEqual("demo", recipeInfo.Name); } [Test] public void Can_Discover_Tasks_And_Details() { var recipeInfo = found[1]; Assert.AreEqual(3, recipeInfo.Tasks.Count); Assert.AreEqual("list", recipeInfo.Tasks[1].Name); Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); } [Test] public void Can_Run_Task() { var recipeInfo = found[1]; - var runner = new TaskRunner(); + var runner = new TaskRunner(finder); runner.Run(recipeInfo, recipeInfo.Tasks[0]); Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } [Test] public void Can_Run_Task_By_Name() { - var runner = new TaskRunner(); + var runner = new TaskRunner(finder); runner.Run("demo","list"); Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); runner.Run("demo", "stats"); } [Test, Ignore] public void Can_Run_All_Default_Tasks() { Assert.Fail(); } [Test] public void Can_Set_Dependencies() { var demo2 = found[0]; Assert.AreEqual("demo2", demo2.Name); Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); } [Test] public void Functions_Are_Called_In_Correct_Order_With_Dependencies() { - var runner = new TaskRunner(); + var runner = new TaskRunner(finder); runner.Run("demo2", "one"); } [Test] public void Can_Infer_Recipe_Category_And_Task_Name() { - var runner = new TaskRunner(); + var runner = new TaskRunner(finder); runner.Run("demo3", "hello"); } [Test, Ignore] public void Can_Override_Current_Root_Folder() { Assert.Fail(); } [Test, Ignore] public void Can_Fetch_List_Of_Available_Recipes_From_Server() { Assert.Fail(); } } }
tobinharris/golem
13bb6224c2022d508e890404cb6d25f414603971
got first set of tests passing@
diff --git a/.gitignore b/.gitignore index 70b4bf8..bb1e9d7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ *_ReSharper* *_Resharper* */bin/* */obj/* *resharper.user* *.suo +*.resharper \ No newline at end of file diff --git a/Rakish.Core/DefaultRecipes.cs b/Rakish.Core/DefaultRecipes.cs deleted file mode 100644 index 6991399..0000000 --- a/Rakish.Core/DefaultRecipes.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Rakish.Core -{ - [Recipe] - public class DefaultRecipes - { - [Task(Description = "Run all tasks")] - public void All() - { - - } - } -} \ No newline at end of file diff --git a/Rakish.Core/Rakish.Core.csproj b/Rakish.Core/Rakish.Core.csproj index e7bcd9d..fce1b42 100644 --- a/Rakish.Core/Rakish.Core.csproj +++ b/Rakish.Core/Rakish.Core.csproj @@ -1,62 +1,64 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{267A8DF5-2B11-470E-8878-BE6E7244B713}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Rakish.Core</RootNamespace> <AssemblyName>Rakish.Core</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> + <Compile Include="Recipe.cs" /> + <Compile Include="Task.cs" /> <Compile Include="TaskAttribute.cs" /> - <Compile Include="DefaultRecipes.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RecipeAttribute.cs" /> <Compile Include="RecipeFinder.cs" /> + <Compile Include="TaskRunner.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Rakish.Core/Recipe.cs b/Rakish.Core/Recipe.cs new file mode 100644 index 0000000..9d58f2b --- /dev/null +++ b/Rakish.Core/Recipe.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace Rakish.Core +{ + public class Recipe + { + public string Name { get; set; } + public List<Task> Tasks { get; private set; } + public Type Class{ get; set;} + + public Recipe() + { + Tasks = new List<Task>(); + } + + public Task GetTaskForMethod(MethodInfo methodInfo) + { + foreach(Task t in Tasks) + { + if (t.Method != null && t.Method.Name == methodInfo.Name) + { + return t; + } + } + return null; + } + } +} \ No newline at end of file diff --git a/Rakish.Core/RecipeAttribute.cs b/Rakish.Core/RecipeAttribute.cs index 615bb7d..e80e6f2 100644 --- a/Rakish.Core/RecipeAttribute.cs +++ b/Rakish.Core/RecipeAttribute.cs @@ -1,9 +1,13 @@ using System; namespace Rakish.Core { + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class RecipeAttribute : Attribute { - public string Description { get; set; } + public string Name { get; set; } + + + } } \ No newline at end of file diff --git a/Rakish.Core/RecipeFinder.cs b/Rakish.Core/RecipeFinder.cs index 1d39a7f..f8a3826 100644 --- a/Rakish.Core/RecipeFinder.cs +++ b/Rakish.Core/RecipeFinder.cs @@ -1,50 +1,109 @@ using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace Rakish.Core { public class RecipeFinder { - public void FindRecipesInAssemblies() + public IList<Recipe> FindRecipesInAssemblies() { var startDir = Environment.CurrentDirectory; - FindRecipesInAssemblies(startDir); + return FindRecipesInAssemblies(startDir); } - public void FindRecipesInAssemblies(params string[] startDirs) + public IList<Recipe> FindRecipesInAssemblies(params string[] startDirs) { - var recipeClasses = new List<Type>(); + var recipeClasses = new List<Recipe>(); foreach(var startDir in startDirs) { - var possibleContainers = - new DirectoryInfo(startDir) - .GetFiles("*Core.dll", SearchOption.AllDirectories); - - foreach(var file in possibleContainers) + FileInfo[] possibleContainers = GetPossibleContainers(startDir); + + foreach(var assemblyFile in possibleContainers) { - var loaded = Assembly.LoadFile(file.FullName); - Console.WriteLine(file.FullName); - - var types = loaded.GetTypes(); - - foreach(var type in types) + FindRecipesInAssembly(assemblyFile, recipeClasses); + } + } + + return recipeClasses.AsReadOnly(); + } + + private static void FindRecipesInAssembly(FileInfo file, List<Recipe> recipeClasses) + { + var loaded = Assembly.LoadFrom(file.FullName); + var types = loaded.GetTypes(); + foreach(var type in types) + { + FindRecipeInType(type, recipeClasses); + } + } + + private static void FindRecipeInType(Type type, List<Recipe> recipeClasses) + { + var atts = type.GetCustomAttributes(true); + + foreach(var att in atts) + { + var recipeAtt = att as RecipeAttribute; + + if (recipeAtt == null) + continue; + + var recipe = new Recipe { Class = type, Name = String.IsNullOrEmpty(recipeAtt.Name) ? type.Name.Replace("Recipe","").ToLower() : recipeAtt.Name }; + recipeClasses.Add(recipe); + + foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) + { + var taskAttributes = method.GetCustomAttributes(true); + foreach(var taskAttribute in taskAttributes) { - var atts = type.GetCustomAttributes(false); + var ta = taskAttribute as TaskAttribute; + + if (ta == null) + continue; - foreach(var att in atts) + Task t = new Task(); + + if(! String.IsNullOrEmpty(ta.Name)) + { + t.Name = ta.Name; + } + else + { + t.Name = method.Name.Replace("Task", "").ToLower(); + } + + t.Method = method; + + if(! String.IsNullOrEmpty(ta.Help)) + { + t.Description = ta.Help; + } + else { - if(Convert.ToString(att) == "Rakish.Core.RecipeAttribute") - { - recipeClasses.Add(type); - Console.WriteLine("\t{0}", att); - } + t.Description = "No description"; } + + foreach(string methodName in ta.After) + { + var dependee = type.GetMethod(methodName); + if(dependee == null) throw new Exception(String.Format("No dependee method {0}",methodName)); + t.DependsOnMethods.Add(dependee); + } + + recipe.Tasks.Add(t); + } } } } + + private FileInfo[] GetPossibleContainers(string startDir) + { + return new DirectoryInfo(startDir) + .GetFiles("*.dll", SearchOption.AllDirectories); + } } } \ No newline at end of file diff --git a/Rakish.Core/Task.cs b/Rakish.Core/Task.cs new file mode 100644 index 0000000..fb2f460 --- /dev/null +++ b/Rakish.Core/Task.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace Rakish.Core +{ + public class Task + { + + public string Name { get; set; } + public string Description { get; set; } + + + public MethodInfo Method { get; set; } + + public IList<MethodInfo> DependsOnMethods { get; private set; } + + public Task() + { + DependsOnMethods = new List<MethodInfo>(); + } + } +} \ No newline at end of file diff --git a/Rakish.Core/TaskAttribute.cs b/Rakish.Core/TaskAttribute.cs index 00af32c..6e107aa 100644 --- a/Rakish.Core/TaskAttribute.cs +++ b/Rakish.Core/TaskAttribute.cs @@ -1,12 +1,20 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Rakish.Core { public class TaskAttribute : Attribute { - public string Description { get; set; } + public string Name { get; set; } + public string Help { get; set; } + public string[] After{get;set;} + public TaskAttribute() + { + After = new string[0]; + } } + + } diff --git a/Rakish.Core/TaskRunner.cs b/Rakish.Core/TaskRunner.cs new file mode 100644 index 0000000..b2b2dd6 --- /dev/null +++ b/Rakish.Core/TaskRunner.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; + +namespace Rakish.Core +{ + public class TaskRunner + { + public void Run(Recipe recipe, Task task) + { + var recipeInstance = Activator.CreateInstance(recipe.Class); + + task.Method.Invoke(recipeInstance, null); + } + + public void Run(string recipeName, string taskName) + { + var finder = new RecipeFinder(); + var found = finder.FindRecipesInAssemblies(); + + foreach(var r in found) + { + if(r.Name.ToLower() == recipeName.ToLower()) + { + foreach(var t in r.Tasks) + { + if(t.Name.ToLower() == taskName.ToLower()) + { + foreach(var methodInfo in t.DependsOnMethods) + { + Run(r, r.GetTaskForMethod(methodInfo)); + } + Run(r, t); + return; + } + } + } + } + } + +// public RunManifest BuildRunManifest(string recipeName, string taskName) +// { +// var manifest = new RunManifest(); +// var finder = new RecipeFinder(); +// var found = finder.FindRecipesInAssemblies(); +// +// foreach (var r in found) +// { +// if (r.Name.ToLower() == recipeName.ToLower()) +// { +// foreach (var t in r.Tasks) +// { +// if (t.Name.ToLower() == taskName.ToLower()) +// { +// foreach(var d in t.DependsOnMethods) +// { +// manifest.Add(null); +// } +// manifest.Add(t); +// +// } +// } +// } +// } +// return manifest; +// } + + + } + + public class RunManifest + { + + public OrderedDictionary ToRun; + public void Add(Task t) + { + if(! ToRun.Contains(t)) + { + ToRun.Add(t,new RunManifestItem{Task=t}); + } + } + public RunManifest() + { + ToRun = new OrderedDictionary(); + } + + public Task TaskAt(int position) + { + return (Task) ToRun[position]; + } + } + public class RunManifestItem + { + public Task Task; + public bool HasRun; + } +} \ No newline at end of file diff --git a/Rakish.Runner/Program.cs b/Rakish.Runner/Program.cs index 8389244..060cc00 100644 --- a/Rakish.Runner/Program.cs +++ b/Rakish.Runner/Program.cs @@ -1,15 +1,50 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Rakish.Core; namespace Rakish.Runner { public class Program { public static void Main(string[] args) { + var finder = new RecipeFinder(); + var found = finder.FindRecipesInAssemblies(); + + if(args.Length > 0) + { + if(args[0].ToLower() == "-t") + { + ShowList(found); + return; + } + + var parts = args[0].Split(':'); + var runner = new TaskRunner(); + + if(parts.Length == 2) + runner.Run(parts[0],parts[1]); + else + Console.WriteLine("Error: don't know what to do with that. \n\nTry: rakish -t\n\n...to see commands."); + } + else + { + ShowList(found); + } } + + private static void ShowList(IList<Recipe> found) + { + foreach(var recipe in found) + { + foreach(var task in recipe.Tasks) + { + Console.WriteLine("rakish " + recipe.Name + ":" + task.Name + " - " + task.Description); + } + } + } } } diff --git a/Rakish.Runner/Rakish.Runner.csproj b/Rakish.Runner/Rakish.Runner.csproj index cff2f4c..bc4417a 100644 --- a/Rakish.Runner/Rakish.Runner.csproj +++ b/Rakish.Runner/Rakish.Runner.csproj @@ -1,66 +1,70 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{AE3B1280-28A3-4E92-8970-DE3168A18676}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Rakish.Runner</RootNamespace> <AssemblyName>Rakish.Runner</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <StartupObject>Rakish.Runner.Program</StartupObject> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Rakish.Core\Rakish.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> <Name>Rakish.Core</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> + <PropertyGroup> + <PostBuildEvent>copy "$(TargetPath)" "$(SolutionDir)rakish.exe" +copy "$(TargetDir)"*.dll "$(SolutionDir)"</PostBuildEvent> + </PropertyGroup> </Project> \ No newline at end of file diff --git a/Rakish.Test/DemoRecipe.cs b/Rakish.Test/DemoRecipe.cs new file mode 100644 index 0000000..a61122e --- /dev/null +++ b/Rakish.Test/DemoRecipe.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using Rakish.Core; + +namespace Rakish.Test +{ + [Recipe(Name="demo2")] + public class Demo2Recipe + { + [Task(Name = "one", After = new[] { "Three", "Two" })] + public void One() + { + Console.WriteLine("One!"); + } + + [Task(Name = "two")] + public void Two() + { + Console.WriteLine("Two!"); + } + + [Task(Name = "three")] + public void Three() + { + Console.WriteLine("Three!"); + } + } + + [Recipe(Name = "demo")] + public class DemoRecipe + { + [Task(Name = "run")] + public void Default() + { + AppDomain.CurrentDomain.SetData("TEST", "TEST"); + } + + [Task(Name="list", Help = "List all NUnit tests in solution")] + public void List() + { + AppDomain.CurrentDomain.SetData("TEST", "LIST"); + } + + [Task(Name="stats", Help="Lists line counts for all types of files")] + public void Stats() + { + string rootDir = Environment.CurrentDirectory;// +"..\\..\\..\\..\\"; + var count = new Dictionary<string, long>() { { "lines", 0 }, { "classes", 0 }, { "files", 0 }, { "enums", 0 }, { "methods", 0 } }; + GetLineCount(rootDir, "*.cs", count); + + + Console.WriteLine("c# Files:\t\t{0}", count["files"]); + Console.WriteLine("c# Classes: \t{0}", count["classes"]); + Console.WriteLine("c# Methods:\t\t{0}", count["methods"]); + Console.WriteLine("c# Lines:\t\t{0}", count["lines"]); + + } + + + private static void GetLineCount(string rootDir, string fileFilter, Dictionary<string,long> counts) + { + var files = Directory.GetFiles(rootDir, fileFilter, SearchOption.AllDirectories); + long lineCount = 0; + foreach(var file in files) + { + using(var r = File.OpenText(file)) + { + counts["files"] += 1; + + var line = r.ReadLine(); + while(line != null) + { + if (fileFilter == "*.cs" && Regex.Match(line, ".+public|private|internal|protected.+class.+").Length > 0) + counts["classes"] += 1; + + if (fileFilter == "*.cs" && Regex.Match(line, ".+public|private|internal|protected.+enum.+").Length > 0) + counts["enums"] += 1; + + if (fileFilter == "*.cs" && Regex.Match(line, ".+public|private|internal|protected.+\\(.*\\).+").Length > 0) + counts["methods"] += 1; + + counts["lines"] += 1; + + line = r.ReadLine(); + } + } + } + + } + } + + [Recipe] + public class Demo3Recipe + { + [Task] + public void Hello() + { + Console.WriteLine("Hello"); + } + } +} \ No newline at end of file diff --git a/Rakish.Test/Rakish.Test.csproj b/Rakish.Test/Rakish.Test.csproj index 67b4109..3f46374 100644 --- a/Rakish.Test/Rakish.Test.csproj +++ b/Rakish.Test/Rakish.Test.csproj @@ -1,69 +1,70 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{30A6D3AC-8EB8-428F-9C1E-5131643F7EBF}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Rakish.Test</RootNamespace> <AssemblyName>Rakish.Test</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="nunit.framework, Version=2.4.7.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\..\Program Files\NUnit 2.4.7\bin\nunit.framework.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> + <Compile Include="DemoRecipe.cs" /> <Compile Include="RecipeDiscoveryFixture.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Rakish.Core\Rakish.Core.csproj"> <Project>{267A8DF5-2B11-470E-8878-BE6E7244B713}</Project> <Name>Rakish.Core</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Rakish.Test/RecipeDiscoveryFixture.cs b/Rakish.Test/RecipeDiscoveryFixture.cs index cab3551..3c0269f 100644 --- a/Rakish.Test/RecipeDiscoveryFixture.cs +++ b/Rakish.Test/RecipeDiscoveryFixture.cs @@ -1,20 +1,108 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Rakish.Core; namespace Rakish.Test { [TestFixture] public class RecipeDiscoveryFixture { + readonly RecipeFinder finder = new RecipeFinder(); + IList<Recipe> found; + + [SetUp] + public void Before_Each_Test_Is_Run() + { + found = finder.FindRecipesInAssemblies(); + } + + [Test] + public void Can_Discover_Recipes() + { + Assert.AreEqual(3, found.Count); + } + + [Test] + public void Can_Discover_Recipe_Details() + { + var recipeInfo = found[1]; + Assert.AreEqual("demo", recipeInfo.Name); + + } + + [Test] + public void Can_Discover_Tasks_And_Details() + { + var recipeInfo = found[1]; + Assert.AreEqual(3, recipeInfo.Tasks.Count); + Assert.AreEqual("list", recipeInfo.Tasks[1].Name); + Assert.AreEqual("List all NUnit tests in solution", recipeInfo.Tasks[1].Description); + } + [Test] - public void CanDiscoverRecipesAndTasksInAssembly() + public void Can_Run_Task() { - var finder = new RecipeFinder(); - finder.FindRecipesInAssemblies(); + var recipeInfo = found[1]; + var runner = new TaskRunner(); + runner.Run(recipeInfo, recipeInfo.Tasks[0]); + Assert.AreEqual("TEST", AppDomain.CurrentDomain.GetData("TEST")); } + + [Test] + public void Can_Run_Task_By_Name() + { + var runner = new TaskRunner(); + runner.Run("demo","list"); + Assert.AreEqual("LIST", AppDomain.CurrentDomain.GetData("TEST")); + runner.Run("demo", "stats"); + } + + + [Test, Ignore] + public void Can_Run_All_Default_Tasks() + { + Assert.Fail(); + } + + [Test] + public void Can_Set_Dependencies() + { + var demo2 = found[0]; + Assert.AreEqual("demo2", demo2.Name); + Assert.AreEqual(2, demo2.Tasks[0].DependsOnMethods.Count); + Assert.AreEqual(demo2.Tasks[0].DependsOnMethods[0].Name, "Three"); + } + + [Test] + public void Functions_Are_Called_In_Correct_Order_With_Dependencies() + { + var runner = new TaskRunner(); + runner.Run("demo2", "one"); + + } + + [Test] + public void Can_Infer_Recipe_Category_And_Task_Name() + { + var runner = new TaskRunner(); + runner.Run("demo3", "hello"); + } + + [Test, Ignore] + public void Can_Override_Current_Root_Folder() + { + Assert.Fail(); + } + + [Test, Ignore] + public void Can_Fetch_List_Of_Available_Recipes_From_Server() + { + Assert.Fail(); + } + + } }
simonhn/pav-api
844a4876f04095aa1d55d4b7a11fa56c09cfa298
error when no order parameter
diff --git a/pavapi.rb b/pavapi.rb index e391a62..c453f89 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,304 +1,304 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' #Queueing with stalker/beanstalkd require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' module V1 class PavApi < Sinatra::Base configure do set :environment, :development set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') set :views, File.join(File.dirname(__FILE__), '/views') set :public, File.join(File.dirname(__FILE__), '/public') #versioning set :version, 'v1' register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :debug ) $LOG = Logger.new(File.join(File.dirname(__FILE__),'log/pavstore.log'), 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order(order) - if (order.downcase=='asc') + if (order && order.downcase=='asc') return "ASC" else return "DESC" end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime" elsif (order=='track') return "tracks.title ASC, plays.playedtime" else return "plays.playedtime" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' require_relative 'routes/info' # search artist by name get "/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end end \ No newline at end of file
simonhn/pav-api
ef7961927cfd671de000b05cfc421f69a85ac9a6
adding capistrano
diff --git a/Gemfile b/Gemfile index 3cf1f06..aa91e40 100644 --- a/Gemfile +++ b/Gemfile @@ -1,34 +1,35 @@ source :rubygems gem 'sinatra', '=1.2.6' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' gem 'chronic_duration' gem 'chronic' gem 'sinatra-respond_to', '=0.7.0' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' gem 'stalker' gem 'i18n' gem 'foreman' -gem 'daemons' \ No newline at end of file +gem 'daemons' +gem 'capistrano' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 6eb752c..774fcf4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,99 +1,114 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) + capistrano (2.12.0) + highline + net-scp (>= 1.0.0) + net-sftp (>= 2.0.0) + net-ssh (>= 2.0.14) + net-ssh-gateway (>= 1.1.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) daemons (1.1.4) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) foreman (0.36.1) term-ansicolor (~> 1.0.7) thor (>= 0.13.6) + highline (1.6.11) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) + net-scp (1.0.4) + net-ssh (>= 1.99.1) + net-sftp (2.0.5) + net-ssh (>= 2.0.9) + net-ssh (2.3.0) + net-ssh-gateway (1.1.0) + net-ssh (>= 1.99.1) newrelic_rpm (3.3.1) numerizer (0.1.1) rack (1.3.5) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) sinatra (1.2.6) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) sinatra-respond_to (0.7.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure term-ansicolor (1.0.7) thor (0.14.6) tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder + capistrano chronic chronic_duration crack daemons dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps foreman i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client sinatra (= 1.2.6) sinatra-respond_to (= 0.7.0) stalker yajl-ruby
simonhn/pav-api
4577bfd2f837165b631fef96a26a9c12fb83417d
adding asc desc ordering as paramter to play route
diff --git a/config.ru b/config.ru deleted file mode 100644 index f280a07..0000000 --- a/config.ru +++ /dev/null @@ -1,7 +0,0 @@ -require File.join(File.dirname(__FILE__), 'pavapi.rb') -use Rack::JSONP -map "/v1" do - run V1::PavApi -end - -#run PavApi \ No newline at end of file diff --git a/pavapi.rb b/pavapi.rb index 121ce97..e391a62 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,295 +1,304 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' #Queueing with stalker/beanstalkd require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' module V1 class PavApi < Sinatra::Base configure do set :environment, :development set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') set :views, File.join(File.dirname(__FILE__), '/views') set :public, File.join(File.dirname(__FILE__), '/public') #versioning set :version, 'v1' register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :debug ) $LOG = Logger.new(File.join(File.dirname(__FILE__),'log/pavstore.log'), 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end + + def get_order(order) + if (order.downcase=='asc') + return "ASC" + else + return "DESC" + end + end + def get_order_by(order) if (order=='artist') - return "artists.artistname ASC, plays.playedtime DESC" + return "artists.artistname ASC, plays.playedtime" elsif (order=='track') - return "tracks.title ASC, plays.playedtime DESC" + return "tracks.title ASC, plays.playedtime" else - return "plays.playedtime DESC" + return "plays.playedtime" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' require_relative 'routes/info' # search artist by name get "/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end end \ No newline at end of file diff --git a/routes/play.rb b/routes/play.rb index 7df414b..86d4922 100644 --- a/routes/play.rb +++ b/routes/play.rb @@ -1,39 +1,40 @@ module V1 class PavApi < Sinatra::Base #PLAY get "/plays" do #DATE_FORMAT(playedtime, '%d %m %Y %H %i %S') artist_query = get_artist_query(params[:artist_query]) track_query = get_track_query(params[:track_query]) album_query = get_album_query(params[:album_query]) query_all = get_all_query(params[:q]) order_by = get_order_by(params[:order_by]) + order = get_order(params[:order]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) channel = get_channel(params[:channel]); program = get_program(params[:program]) - + puts order_by if artist_query or album_query or query_all or params[:order_by]=='artist' - @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE plays.id #{channel} #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}") + @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE plays.id #{channel} #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} #{order} limit #{limit}") else - @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{track_query} #{program} order by #{order_by} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") + @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{track_query} #{program} order by #{order_by} #{order} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") end hat = @plays.collect {|o| {:title => o.title, :track_id => o.track_id, :trackmbid => o.trackmbid, :artistname => o.artistname, :artist_id => o.artist_id, :artistmbid => o.artistmbid, :playedtime => o.playedtime, :albumname => o.albumname, :albumimage => o.albumimage, :album_id => o.album_id, :albummbid => o.albummbid, :program_id => o.program_id, :channel_id => o.channel_id} } respond_to do |wants| wants.html { erb :plays } wants.xml { builder :plays } wants.json { hat.to_json } end end get "/play/:id" do @play = Play.get(params[:id]) respond_to do |wants| wants.json { @play.to_json } end end end end \ No newline at end of file diff --git a/throttler.rb b/throttler.rb index c037a10..622f56e 100644 --- a/throttler.rb +++ b/throttler.rb @@ -1,18 +1,14 @@ -#MAX_REQUESTS_PER_HOUR = 10 -ABC_IP = '174.143.182.132' -module Rack; - module Throttle - class Throttler < Rack::Throttle::Interval - def initialize(app, options = {}) - super - end - def allowed?(request) - if request.ip.to_s == ABC_IP - true - else - super(request) - end - end +require 'rack/throttle' + +class ApiDefender < Rack::Throttle::Hourly + def initialize(app, options = {}) + super + end + def allowed?(request) + if request.ip.to_s =='203.2.218.145' + true + else + super(request) end end end \ No newline at end of file diff --git a/views/front.html.erb b/views/front.html.erb index 8503512..0543779 100644 --- a/views/front.html.erb +++ b/views/front.html.erb @@ -1,523 +1,524 @@ <section id="intro"> <div class="row"> <div class="span10 columns"> <p>The pav:api exposes playlist data and is currently under development.</p> <p>Have a look at the <a href="/<%= options.version %>/demo">app gallery</a> to see what can be built using pav:api.</p> <section id="general"> <h2 id="general">General Information</h2> <h3 id="general-query-parameters">Query Parameters</h3> <div>Some paths accepts the following query parameters. See each <a href="#resources">resource</a> type for more specifics.</div> <ul> <li><code>channel</code>, default is all channels, available on paths that returns a list of results</li> <li><code>limit</code>, default is 10, available on paths that returns a list results</li> <li><code>callback</code>, for cross-domain access jsonp is delivered to requests with 'callback' query parameter and json as return type</li> <li><code>format</code>, return type format (html, json, xml)</li> <li><code>type</code>, to specify lookup type, mbid</li> <li><code>to</code> (to date) in yyyy-mm-dd hh:mm:ss format. The hh:mm:ss part is optional, assumes 12:00:00 if absent</li> <li><code>from</code> (from date) in yyyy-mm-dd hh:mm:ss format. The hh:mm:ss part is optional, assumes 12:00:00 if absent</li> <li><code>order_by</code>, for ordering results. Default is playedtime. Allowed values are artist and track</li> + <li><code>order</code>, sort order. Default is DESC. Allowed values are ASC and DESC. Using ASC without at least a from date is not recommended.</li> <li><code>q</code>, a query for searching for track title, album name and artist name</li> <li><code>artist_query</code>, searching for an artist name</li> <li><code>track_query</code>, searching for a track title</li> <li><code>album_query</code>, searching for an album name</li> <li><code>program</code>, the program_id to limit result to a certain show</li> </ul> <p> <h3 id="general-identifiers">Identifiers</h3> To lookup a specific artist/track/album you can use pav IDs or Musicbrainz IDs where available. </p> <p> <h3 id="general-authentication">Authentication</h3> All put and post requests require authentication </p> <p> <h3 id="general-versioning">Versioning</h3> The version of the api you wish to use is specified at the root path of resources. The current version is v1. </p> <p> <h3 id="general-return-types">Return Types</h3> Return type can selected by appending the desired content type to the url (.html, .xml, .json) or by adding ?format=(html, xml, json) to the query parameter. Use only one of these methods when doing a request. <br /> Default return type is currently html but will change to json when the API is put in production. <br /> Client side cross domain requests are supported using either jsonp or <a href="http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing">CORS</a>. </p> <p> <h3 id="general-response-codes">Response Codes</h3> The API attempts to return appropriate HTTP status codes for every request. <ul> <li>200 OK: Request succeeded</li> <li>400 Bad Request: Your request was invalid and we'll return an error message telling you why</li> <li>401 Not Authorized: You did not provide the right credentials</li> <li>404 Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists</li> <li>500 Internal Server Error: Something is broken.</li> <li>503 Service Unavailable: You cannot make this request at this time. Servers are up, but overloaded with requests</li> </ul> </p> <p> <h3 id="general-terms">Terms</h3> Please be nice when using the api. If you plan to make massive amounts of calls please advise us. </p> </section> </div> <div class="span5 columns"> <h3>Table of Contents</h3> <ul class="unstyled"> <li><a href="#general">General Information</a></li> <ul> <li><a href="#general-query-parameters">Query Parameters</a></li> <li><a href="#general-identifiers">Identifiers</a></li> <li><a href="#general-authentication">Authentication</a></li> <li><a href="#general-versioning">Versioning</a></li> <li><a href="#general-return-types">Return Types</a></li> <li><a href="#general-response-codes">Reponse Codes</a></li> <li><a href="#general-terms">Terms</a></li> </ul> <li>&nbsp;</li> <li><a href="#resources">Resources</a></li> <ul> <li><a href="#resources-artists">Artists</a> <ul> <li><a href="#resources-artists-list">List of new artists</a></li> <li><a href="#resources-artist-single">A single artist</a></li> <li><a href="#resources-artist-albums">Albums from a specific artist</a></li> <li><a href="#resources-artist-tracks">Tracks from a specific artist</a></li> <li><a href="#resources-artist-plays">Plays from a specific artist</a></li> </ul> </li> <li><a href="#resources-tracks">Tracks</a> <ul> <li><a href="#resources-tracks-list">List of new tracks</a></li> <li><a href="#resources-track-single">A single track</a></li> <li><a href="#resources-track-artists">Artists related to a specific track</a></li> <li><a href="#resources-track-albums">Albums related to a specific track</a></li> <li><a href="#resources-track-plays">Plays of a specific track</a></li> <li><a href="#resources-track-new">Create a new play of a track</a></li> </ul> </li> <li><a href="#resources-albums">Albums</a> <ul> <li><a href="#resources-albums-list">List of new albums</a></li> <li><a href="#resources-album-single">A single album</a></li> <li><a href="#resources-album-tracks">Tracks on a specific album</a></li> </ul> </li> <li><a href="#resources-channels">Channels</a> <ul> <li><a href="#resources-channels-list">All channels</a></li> <li><a href="#resources-channel-single">A single channel</a></li> <li><a href="#resources-channel-new">Create a new channel</a></li> <li><a href="#resources-channel-edit">Edit a channel</a></li> </ul> </li> <li><a href="#resources-plays">Plays</a> <ul> <li><a href="#resources-plays-list">A playlist</a></li> <li><a href="#resources-play-single">A single play</a></li> </ul> </li> <li><a href="#resources-chart">Charts</a> <ul> <li><a href="#resources-chart-artist">An artist chart</a></li> <li><a href="#resources-chart-track">A track chart</a></li> <li><a href="#resources-chart-album">An album chart</a></li> </ul> </li> <li><a href="#resources-search">Search</a></li> </ul> </ul> </div> </div> </section> <section id="resources"> <h2 id="resources">Resources</h2> The resources that can be accessed through the api follows the model below: <div id="model-img"> <img id="resources-model" width="400px" src="/<%= options.version %>/images/models.png"/> </div> Some useful observation about the model: <ul> <li>An artist can have multiple tracks</li> <li>A track can have multiple artists</li> <li>A track can have multiple albums (a track appearing on different albums)</li> <li>An album can have multiple tracks</li> <li>A track can have multiple plays</li> <li>A play belongs to one track</li> <li>A play belongs to one channel</li> <li>A channel can have multiple plays</li> </ul> <p> </p> <h3 id="resources-artists">Artists</h3> <h4 id="resources-artists-list">/artists</h4> <div class='resource'> <h5>Description</h5> <p>Returns a list of artists</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/artists.json?channel=4">/artists.json?channel=4</a></code> <h5>Example response</h5> <script src="https://gist.github.com/967986.js"></script> </div> <h4 id="resources-artist-single">/artist/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single artist</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/artist/1234.json">/artist/1234.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/967997.js"></script> </div> <h4 id="resources-artist-tracks">/artist/:id/tracks</h4> <div class='resource'> <h5>Description</h5> <p>Returns the tracks related to a single artist</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code></p> <h5>Example query</h5> <code><a href="/<%= options.version %>/artist/1234/tracks.json">/artist/1234/tracks.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968001.js"></script> </div> <h4 id="resources-artist-albums">/artist/:id/albums</h4> <div class='resource'> <h5>Description</h5> <p>Returns the albums related to a single artist</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code></p> <h5>Example query</h5> <code><a href="/<%= options.version %>/artist/1234/albums.json">/artist/1234/albums.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/1185129.js"></script> </div> <h4 id="resources-artist-plays">/artist/:id/plays</h4> <div class='resource'> <h5>Description</h5> <p>Returns the plays related to a single artist</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>, <code>channel</code></p> <h5>Example query</h5> <code><a href="/<%= options.version %>/artist/1234/plays.json">/artist/1234/plays.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/956363.js"> </script> </div> <h3 id="resources-tracks">Tracks</h3> <h4 id="resources-tracks-list">/tracks</h4> <div class='resource'> <h5>Description</h5> <p>Returns a list of tracks</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/tracks.json?channel=4&limit=3">/tracks.json?channel=4&limit=3</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968008.js"></script> </div> <h4 id="resources-track-single">/track/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single track specified by an id.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/track/324.json">/track/324.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968013.js?file=gistfile1.json"></script> </div> <h4 id="resources-track-artists">/track/:id/artists</h4> <div class='resource'> <h5>Description</h5> <p>Returns the artists related to a single track</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/track/324/artists.json">/track/324/artists.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968022.js?file=gistfile1.json"></script> </div> <h4 id="resources-track-albums">/track/:id/albums</h4> <div class='resource'> <h5>Description</h5> <p>Returns the albums related to a single track</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/track/324/albums.json">/track/324/albums.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968023.js?file=gistfile1.json"></script> </div> <h4 id="resources-track-plays">/track/:id/plays</h4> <div class='resource'> <h5>Description</h5> <p>Returns the plays related to a single track.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/track/324/plays.json">/track/324/plays.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968025.js?file=gistfile1.json"></script> </div> <h4 id="resources-track-new">post /track</h4> <div class='resource'> <h5>Description</h5> <p>Post a track to pav. Requires authentication.</p> <h5>Parameters</h5> <p>A json payload</p> <script src="https://gist.github.com/968015.js?file=gistfile1.json"></script> <h5>Example response</h5> <p><code>200</code></p> </div> <h3 id="resources-albums">Albums</h3> <h4 id="resources-albums-list">/albums</h4> <div class='resource'> <h5>Description</h5> <p>Returns a list of albums.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/albums.json">/albums.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968027.js?file=gistfile1.json"></script> </div> <h4 id="resources-album-single">/album/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single album.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/album/15.json">/album/15.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968029.js?file=gistfile1.json"></script> </div> <h4 id="resources-album-tracks">/album/:id/tracks</h4> <div class='resource'> <h5>Description</h5> <p>Returns the tracks related to a single album.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/album/15/tracks.json">/album/15/tracks.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968035.js?file=gistfile1.json"></script> </div> <h3 id="resources-channels">Channels</h3> <h4 id="resources-channels-list">/channels</h4> <div class='resource'> <h5>Description</h5> <p>Returns a list of channels.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>limit</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/channels.json">/channels.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968054.js?file=gistfile1.json"></script> </div> <h4 id="resources-channel-single">/channel/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single channel.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/channel/1.json">/channel/1.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968058.js?file=gistfile1.json"></script> </div> <h4 id="resources-channel-new">post channel</h4> <div class='resource'> <h5>Description</h5> <p>Create a new channel.</p> <h5>Parameters</h5> <script src="https://gist.github.com/968061.js?file=gistfile1.json"></script> </div> <h4 id="resources-channel-edit">put channel/:id</h4> <div class='resource'> <h5>Description</h5> <p>Update a channel.</p> <h5>Parameters</h5> <script src="https://gist.github.com/968061.js?file=gistfile1.json"></script> </div> <h3 id="resources-plays">Plays</h3> <h4 id="resources-plays-list">/plays</h4> <div class='resource'> <h5>Description</h5> <p>Returns a playlist.</p> <h5>Parameters</h5> - <p>Supports the following parameters: <code>to</code>, <code>from</code>, <code>limit</code>, <code>channel</code>, <code>program</code>, <code>artist_query</code>, <code>track_query</code>, <code>album_query</code>, <code>q</code> (query artist, channel and track name), <code>order_by</code>.</p> + <p>Supports the following parameters: <code>to</code>, <code>from</code>, <code>limit</code>, <code>channel</code>, <code>program</code>, <code>artist_query</code>, <code>track_query</code>, <code>album_query</code>, <code>q</code> (query artist, channel and track name), <code>order_by</code>, <code>order</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/plays.json?channel=1&limit=3">/plays.json?channel=1&limit=3</a></code> <h5>Example response</h5> <script src="https://gist.github.com/956363.js"> </script> </div> <h4 id="resources-play-single">/play/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single play.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/play/4356.json">/play/4356.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968064.js?file=gistfile1.json"></script> </div> <h3 id="resources-chart">Charts</h3> <h4 id="resources-chart-artist">/chart/artist</h4> <div class='resource'> <h5>Description</h5> <p>A chart of most played artists for a given period.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>, <code>to</code>, <code>from</code>, <code>program</code>. If no to/from parameter is provided we return a chart from the last 7 days.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/chart/artist.json?channel=1">/chart/artist.json?channel=1</a></code> <h5>Example response</h5> <script src="https://gist.github.com/973721.js?file=gistfile1.json"></script> </div> <h4 id="resources-chart-track">/chart/track</h4> <div class='resource'> <h5>Description</h5> <p>A chart of most played tracks for a given period.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>, <code>to</code>, <code>from</code>, <code>program</code>. If no to/from parameter is provided we return a chart from the last 7 days.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/chart/track.json?from=2011-04-20">/chart/track.json?from=2011-04-20</a></code> <h5>Example response</h5> <script src="https://gist.github.com/973726.js?file=gistfile1.json"></script> </div> <h4 id="resources-chart-album">/chart/album</h4> <div class='resource'> <h5>Description</h5> <p>A chart of most played albums for a given period.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>, <code>to</code>, <code>from</code>, <code>program</code>. If no to/from parameter is provided we return a chart from the last 7 days.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/chart/album.json?limit=5&channel=4">/chart/album.json?limit=5&channel=4</a></code> <h5>Example response</h5> <script src="https://gist.github.com/973730.js?file=gistfile1.json"></script> </div> <h3 id="resources-search">Search</h3> <div class='resource'> <h5>Description</h5> <p>Search for artists (tracks and albums to come).</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>limit</code>.</p> <h5>Example query</h5> <code><a href="/<%= options.version %>/search/dylan.json?limit=5">/search/dylan.json?limit=5</a></code> <h5>Example response</h5> <script src="https://gist.github.com/973733.js?file=gistfile1.json"></script> </div> </section> <style type="text/css" media="screen"> .gist-syntax .s2 { color: black; } .gist .gist-file .gist-data{ font-size:75%; } .gist .gist-file .gist-meta{ display:none; } </style>
simonhn/pav-api
eeb3879ab62e1964a6e9096bc40b475f36e9862f
trying foreman as daemon manager
diff --git a/Gemfile b/Gemfile index c400852..3cf1f06 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,34 @@ source :rubygems gem 'sinatra', '=1.2.6' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' gem 'chronic_duration' gem 'chronic' gem 'sinatra-respond_to', '=0.7.0' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' gem 'stalker' -gem 'i18n' \ No newline at end of file +gem 'i18n' + +gem 'foreman' +gem 'daemons' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 542443e..6eb752c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,91 +1,99 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) + daemons (1.1.4) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) + foreman (0.36.1) + term-ansicolor (~> 1.0.7) + thor (>= 0.13.6) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) newrelic_rpm (3.3.1) numerizer (0.1.1) rack (1.3.5) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) sinatra (1.2.6) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) sinatra-respond_to (0.7.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure + term-ansicolor (1.0.7) + thor (0.14.6) tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack + daemons dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps + foreman i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client sinatra (= 1.2.6) sinatra-respond_to (= 0.7.0) stalker yajl-ruby diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..2e361ba --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +worker: bundle exec stalk jobs.rb \ No newline at end of file diff --git a/jobs.rb b/jobs.rb index ecd66f3..02a9a8f 100644 --- a/jobs.rb +++ b/jobs.rb @@ -1,188 +1,188 @@ #datamapper stuff require 'dm-core' require 'dm-timestamps' require 'dm-aggregates' require 'dm-migrations' -require './models.rb' +require_relative 'models' #template systems require 'yajl/json_gem' require 'builder' #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' pwd = File.dirname(File.expand_path(__FILE__)) $LOG = Logger.new(pwd+'/log/queue.log', 'monthly') #setup MySQL connection: @config = YAML::load( File.open(pwd +'/config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #Method that stores each playitem to database. Index is the id of the channel to associate the play with def store_hash(item, index) @albums = nil mbid_hash = nil duration = ChronicDuration.parse(item["duration"].to_s) #there can be multiple artist seperated by '+' so we split them artist_array = item['artist']['artistname'].split("+") artist_array.each{ |artist_item| begin artist = artist_item.strip.force_encoding('UTF-8') track = item['title'].force_encoding('UTF-8') album = item['album']['albumname'].force_encoding('UTF-8') #for each item, lookup in musicbrainz. Returns hash with mbids for track, album and artist if found mbid_hash = mbid_lookup(artist,track,album) puts mbid_hash.inspect rescue StandardError => e $LOG.info("Issue while processing #{artist_item.strip} - #{item['title']} - #{e.backtrace}") end #ARTIST if !mbid_hash.nil? && !mbid_hash["artistmbid"].nil? @artist = Artist.first_or_create({:artistmbid => mbid_hash["artistmbid"]},{:artistmbid => mbid_hash["artistmbid"],:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) else @artist = Artist.first_or_create({:artistname => artist_item.strip},{:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) end #store artist_id / channel_id to a lookup table, for faster selects @artist_channels = @artist.channels << Channel.get(index) @artist_channels.save #ALBUM #creating and saving album if not exists if !item['album']['albumname'].empty? if !mbid_hash.nil? && !mbid_hash["albummbid"].nil? #puts "album mbid found for: " + mbid_hash["albummbid"] @albums = Album.first_or_create({:albummbid => mbid_hash["albummbid"]},{:albummbid => mbid_hash["albummbid"], :albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) else @albums = Album.first_or_create({:albumname => item['album']['albumname']},{:albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) end end #Track #creating and saving track if mbid_hash && !mbid_hash["trackmbid"].nil? @tracks = Track.first_or_create({:trackmbid => mbid_hash["trackmbid"]},{:trackmbid => mbid_hash["trackmbid"],:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:publisher => item['publisher'], :datecopyrighted => item['datecopyrighted'].to_i}) else @tracks = Track.first_or_create({:title => item['title'],:duration => duration},{:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:duration => duration,:publisher => item['publisher'],:datecopyrighted => item['datecopyrighted'].to_i}) end #add the track to album - if album exists if [email protected]? @album_tracks = @albums.tracks << @tracks @album_tracks.save end #add the track to the artist @artist_tracks = @artist.tracks << @tracks @artist_tracks.save #adding play: only add if playedtime does not exsist in the database already play_items = Play.count(:playedtime=>item['playedtime'], :channel_id=>index) #if no program, dont insert anything if item['program_id'] == '' item['program_id'] = nil end if play_items < 1 @play = Play.create(:track_id =>@tracks.id, :channel_id => index, :playedtime=>item['playedtime'], :program_id => item['program_id']) @plays = @tracks.plays << @play @plays.save end } end def mbid_lookup(artist, track, album) result_hash = {} #we can only hit mbrainz once a second so we take a nap sleep 1 service = MusicBrainz::Webservice::Webservice.new(:user_agent => 'pavapi/1.0 ([email protected])') q = MusicBrainz::Webservice::Query.new(service) #TRACK if !album.empty? t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :release=>album, :limit => 5) else t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :limit => 5) end t_results = q.get_tracks(t_filter) puts t_results.inspect #No results from the 'advanced' query, so trying artist and album individualy if t_results.count == 0 #ARTIST sleep 1 t_filter = MusicBrainz::Webservice::ArtistFilter.new(:name=>artist) t_results = q.get_artists(t_filter) if t_results.count > 0 x = t_results.first if x.score == 100 && is_ascii(String(x.entity.name)) && String(x.entity.name).casecmp(artist)==0 #puts 'ARTIST score: ' + String(x.score) + '- artist: ' + String(x.entity.name) + ' - artist mbid '+ String(x.entity.id.uuid) result_hash["artistmbid"] = String(x.entity.id.uuid) end end #ALBUM if !album.empty? sleep 1 t_filter = MusicBrainz::Webservice::ReleaseGroupFilter.new(:artist=>artist, :title=>album) t_results = q.get_release_groups(t_filter) #puts "album results count "+t_results.count.to_s if t_results.count>0 x = t_results.first #puts 'ALBUM score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.id.uuid) +' - release title '+ String(x.entity.title) + ' - orginal album title: '+album if x.score == 100 && is_ascii(String(x.entity.title)) #&& String(x.entity.title).casecmp(album)==0 #puts 'abekat'+x.entity.id.uuid.inspect result_hash["albummbid"] = String(x.entity.id.uuid) end end end elsif t_results.count > 0 t_results.each{ |x| #puts 'score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.artist.id.uuid) + ' - track mbid: ' + String(x.entity.id.uuid) + ' - track: ' + String(x.entity.title) +' - album: ' + String(x.entity.releases[0]) +' - album mbid: '+ String(x.entity.releases[0].id.uuid) if x.score == 100 && is_ascii(String(x.entity.artist)) sleep 1 t_include = MusicBrainz::Webservice::ReleaseIncludes.new(:release_groups=>true) release = q.get_release_by_id(x.entity.releases[0].id.uuid, t_include) result_hash["trackmbid"] = String(x.entity.id.uuid) result_hash["artistmbid"] = String(x.entity.artist.id.uuid) result_hash["albummbid"] = String(release.release_group.id.uuid) end } end return result_hash end def is_ascii(item) cd = CharDet.detect(item) encoding = cd['encoding'] return encoding == 'ascii' end job 'track.store' do |args| store_hash(args['item'], args['channel'].to_i) error do |e, job, args| $LOG.info("error e #{e}") $LOG.info("error job #{job.inspect}") $LOG.info("error args #{args.inspect}") end end
simonhn/pav-api
eeb192c4b585ee9a26b17e021e88bc37490c3bf4
adding info on server stack
diff --git a/pavapi.rb b/pavapi.rb index 0a1635d..121ce97 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,294 +1,295 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' #Queueing with stalker/beanstalkd require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' module V1 class PavApi < Sinatra::Base configure do set :environment, :development set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') set :views, File.join(File.dirname(__FILE__), '/views') set :public, File.join(File.dirname(__FILE__), '/public') #versioning set :version, 'v1' register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :debug ) $LOG = Logger.new(File.join(File.dirname(__FILE__),'log/pavstore.log'), 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' + require_relative 'routes/info' # search artist by name get "/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end end \ No newline at end of file diff --git a/routes/info.rb b/routes/info.rb new file mode 100644 index 0000000..bbed037 --- /dev/null +++ b/routes/info.rb @@ -0,0 +1,11 @@ +module V1 +class PavApi < Sinatra::Base + +get "/info" do + respond_to do |wants| + wants.html { erb :info } + end +end + +end +end diff --git a/views/info.html.erb b/views/info.html.erb new file mode 100644 index 0000000..d4da1f6 --- /dev/null +++ b/views/info.html.erb @@ -0,0 +1,9 @@ +<h2>Server information</h2> +<p>A high level overview of the different systems used in our stack</p> +<ul> + <li>centos 5.6 linux</li> + <li>varnish 3.0.0 as reverse proxy in front of apache 2.2.3</li> + <li>sinatra app (ruby 1.9.2 with rvm) running on rack and passenger</li> + <li>beanstalkd as worker queue</li> + <li>mysql 5.0.77</li> +</ul>
simonhn/pav-api
dea39e5ae7225660fdd8bbebbb14c9a287bd5ff3
cleaning up unused files and unused statements
diff --git a/.gitignore b/.gitignore index 1438495..86d802c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,14 @@ log/*.log config/settings.yml config/deploy.rb config/deploy/* .bundle\n .yardoc/ Capfile Rakefile config/capistrano_database.rb config/deploy.rb.old doc/ log/ *.pid -*.output -storetrackjob.rb \ No newline at end of file +*.output \ No newline at end of file diff --git a/pavapi.rb b/pavapi.rb index 781cec3..0a1635d 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,297 +1,294 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' -require_relative 'store_methods' -#Queueing with delayed job -#require 'delayed_job' -#require 'delayed_job_data_mapper' -#require './storetrackjob' +#Queueing with stalker/beanstalkd require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' + module V1 class PavApi < Sinatra::Base configure do set :environment, :development set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') set :views, File.join(File.dirname(__FILE__), '/views') set :public, File.join(File.dirname(__FILE__), '/public') #versioning set :version, 'v1' register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :debug ) $LOG = Logger.new(File.join(File.dirname(__FILE__),'log/pavstore.log'), 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name get "/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end end \ No newline at end of file diff --git a/store_methods.rb b/store_methods.rb deleted file mode 100644 index 6c22bf2..0000000 --- a/store_methods.rb +++ /dev/null @@ -1,123 +0,0 @@ - #Method that stores each playitem to database. Index is the id of the channel to associate the play with - def store_hash(item, index) - mbid_hash = nil - duration = ChronicDuration.parse(item["duration"].to_s) - - #there can be multiple artist seperated by '+' so we split them - artist_array = item['artist']['artistname'].split("+") - artist_array.each{ |artist_item| - begin - #for each item, lookup in musicbrainz. Returns hash with mbids for track, album and artist if found - mbid_hash = mbid_lookup(artist_item.strip, item['title'], item['album']['albumname']) - - rescue StandardError => e - $LOG.info("Issue while processing #{artist_item.strip} - #{item['title']} - #{item['album']['albumname']} - #{e.backtrace}") - end - #ARTIST - if !mbid_hash["artistmbid"].nil? - @artist = Artist.first_or_create({:artistmbid => mbid_hash["artistmbid"]},{:artistmbid => mbid_hash["artistmbid"],:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) - else - @artist = Artist.first_or_create({:artistname => artist_item.strip},{:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) - end - - #store artist_id / channel_id to a lookup table, for faster selects - @artist_channels = @artist.channels << Channel.get(index) - @artist_channels.save - - #ALBUM - #creating and saving album if not exists - if !item['album']['albumname'].empty? - if !mbid_hash["albummbid"].nil? - #puts "album mbid found for: " + mbid_hash["albummbid"] - @albums = Album.first_or_create({:albummbid => mbid_hash["albummbid"]},{:albummbid => mbid_hash["albummbid"], :albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) - else - @albums = Album.first_or_create({:albumname => item['album']['albumname']},{:albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) - end - end - - - #Track - #creating and saving track - if !mbid_hash["trackmbid"].nil? - @tracks = Track.first_or_create({:trackmbid => mbid_hash["trackmbid"]},{:trackmbid => mbid_hash["trackmbid"],:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:publisher => item['publisher'], :datecopyrighted => item['datecopyrighted'].to_i}) - else - @tracks = Track.first_or_create({:title => item['title'],:duration => duration},{:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:duration => duration,:publisher => item['publisher'],:datecopyrighted => item['datecopyrighted'].to_i}) - end - - #add the track to album - if album exists - if [email protected]? - @album_tracks = @albums.tracks << @tracks - @album_tracks.save - end - - #add the track to the artist - @artist_tracks = @artist.tracks << @tracks - @artist_tracks.save - - #adding play: only add if playedtime does not exsist in the database already - play_items = Play.count(:playedtime=>item['playedtime'], :channel_id=>index) - if play_items < 1 - @play = Play.create(:track_id =>@tracks.id, :channel_id => index, :playedtime=>item['playedtime']) - @plays = @tracks.plays << @play - @plays.save - end - - } - end - -def mbid_lookup(artist, track, album) - result_hash = {} - - #we can only hit mbrainz once a second so we take a nap - sleep 1 - service = MusicBrainz::Webservice::Webservice.new(:user_agent => 'pavapi/1.0') - q = MusicBrainz::Webservice::Query.new(service) - - #TRACK - t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :release=>album, :limit => 5) - #t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :limit => 5) - t_results = q.get_tracks(t_filter) - - #No results from the 'advanced' query, so trying artist and album individualy - if t_results.count == 0 - #ARTIST - t_filter = MusicBrainz::Webservice::ArtistFilter.new(:name=>artist) - t_results = q.get_artists(t_filter) - if t_results.count > 0 - x = t_results.first - if x.score == 100 && is_ascii(String(x.entity.name)) && String(x.entity.name).casecmp(artist)==0 - #puts 'ARTIST score: ' + String(x.score) + '- artist: ' + String(x.entity.name) + ' - artist mbid '+ String(x.entity.id.uuid) - result_hash["artistmbid"] = String(x.entity.id.uuid) - end - end - - #ALBUM - t_filter = MusicBrainz::Webservice::ReleaseFilter.new(:artist=>artist, :title=>album) - t_results = q.get_releases(t_filter) - #puts "album results count "+t_results.count.to_s - if t_results.count==1 - x = t_results.first - #puts 'ALBUM score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.id.uuid) +' - release title '+ String(x.entity.title) + ' - orginal album title: '+album - if x.score == 100 && is_ascii(String(x.entity.title)) #&& String(x.entity.title).casecmp(album)==0 - result_hash["albummbid"] = String(x.entity.id.uuid) - end - end - - elsif t_results.count > 0 - t_results.each{ |x| - #puts 'score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.artist.id.uuid) + ' - track mbid: ' + String(x.entity.id.uuid) + ' - track: ' + String(x.entity.title) +' - album: ' + String(x.entity.releases[0]) +' - album mbid: '+ String(x.entity.releases[0].id.uuid) - if x.score == 100 && is_ascii(String(x.entity.artist)) - result_hash["trackmbid"] = String(x.entity.id.uuid) - result_hash["artistmbid"] = String(x.entity.artist.id.uuid) - result_hash["albummbid"] = String(x.entity.releases[0].id.uuid) - end - } - end - return result_hash -end - -def is_ascii(item) - cd = CharDet.detect(item) - encoding = cd['encoding'] - return encoding == 'ascii' -end \ No newline at end of file
simonhn/pav-api
519f78a248d3a114926afa44bdae720f45e13787
fixing version path
diff --git a/views/duplicate_artists.html.erb b/views/duplicate_artists.html.erb index 1403fb8..828e63d 100644 --- a/views/duplicate_artists.html.erb +++ b/views/duplicate_artists.html.erb @@ -1,49 +1,49 @@ <p> - <form action='/admin/merge/artist' method="POST" class="form-stacked"> + <form action='/<%= options.version %>/admin/merge/artist' method="POST" class="form-stacked"> <label for="id_old">Artist to delete</label> <input type="text" name="id_old" /> <label for="id_new">Artist to keep</label> <input type="text" name="id_new" /> <input class="btn small danger" type="submit" value="Merge!" /> <input class="btn small" type="reset"/> </form> </p> <p> <table> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <% @list.each do |track| %> <tr> <td><button class="keep btn small" data-keep="<%= track.id %>">keep</button></td> <td><button class="delete btn small" data-delete="<%= track.id %>">delete</button></td> <td><a href="/<%= options.version %>/artist/<%= track.id %>"><%= track.id %></td> <td> <span><% if !track.artistmbid.nil? %><a href="http://musicbrainz.org/artist/<%= track.artistmbid %>.html"><%= track.artistname %></a> <% else %> <%= track.artistname %><% end %></span> </span> </td> </tr> <% end %> </tbody> </table> </p> <script> $('.keep').bind('click', function(e) { $("input[name='id_new']").val(''); var id = $(this).attr('data-keep'); $("input[name='id_new']").val(id); }); $('.delete').bind('click', function(e) { $("input[name='id_old']").val(''); var id = $(this).attr('data-delete'); $("input[name='id_old']").val(id); }); </script>
simonhn/pav-api
754f8beaeece2b47e3e10e146b7e1f3430342788
ignoring storetrack.jon
diff --git a/.gitignore b/.gitignore index 86d802c..1438495 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,15 @@ log/*.log config/settings.yml config/deploy.rb config/deploy/* .bundle\n .yardoc/ Capfile Rakefile config/capistrano_database.rb config/deploy.rb.old doc/ log/ *.pid -*.output \ No newline at end of file +*.output +storetrackjob.rb \ No newline at end of file
simonhn/pav-api
3ab0bad3711fd0f4cd066b3933b0116e274b5459
setup versioning
diff --git a/Gemfile.lock b/Gemfile.lock index 5ea6128..542443e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,91 +1,91 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) newrelic_rpm (3.3.1) numerizer (0.1.1) - rack (1.4.0) + rack (1.3.5) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) sinatra (1.2.6) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) sinatra-respond_to (0.7.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client sinatra (= 1.2.6) sinatra-respond_to (= 0.7.0) stalker yajl-ruby diff --git a/config.ru b/config.ru index 495d8ac..f280a07 100644 --- a/config.ru +++ b/config.ru @@ -1,4 +1,7 @@ require File.join(File.dirname(__FILE__), 'pavapi.rb') use Rack::JSONP +map "/v1" do + run V1::PavApi +end -run PavApi \ No newline at end of file +#run PavApi \ No newline at end of file diff --git a/pavapi.rb b/pavapi.rb index 9557317..781cec3 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,295 +1,297 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' - -class PavApi < Sinatra::Base +module V1 + class PavApi < Sinatra::Base configure do set :environment, :development set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') + set :views, File.join(File.dirname(__FILE__), '/views') + set :public, File.join(File.dirname(__FILE__), '/public') + #versioning - @version = "v1" + set :version, 'v1' register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: - @config = YAML::load( File.open( 'config/settings.yml' ) ) + @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html - end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging - DataMapper::Logger.new('log/datamapper.log', :warn ) + DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging - DataMapper::Logger.new('log/datamapper.log', :debug ) - $LOG = Logger.new('log/pavstore.log', 'monthly') + DataMapper::Logger.new(File.join(File.dirname(__FILE__), 'log/datamapper.log'), :debug ) + $LOG = Logger.new(File.join(File.dirname(__FILE__),'log/pavstore.log'), 'monthly') end - + #Caching before '/*' do - cache_control :public, :must_revalidate, :max_age => 60 + cache_control :public, :must_revalidate, :max_age => 60 end - + before '/demo/*' do - cache_control :public, :must_revalidate, :max_age => 3600 + cache_control :public, :must_revalidate, :max_age => 3600 end - + before '*/chart/*' do - cache_control :public, :must_revalidate, :max_age => 3600 + cache_control :public, :must_revalidate, :max_age => 3600 end - # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) - @config = YAML::load( File.open( 'config/settings.yml' ) ) + @config = YAML::load( File.open(File.join(File.dirname(__FILE__), 'config/settings.yml') ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name - get "/#{@version}/search/:q" do + get "/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end +end end \ No newline at end of file diff --git a/routes/admin.rb b/routes/admin.rb index 11e57c5..f7bd0c8 100644 --- a/routes/admin.rb +++ b/routes/admin.rb @@ -1,159 +1,161 @@ -class PavApi < Sinatra::Base +module V1 + class PavApi < Sinatra::Base #admin dashboard get "/admin" do protected! respond_to do |wants| wants.html { erb :admin } end end #Count all artists get "/admin/stats" do json_outout = {} #@dig_duration_avg = repository(:default).adapter.select("SELECT ROUND(AVG(duration),0) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE tracks.duration < 500 AND`plays`.`channel_id` = 1") #json_outout['dig_duration_avg'] = @dig_duration_avg.first.to_i.to_s #@all_duration_avg = Track.avg(:duration, :duration.lt => 500) #json_outout['all_duration_avg'] = @all_duration_avg.to_i.to_s @artistcount = Artist.count json_outout['all_artistcount'] = @artistcount @artistmbid = (Artist.count(:artistmbid).to_f/@artistcount.to_f)*100 @trackcount = Track.count json_outout['all_trackcount'] = @trackcount @trackmbid = (Track.count(:trackmbid).to_f/@trackcount.to_f)*100 @playcount = Play.count json_outout['all_playcount'] = @playcount @albumcount = Album.count json_outout['all_albumcount'] = @albumcount @albummbid = (Album.count(:albummbid).to_f/@albumcount.to_f)*100 @dig_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_play = Play.all('channel_id'=>1).count @jazz_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_play = Play.all('channel_id'=>2).count @country_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_play = Play.all('channel_id'=>3).count @jjj_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_play = Play.all('channel_id'=>4).count respond_to do |wants| wants.html { erb :stats } wants.json {json_outout.to_json} end end get "/admin/duplicate/artist" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.artistname, d2.artistmbid FROM artists d1 JOIN artists d2 ON d2.artistname = d1.artistname AND d2.id <> d1.id order by artistname, id") respond_to do |wants| wants.html { erb :duplicate_artists } end end post "/admin/merge/artist" do protected! old_artist = Artist.get(params[:id_old]) new_artist = Artist.get(params[:id_new]) if(old_artist&&new_artist) #move tracks from old artist to new artist link = ArtistTrack.all(:artist_id => old_artist.id) link.each{ |link_item| @track_load = Track.get(link_item.track_id) @moved = new_artist.tracks << @track_load @moved.save } #delete old artist_track relations link.destroy! #delete old artist old_artist.destroy! end redirect back end get "/admin/duplicate/album" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.albumname, d2.albummbid FROM albums d1 JOIN albums d2 ON d2.albumname = d1.albumname AND d2.id <> d1.id order by albumname, id") respond_to do |wants| wants.html { erb :duplicate_albums } end end post "/admin/merge/album" do protected! old_album = Album.get(params[:id_old]) old_album_tracks = old_album.tracks new_album = Album.get(params[:id_new]) new_album_tracks = new_album.tracks if(old_album&&new_album) #if there are similar track on the two albums, # move the 'old' tracks to the 'new' tracks before moving album links old_album_tracks.each{ |old_track| new_track = new_album_tracks.find {|e| e.title==old_track.title&&e.id!=old_track.id } if(new_track) merge_tracks(old_track.id, new_track.id) end } #move tracks from old album to new album link = AlbumTrack.all(:album_id => old_album.id) link.each{ |link_item| @track_load = Track.get(link_item.track_id) @moved = new_album.tracks << @track_load @moved.save } #delete old album_track relations link.destroy! #delete old album old_album.destroy! end redirect back end get "/admin/duplicate/track" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.title, d2.trackmbid FROM tracks d1 JOIN tracks d2 ON d2.title = d1.title AND d2.id <> d1.id order by title, id") respond_to do |wants| wants.html { erb :duplicate_tracks } end end post "/admin/merge/track" do protected! merge_tracks(params[:id_old], params[:id_new]) redirect back end +end end \ No newline at end of file diff --git a/routes/album.rb b/routes/album.rb index 3b9fe7e..bf7ae1f 100644 --- a/routes/album.rb +++ b/routes/album.rb @@ -1,76 +1,78 @@ +module V1 class PavApi < Sinatra::Base #show all albums -get "/#{@version}/albums" do +get "/albums" do limit = get_limit(params[:limit]) channel = params[:channel] if channel @albums = Album.all('tracks.plays.channel_id' => channel, :limit=>limit.to_i, :order => [:created_at.desc ]) else @albums = Album.all(:limit => limit.to_i, :order => [:created_at.desc ]) end respond_to do |wants| wants.html { erb :albums } wants.xml { builder :albums } wants.json { @albums.to_json } end end # show album from id -get "/#{@version}/album/:id" do +get "/album/:id" do if params[:type] == 'mbid' || params[:id].length == 36 @album = Album.first(:albummbid => params[:id]) else @album = Album.get(params[:id]) end respond_to do |wants| wants.html { erb :album } wants.xml { builder :album } wants.json {@album.to_json} end end # edit track from id. if ?type=mbid is added, it will perform a mbid lookup -get "/#{@version}/album/:id/edit" do +get "/album/:id/edit" do protected! if params[:type] == 'mbid' || params[:id].length == 36 @album = Album.first(:albummbid => params[:id]) else @album = Album.get(params[:id]) end respond_to do |wants| wants.html { erb :album_edit } end end -post "/#{@version}/album/:id/edit" do +post "/album/:id/edit" do protected! @album = Album.get(params[:id]) raise not_found unless @album @album.attributes = { :albumname => params["albumname"], :albummbid => params["albummbid"], :albumimage => params["albumimage"], :created_at => params["created_at"] } @album.save - redirect "/v1/album/#{@album.id}" + redirect "/#{options.version}/album/#{@album.id}" end # show tracks for an album -get "/#{@version}/album/:id/tracks" do +get "/album/:id/tracks" do if params[:type] == 'mbid' || params[:id].length == 36 @album = Album.first(:albummbid => params[:id]) else @album = Album.get(params[:id]) end @tracks = @album.tracks respond_to do |wants| wants.html { erb :album_tracks } wants.xml { builder :album_tracks } wants.json {@tracks.to_json } end end +end end \ No newline at end of file diff --git a/routes/artist.rb b/routes/artist.rb index a621905..fe2fc48 100644 --- a/routes/artist.rb +++ b/routes/artist.rb @@ -1,223 +1,225 @@ +module V1 class PavApi < Sinatra::Base #show all artists, defaults to 10, ordered by created date -get "/#{@version}/artists" do +get "/artists" do limit = get_limit(params[:limit]) channel = params[:channel] if channel @artists = Artist.all('tracks.plays.channel_id' => channel, :limit=>limit.to_i, :order => [:created_at.desc ]) else @artists = Artist.all(:limit => limit.to_i, :order => [:created_at.desc ]) end respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end # show artist from id. if ?type=mbid is added, it will perform a mbid lookup -get "/#{@version}/artist/:id" do +get "/artist/:id" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end respond_to do |wants| wants.html { erb :artist } wants.xml { builder :artist } wants.json { @artist.to_json } end end -get "/#{@version}/artist/:id/details" do +get "/artist/:id/details" do result = Hash.new #if no channel parameter provided, we assume all channels channel = get_channel(params[:channel]) if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end artist_result = Hash.new artist_result['artist_id'] = @artist.id artist_result['artistname'] = @artist.artistname result["artist"] = artist_result @play_count = repository(:default).adapter.select("SELECT plays.playedtime, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} order by playedtime") if !@play_count.empty? @tracks = repository(:default).adapter.select("SELECT count(plays.id) as play_count, tracks.title, tracks.id FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} group by tracks.id order by playedtime") result["tracks"] = @tracks.collect {|o| {:count => o.play_count, :title => o.title, :track_id => o.id} } @albums = @artist.tracks.albums result["albums"] = @albums.collect {|o| {:album_id => o.id, :albumname => o.albumname, :albumimage => o.albumimage} } result["play_count"] = @play_count.size programs = repository(:default).adapter.select("select count(plays.id) as play_count, program_id from plays, tracks, artist_tracks, artists where artists.id=#{@artist.id} AND artists.id = artist_tracks.artist_id AND artist_tracks.track_id=tracks.id and tracks.id=plays.track_id AND plays.program_id !='' group by program_id") result["programs"] = programs.collect {|o| {:play_count => o.play_count, :program_id => o.program_id} } first_play = @play_count.first #puts 'first played on '+Time.parse(first_play.playedtime.to_s).to_s result["first_play"] = Time.parse(first_play.playedtime.to_s).to_s last_play = @play_count.last #puts 'last played on '+Time.parse(last_play.playedtime.to_s).to_s result["last_play"] = Time.parse(last_play.playedtime.to_s).to_s average_duration = @artist.tracks.avg(:duration) #puts 'average track duration '+average_duration.inspect result["avg_duration"] = average_duration australian = @artist.tracks.first.aust #puts 'australian? '+australian.inspect result["australian"] = australian @artist_chart = repository(:default).adapter.select("select artists.artistname, artists.id, artist_tracks.artist_id, artists.artistmbid, count(*) as cnt from tracks, plays, artists, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id=artists.id #{channel} group by artists.id order by cnt desc") index_number = @artist_chart.index{|x|x[:id][email protected]} real_index = 1+index_number.to_i #puts 'Position on all time chart '+real_index.to_s result["chart_pos"] = real_index #@play_count_range, divides last - first into 10 time slots if @play_count.size > 1 #only makes sense if more than one play @time_range = (Time.parse(last_play.playedtime.to_s) - Time.parse(first_play.playedtime.to_s)) @slice = @time_range / 10 hat = Time.parse(first_play.playedtime.to_s) i = 0 result_array = [] while i < 10 do from = hat hat = hat + @slice to = hat to_from = "AND playedtime <= '#{to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime >= '#{from.strftime("%Y-%m-%d %H:%M:%S")}'" @play_counter = repository(:default).adapter.select("SELECT plays.playedtime, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} #{to_from} order by playedtime") item = Hash.new item["from"] = from.to_s item["to"] = to.to_s item["count"] = @play_counter.size.to_s result_array[i] = item i += 1 end #puts 'time sliced play count '+result_array.inspect result["time_sliced"] = result_array #average play counts per week from first played to now #@play_count.size @new_time_range = (Time.now - Time.parse(first_play.playedtime.to_s)) avg = @play_count.size/(@new_time_range/(60*60*24*7)) #puts 'avg plays per week '+ avg.to_s result["avg_play_week"] = avg else #when only 1 play: result["time_sliced"] = [] result["avg_play_week"] = 0 end #played on other channels? channel_result = Hash.new channels = Channel.all channels.each do |channel| q = repository(:default).adapter.select("SELECT count(*) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} AND plays.channel_id=#{channel.id}") if q.first.to_i>0 channel_result[channel.channelname] = q.first #puts 'played on ' + channel.channelname+' '+q.first.to_s+' times' end end result["channels"] = channel_result @res = result end respond_to do |wants| wants.json { result.to_json } end end # edit artist from id. if ?type=mbid is added, it will perform a mbid lookup -get "/#{@version}/artist/:id/edit" do +get "/artist/:id/edit" do protected! if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end respond_to do |wants| wants.html { erb :artist_edit } end end -post "/#{@version}/artist/:id/edit" do +post "/artist/:id/edit" do protected! @artist = Artist.get(params[:id]) raise not_found unless @artist @artist.attributes = { :artistname => params["artistname"], :artistmbid => params["artistmbid"], :artistlink => params["artistlink"], :artistnote => params["artistnote"] } @artist.save - redirect "/v1/artist/#{@artist.id}" + redirect "/#{options.version}/artist/#{@artist.id}" end # show tracks from artist -get "/#{@version}/artist/:id/tracks" do +get "/artist/:id/tracks" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end @tracks = @artist.tracks @tracks_json = repository(:default).adapter.select("SELECT count(plays.id) as play_count, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} group by tracks.id order by playedtime") respond_to do |wants| wants.html { erb :artist_tracks } wants.xml { builder :artist_tracks } wants.json { @tracks_json.to_json } end end # show albums from artist -get "/#{@version}/artist/:id/albums" do +get "/artist/:id/albums" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end @albums = @artist.tracks.albums respond_to do |wants| wants.html { erb :artist_albums } wants.xml { builder :artist_albums } wants.json { @albums.to_json } end end # show plays from artist -get "/#{@version}/artist/:id/plays" do +get "/artist/:id/plays" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end channel = params[:channel] limit = get_limit(params[:limit]) if channel @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE `plays`.`channel_id` = #{channel} AND artists.id=#{@artist.id} group by tracks.id, plays.playedtime order by plays.playedtime limit #{limit}") else @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE tracks.id AND artists.id=#{@artist.id} group by tracks.id, plays.playedtime order by plays.playedtime limit #{limit}") end hat = @plays.collect {|o| {:title => o.title, :track_id => o.track_id, :trackmbid => o.trackmbid, :artistname => o.artistname, :artist_id => o.artist_id, :artistmbid => o.artistmbid, :playedtime => o.playedtime, :albumname => o.albumname, :albumimage => o.albumimage, :album_id => o.album_id, :albummbid => o.albummbid, :program_id => o.program_id, :channel_id => o.channel_id} } respond_to do |wants| wants.html { erb :artist_plays } wants.xml { builder :artist_plays } wants.json { hat.to_json } end end +end end \ No newline at end of file diff --git a/routes/channel.rb b/routes/channel.rb index 8f495fb..5a3f64e 100644 --- a/routes/channel.rb +++ b/routes/channel.rb @@ -1,35 +1,37 @@ +module V1 class PavApi < Sinatra::Base # show all channels -get "/#{@version}/channels" do +get "/channels" do @channels = Channel.all respond_to do |wants| wants.xml { @channels.to_xml } wants.json { @channels.to_json } end end #create new channel -post "/#{@version}/channel" do +post "/channel" do protected! data = JSON.parse params[:payload].to_json channel = Channel.first_or_create({ :channelname => data['channelname'] }, { :channelname => data['channelname'],:channelxml => data['channelxml'], :logo => data['logo'], :channellink => data['channellink'] }) end #update a channel -put "/#{@version}/channel/:id" do +put "/channel/:id" do protected! channel = Channel.get(params[:id]) data = JSON.parse params[:payload].to_json channel = channel.update(:channelname => data['channelname'],:channelxml => data['channelxml'], :logo => data['logo'], :channellink => data['channellink']) end # show channel from id -get "/#{@version}/channel/:id" do +get "/channel/:id" do @channel = Channel.get(params[:id]) respond_to do |wants| wants.xml { @channel.to_xml } wants.json { @channel.to_json } end end +end end \ No newline at end of file diff --git a/routes/chart.rb b/routes/chart.rb index d5fcd32..066fac2 100644 --- a/routes/chart.rb +++ b/routes/chart.rb @@ -1,50 +1,52 @@ +module V1 class PavApi < Sinatra::Base # chart of top tracks -get "/#{@version}/chart/track" do +get "/chart/track" do program = get_program(params[:program]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) channel = get_channel(params[:channel]) @tracks = repository(:default).adapter.select("select *, cnt from (select tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at, count(*) as cnt from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{program} group by tracks.id order by cnt DESC limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") hat = @tracks.collect {|o| {:count => o.cnt, :title => o.title, :track_id => o.id, :artistname => o.artistname,:artistmbid => o.artistmbid, :trackmbid => o.trackmbid, :albumname => o.albumname, :albummbid => o.albummbid, :albumimage => o.albumimage} } respond_to do |wants| wants.html { erb :track_chart } wants.xml { builder :track_chart } wants.json { hat.to_json } end end # chart of top artist by name -get "/#{@version}/chart/artist" do +get "/chart/artist" do program = get_program(params[:program]) to_from = make_to_from(params[:from], params[:to]) limit = get_limit(params[:limit]) channel = get_channel(params[:channel]) @artists = repository(:default).adapter.select("select artists.id, artists.artistname, artists.artistmbid,count(*) as cnt from (select artist_tracks.artist_id from plays, tracks, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id #{channel} #{to_from} #{program}) as artist_tracks, artists where artist_tracks.artist_id=artists.id group by artists.id order by cnt desc limit #{limit}") #@artists = repository(:default).adapter.select("select sum(cnt) as count, har.artistname, har.id from (select artists.artistname, artists.id, artist_tracks.artist_id, count(*) as cnt from tracks, plays, artists, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id= artists.id #{to_from} group by tracks.id, plays.playedtime) as har group by har.artistname order by count desc limit #{limit}") hat = @artists.collect {|o| {:count => o.cnt, :artistname => o.artistname, :id => o.id, :artistmbid => o.artistmbid} } respond_to do |wants| wants.html { erb :artist_chart } wants.xml { builder :artist_chart } wants.json {hat.to_json} end end -get "/#{@version}/chart/album" do +get "/chart/album" do program = get_program(params[:program]) to_from = make_to_from(params[:from], params[:to]) limit = get_limit(params[:limit]) channel = get_channel(params[:channel]) @albums = repository(:default).adapter.select("select artists.artistname, artists.artistmbid, albums.albumname, albums.albumimage, albums.id as album_id, albums.albummbid, count(distinct album_tracks.pid) as cnt from (select album_tracks.album_id as aid, tracks.id as tid, plays.id as pid from tracks, plays, album_tracks where tracks.id = plays.track_id AND album_tracks.track_id = tracks.id #{channel} #{to_from} #{program}) as album_tracks, albums, artists, artist_tracks where albums.id = album_tracks.aid AND album_tracks.tid = artist_tracks.track_id AND artists.id = artist_tracks.artist_id group by albums.id order by cnt DESC limit #{limit}") hat = @albums.collect {|o| {:count => o.cnt, :artistname => o.artistname, :artistmbid => o.artistmbid, :albumname => o.albumname, :album_id => o.album_id, :albummbid => o.albummbid,:albumimage => o.albumimage} } respond_to do |wants| wants.html { erb :album_chart } wants.xml { builder :album_chart } wants.json {hat.to_json} end end +end end \ No newline at end of file diff --git a/routes/demo.rb b/routes/demo.rb index 6edfbb5..43777fe 100644 --- a/routes/demo.rb +++ b/routes/demo.rb @@ -1,127 +1,129 @@ +module V1 class PavApi < Sinatra::Base get '/demo/?' do respond_to do |wants| wants.html{erb :demo} end end get '/demo/album-charts' do from_date = DateTime.now - 7 @from_date_string = from_date.strftime("%b %e") to_date = DateTime.now @to_date_string = to_date.strftime("%b %e") respond_to do |wants| wants.html{erb :album_chart_all} end end get '/demo/program-chart' do redirect '/demo/program-chart/track' end get '/demo/program-chart/track' do @program = params[:program] @program ||= 'super_request' @span = params[:span] @span ||= 7 respond_to do |wants| wants.html{erb :program_chart_track} end end get '/demo/program-chart/artist' do @program = params[:program] @program ||= 'super_request' @span = params[:span] @span ||= 7 respond_to do |wants| wants.html{erb :program_chart_artist} end end get '/demo/program-chart/artist-expand' do @program = params[:program] @program ||= 'super_request' @span = params[:span] @span ||= 7 respond_to do |wants| wants.html{erb :program_chart_artist_expand} end end get '/demo/program-chart/album' do @program = params[:program] @program ||= 'super_request' @span = params[:span] @span ||= 7 respond_to do |wants| wants.html{erb :program_chart_album} end end get '/demo/jjj' do cache_control :public, :max_age => 600 artistmbid = {} har ='a' hur = 'b' @artists = repository(:default).adapter.select("select artists.artistname, artists.id, artist_tracks.artist_id, artists.artistmbid, count(*) as cnt from tracks, plays, artists, artist_tracks where plays.channel_id=4 AND tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id=artists.id group by artists.id order by cnt desc limit 10") #hat = @artists.collect {|o| {:count => o.cnt, :artistname => o.artistname, :id => o.id, :artistmbid => o.artistmbid} } all = Hash.new @artists.each{ |o| begin if o.artistmbid #puts o.artistname begin result = RestClient.get 'http://www.abc.net.au/triplej/media/artists/'+o.artistmbid+'/all-media.xml' if(result.code==200) all[o.artistname] = Hash.new all[o.artistname].store("media",Hash.new()) all[o.artistname].store("info",Hash.new()) all[o.artistname].fetch("info").store("mbid",o.artistmbid) all[o.artistname].fetch("info").store("count",o.cnt) xml = Crack::XML.parse(result) if(xml["rss"]["channel"]["item"].kind_of?(Array)) xml["rss"]["channel"]["item"].each_with_index{|ha,i| if !ha["title"].empty? && !ha["media:thumbnail"].first.nil? har = ha["title"] da = ha["media:thumbnail"] if da.kind_of?(Array) hur = da.first["url"] all[o.artistname].fetch("media").store(ha["title"],hur) else hur = da["url"] all[o.artistname].fetch("media").store(ha["title"],hur) end if ha["media:content"].kind_of?(Array) all[o.artistname].fetch("media").store(ha["media:content"].first["medium"],ha["media:content"].first["url"]) else all[o.artistname].fetch("media").store(ha["media:content"]["medium"],ha["media:content"]["url"]) end end } else if(!xml["rss"]["channel"]["item"]["title"].nil? && !xml["rss"]["channel"]["item"]["media:thumbnail"]["url"].nil?) har = xml["rss"]["channel"]["item"]["title"] hur = xml["rss"]["channel"]["item"]["media:thumbnail"]["url"] end end #john = @artists.map {|o| {:count => o.cnt, :artistname => o.artistname, :id => o.id, :artistmbid => o.artistmbid, :media=> {:title => har.to_s, :thumb=>hur.to_s}} } #puts john.inspect end rescue => e end end end } @hat = all respond_to do |wants| wants.html { erb :jjj } wants.json { all.to_json } end end end +end diff --git a/routes/play.rb b/routes/play.rb index 87f47da..7df414b 100644 --- a/routes/play.rb +++ b/routes/play.rb @@ -1,37 +1,39 @@ +module V1 class PavApi < Sinatra::Base #PLAY -get "/#{@version}/plays" do +get "/plays" do #DATE_FORMAT(playedtime, '%d %m %Y %H %i %S') artist_query = get_artist_query(params[:artist_query]) track_query = get_track_query(params[:track_query]) album_query = get_album_query(params[:album_query]) query_all = get_all_query(params[:q]) order_by = get_order_by(params[:order_by]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) channel = get_channel(params[:channel]); program = get_program(params[:program]) if artist_query or album_query or query_all or params[:order_by]=='artist' @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE plays.id #{channel} #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}") else @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{track_query} #{program} order by #{order_by} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") end hat = @plays.collect {|o| {:title => o.title, :track_id => o.track_id, :trackmbid => o.trackmbid, :artistname => o.artistname, :artist_id => o.artist_id, :artistmbid => o.artistmbid, :playedtime => o.playedtime, :albumname => o.albumname, :albumimage => o.albumimage, :album_id => o.album_id, :albummbid => o.albummbid, :program_id => o.program_id, :channel_id => o.channel_id} } respond_to do |wants| wants.html { erb :plays } wants.xml { builder :plays } wants.json { hat.to_json } end end -get "/#{@version}/play/:id" do +get "/play/:id" do @play = Play.get(params[:id]) respond_to do |wants| wants.json { @play.to_json } end end +end end \ No newline at end of file diff --git a/routes/track.rb b/routes/track.rb index 791cb67..67252d6 100644 --- a/routes/track.rb +++ b/routes/track.rb @@ -1,132 +1,135 @@ +module V1 class PavApi < Sinatra::Base #add new track item (an item in the playout xml) -post "/#{@version}/track" do +post "/track" do protected! begin data = JSON.parse params[:payload].to_json + puts Play.count(:playedtime => data['item']['playedtime'], :channel_id => data['channel'])==0 if !data['item']['artist']['artistname'].nil? && Play.count(:playedtime => data['item']['playedtime'], :channel_id => data['channel'])==0 Stalker.enqueue('track.store', :item => data['item'],:channel => data['channel']) #Delayed::Job.enqueue StoreTrackJob.new(data['item'], data['channel']) #store_hash(data['item'], data['channel']) end rescue StandardError => e $LOG.info("Post method end: Issue while processing #{data['item']['artist']['artistname']} - #{data['channel']}, #{e.backtrace}") end end #show tracks -get "/#{@version}/tracks" do +get "/tracks" do limit = get_limit(params[:limit]) channel = params[:channel] if channel @tracks = Track.all(Track.plays.channel_id => channel, :limit=>limit.to_i, :order => [:created_at.desc]) else @tracks = Track.all(:limit => limit.to_i, :order => [:created_at.desc ]) end respond_to do |wants| wants.html { erb :tracks } wants.xml { builder :tracks } wants.json {@tracks.to_json} end end # show track -get "/#{@version}/track/:id" do +get "/track/:id" do if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end respond_to do |wants| wants.html { erb :track } wants.xml { builder :track } wants.json {@track.to_json} end end # edit track from id. if ?type=mbid is added, it will perform a mbid lookup -get "/#{@version}/track/:id/edit" do +get "/track/:id/edit" do protected! if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end respond_to do |wants| wants.html { erb :track_edit } end end -post "/#{@version}/track/:id/edit" do +post "/track/:id/edit" do protected! @track = Track.get(params[:id]) raise not_found unless @track @track.attributes = { :title => params["title"], :trackmbid => params["trackmbid"], :tracklink => params["tracklink"], :tracknote => params["tracknote"], :talent => params["talent"], :aust => params["aust"], :datecopyrighted => params["datecopyrighted"], :show => params["show"], :publisher => params["publisher"], :created_at => params["created_at"] } @track.save - redirect "/v1/track/#{@track.id}" + redirect "/#{options.version}/track/#{@track.id}" end #show artists for a track -get "/#{@version}/track/:id/artists" do +get "/track/:id/artists" do if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end @artists = @track.artists respond_to do |wants| wants.html { erb :track_artists } wants.xml { builder :track_artists } wants.json {@artists.to_json} end end #show albums for a track -get "/#{@version}/track/:id/albums" do +get "/track/:id/albums" do if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end @albums = @track.albums respond_to do |wants| wants.html { erb :track_albums } wants.xml { builder :track_albums } wants.json {@albums.to_json} end end # show plays for a track -get "/#{@version}/track/:id/plays" do +get "/track/:id/plays" do if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end @plays = @track.plays respond_to do |wants| wants.html { erb :track_plays } wants.xml { builder :track_plays } wants.json {@plays.to_json} end end +end end \ No newline at end of file diff --git a/views/admin.html.erb b/views/admin.html.erb index 77649f0..abc4117 100644 --- a/views/admin.html.erb +++ b/views/admin.html.erb @@ -1,7 +1,7 @@ <h2>Admin dashboard</h2> <ul> - <li><a href="/admin/stats">Stats</a></li> - <li><a href="/admin/duplicate/artist">Duplicate artists</a></li> - <li><a href="/admin/duplicate/track">Duplicate tracks</a></li> - <li><a href="/admin/duplicate/album">Duplicate albums</a></li> + <li><a href="/<%= options.version %>/admin/stats">Stats</a></li> + <li><a href="/<%= options.version %>/admin/duplicate/artist">Duplicate artists</a></li> + <li><a href="/<%= options.version %>/admin/duplicate/track">Duplicate tracks</a></li> + <li><a href="/<%= options.version %>/admin/duplicate/album">Duplicate albums</a></li> </ul> \ No newline at end of file diff --git a/views/album_chart_all.html.erb b/views/album_chart_all.html.erb index 7526bda..36fe50f 100644 --- a/views/album_chart_all.html.erb +++ b/views/album_chart_all.html.erb @@ -1,293 +1,293 @@ <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script> <script src="http://jmar777.googlecode.com/svn/trunk/js/jquery.easing.1.3.js" type="text/javascript"></script> <script src="http://kwicks.googlecode.com/svn/branches/v1.5.1/Kwicks/jquery.kwicks-1.5.1.pack.js" type="text/javascript"></script> <div> <h2>Demo of Most Played Albums <%=@from_date_string%> to <%=@to_date_string%></h2> <div id="front_page_playlist_section"> <div class="heading_wrapper"> <div class="image_text_replacement"></div> </div> <div class="top_wrapper"> - <img src='/images/triplejlogo.gif'> + <img src='./../images/triplejlogo.gif'> <ul class="kwicks-jjj"> </ul> </div> </div> <div id="front_page_playlist_section"> <div class="heading_wrapper"> <div class="image_text_replacement"></div> </div> <div class="top_wrapper"> - <img src='/images/abcdigmusiclogo.gif'> + <img src='./../images/abcdigmusiclogo.gif'> <ul class="kwicks-dig"> </ul> </div> </div> <div id="front_page_playlist_section"> <div class="heading_wrapper"> <div class="image_text_replacement"></div> </div> <div class="top_wrapper"> - <img src='/images/abcjazzlogo.gif'> + <img src='./../images/abcjazzlogo.gif'> <ul class="kwicks-jazz"> </ul> </div> </div> <div id="front_page_playlist_section"> <div class="heading_wrapper"> <div class="image_text_replacement"></div> </div> <div class="top_wrapper"> - <img src='/images/abccountrylogo.gif'> + <img src='./../images/abccountrylogo.gif'> <ul class="kwicks-country"> </ul> </div> </div> <div id="front_page_playlist_section"> <div class="heading_wrapper"> <div class="image_text_replacement"></div> </div> <div class="top_wrapper"> - <img src='/images/abcradiologo.gif'> + <img src='./../images/abcradiologo.gif'> <h5>Combined view of triple j, ABC Dig Music, ABC Jazz and ABC Country</h5> <ul class="kwicks-combined"> </ul> </div> </div> </div> <script type="text/javascript"> $().ready(function() { $("<img id='loader'></img>") - .attr('src', "/images/ajax_loader.gif") + .attr('src', "./../images/ajax_loader.gif") .appendTo(".kwicks-jjj"); $.ajax({ url: "http://96.126.96.51/v1/chart/album", cache:true, jsonpCallback:'c1', dataType: "jsonp", data: { format:"json", channel: 4 }, success: function(data){ $(".kwicks-jjj #loader").remove(); $.each( data, function(i,item) { var count = i+1; var artist = item.artistname; content = '<li><div class="kwicks_inner"><div class="bigLetter"><img src="'+ item.albumimage +'"/><div id="number_overlay">'+count+'</div></div><div class="smallLetters"><i>'+ item.albumname+'</i><div id"kwick_artistname">'+artist + '</div></div></li>'; $(content).appendTo(".kwicks-jjj"); }); $('.kwicks-jjj').kwicks({ max: 189, duration: 400, spacing: 1, sticky: false }); } }); $("<img id='loader'></img>") - .attr('src', "/images/ajax_loader.gif") + .attr('src', "./../images/ajax_loader.gif") .appendTo(".kwicks-dig"); $.ajax({ url: "http://96.126.96.51/v1/chart/album", timeout : 40000, cache:true, jsonpCallback:'c2', dataType: "jsonp", data: { format:"json", channel: 1 }, success: function(data){ $(".kwicks-dig #loader").remove(); $.each( data, function(i,item) { var count = i+1; var artist = item.artistname; content = '<li><div class="kwicks_inner"><div class="bigLetter"><img src="'+ item.albumimage +'"/><div id="number_overlay">'+count+'</div></div><div class="smallLetters"><i>'+ item.albumname+'</i><div id"kwick_artistname">'+artist + '</div></div></li>'; $(content).appendTo(".kwicks-dig"); }); $('.kwicks-dig').kwicks({ max: 189, duration: 400, spacing: 1, sticky: false }); } }); $("<img id='loader'></img>") - .attr('src', "/images/ajax_loader.gif") + .attr('src', "./../images/ajax_loader.gif") .appendTo(".kwicks-jazz"); $.ajax({ url: "http://96.126.96.51/v1/chart/album", timeout : 40000, jsonpCallback:'c3', cache:true, dataType: "jsonp", data: { format:"json", channel: 2 }, success: function(data){ $(".kwicks-jazz #loader").remove(); $.each( data, function(i,item) { var count = i+1; var artist = item.artistname; content = '<li><div class="kwicks_inner"><div class="bigLetter"><img src="'+ item.albumimage +'"/><div id="number_overlay">'+count+'</div></div><div class="smallLetters"><i>'+ item.albumname+'</i><div id"kwick_artistname">'+artist + '</div></div></li>'; $(content).appendTo(".kwicks-jazz"); }); $('.kwicks-jazz').kwicks({ max: 189, duration: 400, spacing: 1, sticky: false }); } }); $("<img id='loader'></img>") - .attr('src', "/images/ajax_loader.gif") + .attr('src', "./../images/ajax_loader.gif") .appendTo(".kwicks-country"); $.ajax({ url: "http://96.126.96.51/v1/chart/album", timeout : 40000, cache:true, jsonpCallback:'c4', dataType: "jsonp", data: { format:"json", channel: 3 }, success: function(data){ $(".kwicks-country #loader").remove(); $.each( data, function(i,item) { var count = i+1; var artist = item.artistname; content = '<li><div class="kwicks_inner"><div class="bigLetter"><img src="'+ item.albumimage +'"/><div id="number_overlay">'+count+'</div></div><div class="smallLetters"><i>'+ item.albumname+'</i><div id"kwick_artistname">'+artist + '</div></div></li>'; $(content).appendTo(".kwicks-country"); }); $('.kwicks-country').kwicks({ max: 189, duration: 400, spacing: 1, sticky: false }); } }); $("<img id='loader'></img>") - .attr('src', "/images/ajax_loader.gif") + .attr('src', "./../images/ajax_loader.gif") .appendTo(".kwicks-combined"); $.ajax({ url: "http://96.126.96.51/v1/chart/album", timeout : 40000, cache:true, jsonpCallback:'c5', dataType: "jsonp", data: { format:"json" }, success: function(data){ $(".kwicks-combined #loader").remove(); $.each( data, function(i,item) { var count = i+1; var artist = item.artistname; content = '<li><div class="kwicks_inner"><div class="bigLetter"><img src="'+ item.albumimage +'"/><div id="number_overlay">'+count+'</div></div><div class="smallLetters"><i>'+ item.albumname+'</i><div id"kwick_artistname">'+artist + '</div></div></li>'; $(content).appendTo(".kwicks-combined"); }); $('.kwicks-combined').kwicks({ max: 189, duration: 400, spacing: 1, sticky: false }); } }); }); </script> <style type="text/css" media="screen"> header#main,div#wrapper{ width:700px; } #number_overlay{ display: block; position: absolute; width: 100%; top: 7%; top: 50%; left: -5; z-index: 2; text-align: right; font-size: 70px; letter-spacing: -13px; font-weight: bold; font-family:arial,helvetica,sans-serif; } #front_page_playlist_section {height:145px;} #front_page_playlist_section .top_wrapper{ border-top: 0px dotted #C9C9C9; padding-top: 20px; } /* defaults for all examples */ .kwicks-combined, .kwicks-jjj, .kwicks-dig, .kwicks-jazz, .kwicks-country { list-style: none; position: relative; margin: 0; padding: 0; padding-top:10px; } .kwicks-combined li, .kwicks-jjj li, .kwicks-dig li,.kwicks-jazz li,.kwicks-country li{ display: block; overflow: hidden; padding: 0; width: 69px } .kwicks_inner { width: 180px; } .bigLetter { float: left; margin-right:8px; position:relative; z-index:1; color:white; } .bigLetter img{ width: 69px; height:69px; } .smallLetters { display: none; font-size: 12px; width:100px; float:right; word-wrap: break-word; } #kwick_albumname{ color: #204BA1; } li.active .smallLetters { display: block; } </style> diff --git a/views/album_edit.html.erb b/views/album_edit.html.erb index ba350c5..ad79022 100644 --- a/views/album_edit.html.erb +++ b/views/album_edit.html.erb @@ -1,25 +1,25 @@ <style type="text/css" media="screen"> input,textarea{width:100%;} </style> <h2>album</h2> <p><%= @album.albumname %> - <%= @album.id %></p> -<form action='/v1/album/<%= @album.id %>/edit' method="POST"> +<form action='/<%= options.version %>/album/<%= @album.id %>/edit' method="POST"> <label for="albumname">title</label> <input type="text" name="albumname" value="<%= @album.albumname %>"/> <br> <label for="albummbid">MBID</label> <input type="text" name="albummbid" value="<%= @album.albummbid %>"/> <br> <label for="albumimage">image</label> <input type="text" name="albumimage" value="<%= @album.albumimage %>"/> <br> <label for="created_at">created date</label> <input type="text" name="created_at" value="<%= @album.created_at %>"/> <br> <input type="submit" value="Save" /> </form> \ No newline at end of file diff --git a/views/artist_details.xml.builder b/views/artist_details.xml.builder new file mode 100644 index 0000000..b43055b --- /dev/null +++ b/views/artist_details.xml.builder @@ -0,0 +1,7 @@ +xml.instruct! :xml, :version => '1.0' +xml.artist do [email protected] do |result| +xml.album :id => result.id do +end +end +end \ No newline at end of file diff --git a/views/artist_edit.html.erb b/views/artist_edit.html.erb index db34eb4..0e468a8 100644 --- a/views/artist_edit.html.erb +++ b/views/artist_edit.html.erb @@ -1,25 +1,25 @@ <style type="text/css" media="screen"> input,textarea{width:100%;} </style> <h2>Artist</h2> <p><%= @artist.artistname %> - <%= @artist.id %></p> -<form action='/v1/artist/<%= @artist.id %>/edit' method="POST"> +<form action='/<%= options.version %>/artist/<%= @artist.id %>/edit' method="POST"> <label for="artistmbid">Artist name</label> <input type="text" name="artistname" value="<%= @artist.artistname %>"/> <br> <label for="artistmbid">Artist MBID</label> <input type="text" name="artistmbid" value="<%= @artist.artistmbid %>"/> <br> <label for="artistlink">Artist link</label> <input type="text" name="artistlink" value="<%= @artist.artistlink %>"/> <br> <label for="artistnote">Artist Note</label> <textarea name="artistnote"><%= @artist.artistnote %></textarea> <br> <input type="submit" value="Save" /> </form> \ No newline at end of file diff --git a/views/demo.html.erb b/views/demo.html.erb index 26bab12..9b56d7b 100644 --- a/views/demo.html.erb +++ b/views/demo.html.erb @@ -1,9 +1,9 @@ <h2>App Gallery</h2> <ul> - <li><a href="/demo/program-chart/track?program=super_request">Program Track Chart</a></li> - <li><a href="/demo/program-chart/artist?program=super_request">Program Artist Chart</a></li> - <li><a href="/demo/program-chart/artist-expand?program=super_request">Program Artist Chart with detailed information</a></li> - <li><a href="/demo/program-chart/album?program=super_request">Program Album Chart</a></li> - <li><a href="/demo/album-charts">Album Charts</a></li> + <li><a href="/<%= options.version %>/demo/program-chart/track?program=super_request">Program Track Chart</a></li> + <li><a href="/<%= options.version %>/demo/program-chart/artist?program=super_request">Program Artist Chart</a></li> + <li><a href="/<%= options.version %>/demo/program-chart/artist-expand?program=super_request">Program Artist Chart with detailed information</a></li> + <li><a href="/<%= options.version %>/demo/program-chart/album?program=super_request">Program Album Chart</a></li> + <li><a href="/<%= options.version %>/demo/album-charts">Album Charts</a></li> <!--<li><a href="/demo/jjj">Triple j media integrated into chart</a></li>--> -</ul> \ No newline at end of file +</ul> diff --git a/views/duplicate_albums.html.erb b/views/duplicate_albums.html.erb index 3c0b087..ceb249b 100644 --- a/views/duplicate_albums.html.erb +++ b/views/duplicate_albums.html.erb @@ -1,50 +1,50 @@ <p> - <form action='/admin/merge/album' method="POST" class="form-stacked"> + <form action='/<%= options.version %>/admin/merge/album' method="POST" class="form-stacked"> <label for="id_old">Album to delete</label> <input type="text" name="id_old" /> <label for="id_new">Album to keep</label> <input type="text" name="id_new" /> <input class="btn small danger" type="submit" value="Merge!" /> <input class="btn small" type="reset"/> </form> </p> <p> <table> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <% @list.each do |track| %> <tr> <td><button class="keep btn small" data-keep="<%= track.id %>">keep</button></td> <td><button class="delete btn small" data-delete="<%= track.id %>">delete</button></td> - <td><a href="/v1/album/<%= track.id %>"><%= track.id %></td> + <td><a href="/<%= options.version %>/album/<%= track.id %>"><%= track.id %></td> <td> <span><% if !track.albummbid.nil? %><a href="http://musicbrainz.org/release-group/<%= track.albummbid %>.html"><%= track.albumname %></a> <% else %> <%= track.albumname %><% end %></span> </span> </td> </tr> <% end %> </tbody> </table> </p> <script> $('.keep').bind('click', function(e) { $("input[name='id_new']").val(''); var id = $(this).attr('data-keep'); $("input[name='id_new']").val(id); }); $('.delete').bind('click', function(e) { $("input[name='id_old']").val(''); var id = $(this).attr('data-delete'); $("input[name='id_old']").val(id); }); </script> diff --git a/views/duplicate_artists.html.erb b/views/duplicate_artists.html.erb index ec9018c..1403fb8 100644 --- a/views/duplicate_artists.html.erb +++ b/views/duplicate_artists.html.erb @@ -1,49 +1,49 @@ <p> <form action='/admin/merge/artist' method="POST" class="form-stacked"> <label for="id_old">Artist to delete</label> <input type="text" name="id_old" /> <label for="id_new">Artist to keep</label> <input type="text" name="id_new" /> <input class="btn small danger" type="submit" value="Merge!" /> <input class="btn small" type="reset"/> </form> </p> <p> <table> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <% @list.each do |track| %> <tr> <td><button class="keep btn small" data-keep="<%= track.id %>">keep</button></td> <td><button class="delete btn small" data-delete="<%= track.id %>">delete</button></td> - <td><a href="/v1/artist/<%= track.id %>"><%= track.id %></td> + <td><a href="/<%= options.version %>/artist/<%= track.id %>"><%= track.id %></td> <td> <span><% if !track.artistmbid.nil? %><a href="http://musicbrainz.org/artist/<%= track.artistmbid %>.html"><%= track.artistname %></a> <% else %> <%= track.artistname %><% end %></span> </span> </td> </tr> <% end %> </tbody> </table> </p> <script> $('.keep').bind('click', function(e) { $("input[name='id_new']").val(''); var id = $(this).attr('data-keep'); $("input[name='id_new']").val(id); }); $('.delete').bind('click', function(e) { $("input[name='id_old']").val(''); var id = $(this).attr('data-delete'); $("input[name='id_old']").val(id); }); </script> diff --git a/views/duplicate_tracks.html.erb b/views/duplicate_tracks.html.erb index 55e29c3..397f99c 100644 --- a/views/duplicate_tracks.html.erb +++ b/views/duplicate_tracks.html.erb @@ -1,49 +1,49 @@ <p> - <form action='/admin/merge/track' method="POST" class="form-stacked"> + <form action='/<%= options.version %>/admin/merge/track' method="POST" class="form-stacked"> <label for="id_old">Track to delete</label> <input type="text" name="id_old" /> <label for="id_new">Track to keep</label> <input type="text" name="id_new" /> <input class="btn small danger" type="submit" value="Merge!" /> <input class="btn small" type="reset"/> </form> </p> <p> <table> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <% @list.each do |track| %> <tr> <td><button class="keep btn small" data-keep="<%= track.id %>">keep</button></td> <td><button class="delete btn small" data-delete="<%= track.id %>">delete</button></td> - <td><a href="/v1/track/<%= track.id %>"><%= track.id %></td> + <td><a href="/<%= options.version %>/track/<%= track.id %>"><%= track.id %></td> <td> <span><% if !track.trackmbid.nil? %><a href="http://musicbrainz.org/track/<%= track.trackmbid %>.html"><%= track.title %></a> <% else %> <%= track.title %><% end %></span> </span> </td> </tr> <% end %> </tbody> </table> </p> <script> $('.keep').bind('click', function(e) { $("input[name='id_new']").val(''); var id = $(this).attr('data-keep'); $("input[name='id_new']").val(id); }); $('.delete').bind('click', function(e) { $("input[name='id_old']").val(''); var id = $(this).attr('data-delete'); $("input[name='id_old']").val(id); }); </script> \ No newline at end of file diff --git a/views/front.html.erb b/views/front.html.erb index 3884ded..8503512 100644 --- a/views/front.html.erb +++ b/views/front.html.erb @@ -1,521 +1,523 @@ <section id="intro"> <div class="row"> <div class="span10 columns"> <p>The pav:api exposes playlist data and is currently under development.</p> - <p>Have a look at the <a href='/demo'>app gallery</a> to see what can be built using pav:api.</p> + <p>Have a look at the <a href="/<%= options.version %>/demo">app gallery</a> to see what can be built using pav:api.</p> <section id="general"> <h2 id="general">General Information</h2> <h3 id="general-query-parameters">Query Parameters</h3> <div>Some paths accepts the following query parameters. See each <a href="#resources">resource</a> type for more specifics.</div> <ul> <li><code>channel</code>, default is all channels, available on paths that returns a list of results</li> <li><code>limit</code>, default is 10, available on paths that returns a list results</li> <li><code>callback</code>, for cross-domain access jsonp is delivered to requests with 'callback' query parameter and json as return type</li> <li><code>format</code>, return type format (html, json, xml)</li> <li><code>type</code>, to specify lookup type, mbid</li> <li><code>to</code> (to date) in yyyy-mm-dd hh:mm:ss format. The hh:mm:ss part is optional, assumes 12:00:00 if absent</li> <li><code>from</code> (from date) in yyyy-mm-dd hh:mm:ss format. The hh:mm:ss part is optional, assumes 12:00:00 if absent</li> <li><code>order_by</code>, for ordering results. Default is playedtime. Allowed values are artist and track</li> <li><code>q</code>, a query for searching for track title, album name and artist name</li> <li><code>artist_query</code>, searching for an artist name</li> <li><code>track_query</code>, searching for a track title</li> <li><code>album_query</code>, searching for an album name</li> <li><code>program</code>, the program_id to limit result to a certain show</li> </ul> <p> <h3 id="general-identifiers">Identifiers</h3> To lookup a specific artist/track/album you can use pav IDs or Musicbrainz IDs where available. </p> <p> <h3 id="general-authentication">Authentication</h3> All put and post requests require authentication </p> <p> <h3 id="general-versioning">Versioning</h3> The version of the api you wish to use is specified at the root path of resources. The current version is v1. </p> <p> <h3 id="general-return-types">Return Types</h3> Return type can selected by appending the desired content type to the url (.html, .xml, .json) or by adding ?format=(html, xml, json) to the query parameter. Use only one of these methods when doing a request. <br /> Default return type is currently html but will change to json when the API is put in production. + <br /> + Client side cross domain requests are supported using either jsonp or <a href="http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing">CORS</a>. </p> <p> <h3 id="general-response-codes">Response Codes</h3> The API attempts to return appropriate HTTP status codes for every request. <ul> <li>200 OK: Request succeeded</li> <li>400 Bad Request: Your request was invalid and we'll return an error message telling you why</li> <li>401 Not Authorized: You did not provide the right credentials</li> <li>404 Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists</li> <li>500 Internal Server Error: Something is broken.</li> <li>503 Service Unavailable: You cannot make this request at this time. Servers are up, but overloaded with requests</li> </ul> </p> <p> <h3 id="general-terms">Terms</h3> Please be nice when using the api. If you plan to make massive amounts of calls please advise us. </p> </section> </div> <div class="span5 columns"> <h3>Table of Contents</h3> <ul class="unstyled"> <li><a href="#general">General Information</a></li> <ul> <li><a href="#general-query-parameters">Query Parameters</a></li> <li><a href="#general-identifiers">Identifiers</a></li> <li><a href="#general-authentication">Authentication</a></li> <li><a href="#general-versioning">Versioning</a></li> <li><a href="#general-return-types">Return Types</a></li> <li><a href="#general-response-codes">Reponse Codes</a></li> <li><a href="#general-terms">Terms</a></li> </ul> <li>&nbsp;</li> <li><a href="#resources">Resources</a></li> <ul> <li><a href="#resources-artists">Artists</a> <ul> <li><a href="#resources-artists-list">List of new artists</a></li> <li><a href="#resources-artist-single">A single artist</a></li> <li><a href="#resources-artist-albums">Albums from a specific artist</a></li> <li><a href="#resources-artist-tracks">Tracks from a specific artist</a></li> <li><a href="#resources-artist-plays">Plays from a specific artist</a></li> </ul> </li> <li><a href="#resources-tracks">Tracks</a> <ul> <li><a href="#resources-tracks-list">List of new tracks</a></li> <li><a href="#resources-track-single">A single track</a></li> <li><a href="#resources-track-artists">Artists related to a specific track</a></li> <li><a href="#resources-track-albums">Albums related to a specific track</a></li> <li><a href="#resources-track-plays">Plays of a specific track</a></li> <li><a href="#resources-track-new">Create a new play of a track</a></li> </ul> </li> <li><a href="#resources-albums">Albums</a> <ul> <li><a href="#resources-albums-list">List of new albums</a></li> <li><a href="#resources-album-single">A single album</a></li> <li><a href="#resources-album-tracks">Tracks on a specific album</a></li> </ul> </li> <li><a href="#resources-channels">Channels</a> <ul> <li><a href="#resources-channels-list">All channels</a></li> <li><a href="#resources-channel-single">A single channel</a></li> <li><a href="#resources-channel-new">Create a new channel</a></li> <li><a href="#resources-channel-edit">Edit a channel</a></li> </ul> </li> <li><a href="#resources-plays">Plays</a> <ul> <li><a href="#resources-plays-list">A playlist</a></li> <li><a href="#resources-play-single">A single play</a></li> </ul> </li> <li><a href="#resources-chart">Charts</a> <ul> <li><a href="#resources-chart-artist">An artist chart</a></li> <li><a href="#resources-chart-track">A track chart</a></li> <li><a href="#resources-chart-album">An album chart</a></li> </ul> </li> <li><a href="#resources-search">Search</a></li> </ul> </ul> </div> </div> </section> <section id="resources"> <h2 id="resources">Resources</h2> The resources that can be accessed through the api follows the model below: <div id="model-img"> - <img id="resources-model" width="400px" src="images/models.png"/> + <img id="resources-model" width="400px" src="/<%= options.version %>/images/models.png"/> </div> Some useful observation about the model: <ul> <li>An artist can have multiple tracks</li> <li>A track can have multiple artists</li> <li>A track can have multiple albums (a track appearing on different albums)</li> <li>An album can have multiple tracks</li> <li>A track can have multiple plays</li> <li>A play belongs to one track</li> <li>A play belongs to one channel</li> <li>A channel can have multiple plays</li> </ul> <p> </p> <h3 id="resources-artists">Artists</h3> <h4 id="resources-artists-list">/artists</h4> <div class='resource'> <h5>Description</h5> <p>Returns a list of artists</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>.</p> <h5>Example query</h5> - <code><a href="/v1/artists.json?channel=4">/v1/artists.json?channel=4</a></code> + <code><a href="/<%= options.version %>/artists.json?channel=4">/artists.json?channel=4</a></code> <h5>Example response</h5> <script src="https://gist.github.com/967986.js"></script> </div> <h4 id="resources-artist-single">/artist/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single artist</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> - <code><a href="/v1/artist/1234.json">/v1/artist/1234.json</a></code> + <code><a href="/<%= options.version %>/artist/1234.json">/artist/1234.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/967997.js"></script> </div> <h4 id="resources-artist-tracks">/artist/:id/tracks</h4> <div class='resource'> <h5>Description</h5> <p>Returns the tracks related to a single artist</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code></p> <h5>Example query</h5> - <code><a href="/v1/artist/1234/tracks.json">/v1/artist/1234/tracks.json</a></code> + <code><a href="/<%= options.version %>/artist/1234/tracks.json">/artist/1234/tracks.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968001.js"></script> </div> <h4 id="resources-artist-albums">/artist/:id/albums</h4> <div class='resource'> <h5>Description</h5> <p>Returns the albums related to a single artist</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code></p> <h5>Example query</h5> - <code><a href="/v1/artist/1234/albums.json">/v1/artist/1234/albums.json</a></code> + <code><a href="/<%= options.version %>/artist/1234/albums.json">/artist/1234/albums.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/1185129.js"></script> </div> <h4 id="resources-artist-plays">/artist/:id/plays</h4> <div class='resource'> <h5>Description</h5> <p>Returns the plays related to a single artist</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>, <code>channel</code></p> <h5>Example query</h5> - <code><a href="/v1/artist/1234/plays.json">/v1/artist/1234/plays.json</a></code> + <code><a href="/<%= options.version %>/artist/1234/plays.json">/artist/1234/plays.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/956363.js"> </script> </div> <h3 id="resources-tracks">Tracks</h3> <h4 id="resources-tracks-list">/tracks</h4> <div class='resource'> <h5>Description</h5> <p>Returns a list of tracks</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>.</p> <h5>Example query</h5> - <code><a href="/v1/tracks.json?channel=4&limit=3">/v1/tracks.json?channel=4&limit=3</a></code> + <code><a href="/<%= options.version %>/tracks.json?channel=4&limit=3">/tracks.json?channel=4&limit=3</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968008.js"></script> </div> <h4 id="resources-track-single">/track/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single track specified by an id.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> - <code><a href="/v1/track/324.json">/v1/track/324.json</a></code> + <code><a href="/<%= options.version %>/track/324.json">/track/324.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968013.js?file=gistfile1.json"></script> </div> <h4 id="resources-track-artists">/track/:id/artists</h4> <div class='resource'> <h5>Description</h5> <p>Returns the artists related to a single track</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> - <code><a href="/v1/track/324/artists.json">/v1/track/324/artists.json</a></code> + <code><a href="/<%= options.version %>/track/324/artists.json">/track/324/artists.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968022.js?file=gistfile1.json"></script> </div> <h4 id="resources-track-albums">/track/:id/albums</h4> <div class='resource'> <h5>Description</h5> <p>Returns the albums related to a single track</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> - <code><a href="/v1/track/324/albums.json">/v1/track/324/albums.json</a></code> + <code><a href="/<%= options.version %>/track/324/albums.json">/track/324/albums.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968023.js?file=gistfile1.json"></script> </div> <h4 id="resources-track-plays">/track/:id/plays</h4> <div class='resource'> <h5>Description</h5> <p>Returns the plays related to a single track.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> - <code><a href="/v1/track/324/plays.json">/v1/track/324/plays.json</a></code> + <code><a href="/<%= options.version %>/track/324/plays.json">/track/324/plays.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968025.js?file=gistfile1.json"></script> </div> <h4 id="resources-track-new">post /track</h4> <div class='resource'> <h5>Description</h5> <p>Post a track to pav. Requires authentication.</p> <h5>Parameters</h5> <p>A json payload</p> <script src="https://gist.github.com/968015.js?file=gistfile1.json"></script> <h5>Example response</h5> <p><code>200</code></p> </div> <h3 id="resources-albums">Albums</h3> <h4 id="resources-albums-list">/albums</h4> <div class='resource'> <h5>Description</h5> <p>Returns a list of albums.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>.</p> <h5>Example query</h5> - <code><a href="/v1/albums.json">/v1/albums.json</a></code> + <code><a href="/<%= options.version %>/albums.json">/albums.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968027.js?file=gistfile1.json"></script> </div> <h4 id="resources-album-single">/album/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single album.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> - <code><a href="/v1/album/15.json">/v1/album/15.json</a></code> + <code><a href="/<%= options.version %>/album/15.json">/album/15.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968029.js?file=gistfile1.json"></script> </div> <h4 id="resources-album-tracks">/album/:id/tracks</h4> <div class='resource'> <h5>Description</h5> <p>Returns the tracks related to a single album.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>type</code>.</p> <h5>Example query</h5> - <code><a href="/v1/album/15/tracks.json">/v1/album/15/tracks.json</a></code> + <code><a href="/<%= options.version %>/album/15/tracks.json">/album/15/tracks.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968035.js?file=gistfile1.json"></script> </div> <h3 id="resources-channels">Channels</h3> <h4 id="resources-channels-list">/channels</h4> <div class='resource'> <h5>Description</h5> <p>Returns a list of channels.</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>limit</code>.</p> <h5>Example query</h5> - <code><a href="/v1/channels.json">/v1/channels.json</a></code> + <code><a href="/<%= options.version %>/channels.json">/channels.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968054.js?file=gistfile1.json"></script> </div> <h4 id="resources-channel-single">/channel/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single channel.</p> <h5>Example query</h5> - <code><a href="/v1/channel/1.json">/v1/channel/1.json</a></code> + <code><a href="/<%= options.version %>/channel/1.json">/channel/1.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968058.js?file=gistfile1.json"></script> </div> <h4 id="resources-channel-new">post channel</h4> <div class='resource'> <h5>Description</h5> <p>Create a new channel.</p> <h5>Parameters</h5> <script src="https://gist.github.com/968061.js?file=gistfile1.json"></script> </div> <h4 id="resources-channel-edit">put channel/:id</h4> <div class='resource'> <h5>Description</h5> <p>Update a channel.</p> <h5>Parameters</h5> <script src="https://gist.github.com/968061.js?file=gistfile1.json"></script> </div> <h3 id="resources-plays">Plays</h3> <h4 id="resources-plays-list">/plays</h4> <div class='resource'> <h5>Description</h5> <p>Returns a playlist.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>to</code>, <code>from</code>, <code>limit</code>, <code>channel</code>, <code>program</code>, <code>artist_query</code>, <code>track_query</code>, <code>album_query</code>, <code>q</code> (query artist, channel and track name), <code>order_by</code>.</p> <h5>Example query</h5> - <code><a href="/v1/plays.json?channel=1&limit=3">/v1/plays.json?channel=1&limit=3</a></code> + <code><a href="/<%= options.version %>/plays.json?channel=1&limit=3">/plays.json?channel=1&limit=3</a></code> <h5>Example response</h5> <script src="https://gist.github.com/956363.js"> </script> </div> <h4 id="resources-play-single">/play/:id</h4> <div class='resource'> <h5>Description</h5> <p>Returns a single play.</p> <h5>Example query</h5> - <code><a href="/v1/play/4356.json">/v1/play/4356.json</a></code> + <code><a href="/<%= options.version %>/play/4356.json">/play/4356.json</a></code> <h5>Example response</h5> <script src="https://gist.github.com/968064.js?file=gistfile1.json"></script> </div> <h3 id="resources-chart">Charts</h3> <h4 id="resources-chart-artist">/chart/artist</h4> <div class='resource'> <h5>Description</h5> <p>A chart of most played artists for a given period.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>, <code>to</code>, <code>from</code>, <code>program</code>. If no to/from parameter is provided we return a chart from the last 7 days.</p> <h5>Example query</h5> - <code><a href="/v1/chart/artist.json?channel=1">/v1/chart/artist.json?channel=1</a></code> + <code><a href="/<%= options.version %>/chart/artist.json?channel=1">/chart/artist.json?channel=1</a></code> <h5>Example response</h5> <script src="https://gist.github.com/973721.js?file=gistfile1.json"></script> </div> <h4 id="resources-chart-track">/chart/track</h4> <div class='resource'> <h5>Description</h5> <p>A chart of most played tracks for a given period.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>, <code>to</code>, <code>from</code>, <code>program</code>. If no to/from parameter is provided we return a chart from the last 7 days.</p> <h5>Example query</h5> - <code><a href="/v1/chart/track.json?from=2011-04-20">/v1/chart/track.json?from=2011-04-20</a></code> + <code><a href="/<%= options.version %>/chart/track.json?from=2011-04-20">/chart/track.json?from=2011-04-20</a></code> <h5>Example response</h5> <script src="https://gist.github.com/973726.js?file=gistfile1.json"></script> </div> <h4 id="resources-chart-album">/chart/album</h4> <div class='resource'> <h5>Description</h5> <p>A chart of most played albums for a given period.</p> <h5>Parameters</h5> <p>Supports the following parameters: <code>channel</code>, <code>limit</code>, <code>to</code>, <code>from</code>, <code>program</code>. If no to/from parameter is provided we return a chart from the last 7 days.</p> <h5>Example query</h5> - <code><a href="/v1/chart/album.json?limit=5&channel=4">/v1/chart/album.json?limit=5&channel=4</a></code> + <code><a href="/<%= options.version %>/chart/album.json?limit=5&channel=4">/chart/album.json?limit=5&channel=4</a></code> <h5>Example response</h5> <script src="https://gist.github.com/973730.js?file=gistfile1.json"></script> </div> <h3 id="resources-search">Search</h3> <div class='resource'> <h5>Description</h5> <p>Search for artists (tracks and albums to come).</p> <h5>Parameters</h5> <p>Supports the following parameter: <code>limit</code>.</p> <h5>Example query</h5> - <code><a href="/v1/search/dylan.json?limit=5">/v1/search/dylan.json?limit=5</a></code> + <code><a href="/<%= options.version %>/search/dylan.json?limit=5">/search/dylan.json?limit=5</a></code> <h5>Example response</h5> <script src="https://gist.github.com/973733.js?file=gistfile1.json"></script> </div> </section> <style type="text/css" media="screen"> .gist-syntax .s2 { color: black; } .gist .gist-file .gist-data{ font-size:75%; } .gist .gist-file .gist-meta{ display:none; } </style> diff --git a/views/layout.html.erb b/views/layout.html.erb index 2846493..3cef6d1 100644 --- a/views/layout.html.erb +++ b/views/layout.html.erb @@ -1,27 +1,27 @@ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> -<title>pav api</title> -<link rel="stylesheet" href="/css/bootstrap-1.4.0.css" type="text/css" /> -<link rel="stylesheet" href="/css/master.css" type="text/css" /> +<title><%= options.version %> pav api</title> +<link rel="stylesheet" href="/<%= options.version %>/css/bootstrap-1.4.0.css" type="text/css" /> +<link rel="stylesheet" href="/<%= options.version %>/css/master.css" type="text/css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> -<link rel="shortcut icon" href="/images/favicon.ico"/> +<link rel="shortcut icon" href="/<%= options.version %>/images/favicon.ico"/> </head> <body> <div class="container"> <a href="http://github.com/simonhn"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a> <header id="main"> <hgroup> - <a href="/"><h1>pav:api</h1></a> + <a href="/<%= options.version %>"><h1><%= options.version %> pav:api</h1></a> </hgroup> </header> <div id="main-content"> <%= yield %> </div> </div> </body> -</html> \ No newline at end of file +</html> diff --git a/views/track_edit.html.erb b/views/track_edit.html.erb index 23241d9..66d7b4a 100644 --- a/views/track_edit.html.erb +++ b/views/track_edit.html.erb @@ -1,46 +1,46 @@ <style type="text/css" media="screen"> input,textarea{width:100%;} </style> <h2>track</h2> <p><%= @track.title %> - <%= @track.id %></p> -<form action='/v1/track/<%= @track.id %>/edit' method="POST"> +<form action='/<%= options.version %>/track/<%= @track.id %>/edit' method="POST"> <label for="title">title</label> <input type="text" name="title" value="<%= @track.title %>"/> <br> <label for="trackmbid">MBID</label> <input type="text" name="trackmbid" value="<%= @track.trackmbid %>"/> <br> <label for="tracklink">link</label> <input type="text" name="tracklink" value="<%= @track.tracklink %>"/> <br> <label for="tracknote">note</label> <textarea name="tracknote"><%= @track.tracknote %></textarea> <br> <label for="show">show</label> <input type="text" name="show" value="<%= @track.show %>"/> <br> <label for="aust">aust</label> <input type="text" name="aust" value="<%= @track.aust %>"/> <br> <label for="talent">talent</label> <input type="text" name="talent" value="<%= @track.talent %>"/> <br> <label for="publisher">publisher</label> <input type="text" name="publisher" value="<%= @track.publisher %>"/> <br> <label for="datecopyrighted">datecopyrighted</label> <input type="text" name="datecopyrighted" value="<%= @track.datecopyrighted %>"/> <br> <input type="submit" value="Save" /> </form> \ No newline at end of file
simonhn/pav-api
0af8df712e6a7a3415a2b961b02e3af1a014b3f8
adding jsonp to config.ru instead
diff --git a/config.ru b/config.ru index ccdb351..495d8ac 100644 --- a/config.ru +++ b/config.ru @@ -1,3 +1,4 @@ require File.join(File.dirname(__FILE__), 'pavapi.rb') +use Rack::JSONP run PavApi \ No newline at end of file diff --git a/pavapi.rb b/pavapi.rb index fd3eb9f..9557317 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,296 +1,295 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' class PavApi < Sinatra::Base configure do set :environment, :development set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') #versioning @version = "v1" - use Rack::JSONP register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new('log/datamapper.log', :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new('log/datamapper.log', :debug ) $LOG = Logger.new('log/pavstore.log', 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end \ No newline at end of file
simonhn/pav-api
96cf1a7e08ef0f6676b293eef5ff2d2c912879b2
adding jsonp ability again
diff --git a/pavapi.rb b/pavapi.rb index 4aee395..fd3eb9f 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,296 +1,296 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' class PavApi < Sinatra::Base configure do set :environment, :development set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') #versioning @version = "v1" - + use Rack::JSONP register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new('log/datamapper.log', :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new('log/datamapper.log', :debug ) $LOG = Logger.new('log/pavstore.log', 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end \ No newline at end of file
simonhn/pav-api
62bafea1a8a5fb7ddfe2d50a13a2097d34d2bb14
sinatra 1.2.7 and respond_to 0.7.0
diff --git a/Gemfile b/Gemfile index a04f50c..c400852 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,31 @@ source :rubygems -gem 'sinatra', '=1.2.8' +gem 'sinatra', '=1.2.6' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' gem 'chronic_duration' gem 'chronic' -gem 'sinatra-respond_to', '=0.8.0' +gem 'sinatra-respond_to', '=0.7.0' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' gem 'stalker' gem 'i18n' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 7641e05..5ea6128 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,91 +1,91 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) newrelic_rpm (3.3.1) numerizer (0.1.1) rack (1.4.0) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) - sinatra (1.2.8) + sinatra (1.2.6) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) - sinatra-respond_to (0.8.0) + sinatra-respond_to (0.7.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client - sinatra (= 1.2.8) - sinatra-respond_to (= 0.8.0) + sinatra (= 1.2.6) + sinatra-respond_to (= 0.7.0) stalker yajl-ruby diff --git a/pavapi.rb b/pavapi.rb index 5b10ebc..4aee395 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,296 +1,296 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types -gem 'sinatra-respond_to', '=0.8.0' +gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' class PavApi < Sinatra::Base configure do set :environment, :development set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') #versioning @version = "v1" register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new('log/datamapper.log', :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new('log/datamapper.log', :debug ) $LOG = Logger.new('log/pavstore.log', 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end \ No newline at end of file
simonhn/pav-api
a0588c19377155b74c737fcd0042bfd0e74cbce7
helping the app to find the vies folder etc
diff --git a/pavapi.rb b/pavapi.rb index 81ccc9a..2dc0f82 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,293 +1,294 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' class PavApi < Sinatra::Base configure do set :environment, :development + set :app_file, File.join(File.dirname(__FILE__), 'pavapi.rb') #versioning @version = "v1" register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new('log/datamapper.log', :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new('log/datamapper.log', :debug ) $LOG = Logger.new('log/pavstore.log', 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end \ No newline at end of file
simonhn/pav-api
ea6904195f1e789bc1b37df4358cd0e09fc3cf99
version stuff again aghhhh
diff --git a/Gemfile b/Gemfile index a04f50c..c400852 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,31 @@ source :rubygems -gem 'sinatra', '=1.2.8' +gem 'sinatra', '=1.2.6' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' gem 'chronic_duration' gem 'chronic' -gem 'sinatra-respond_to', '=0.8.0' +gem 'sinatra-respond_to', '=0.7.0' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' gem 'stalker' gem 'i18n' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 7641e05..5ea6128 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,91 +1,91 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) newrelic_rpm (3.3.1) numerizer (0.1.1) rack (1.4.0) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) - sinatra (1.2.8) + sinatra (1.2.6) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) - sinatra-respond_to (0.8.0) + sinatra-respond_to (0.7.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client - sinatra (= 1.2.8) - sinatra-respond_to (= 0.8.0) + sinatra (= 1.2.6) + sinatra-respond_to (= 0.7.0) stalker yajl-ruby diff --git a/config.ru b/config.ru index 09fcd01..ccdb351 100644 --- a/config.ru +++ b/config.ru @@ -1,4 +1,3 @@ -require 'rubygems' require File.join(File.dirname(__FILE__), 'pavapi.rb') run PavApi \ No newline at end of file diff --git a/pavapi.rb b/pavapi.rb index 9ae0aa4..81ccc9a 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,294 +1,293 @@ #core stuff require 'rubygems' -gem 'sinatra', '=1.2.8' +gem 'sinatra', '=1.2.6' require 'sinatra/base' require_relative 'models' require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types -gem 'sinatra-respond_to', '=0.8.0' +gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' class PavApi < Sinatra::Base configure do set :environment, :development - #versioning @version = "v1" register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new('log/datamapper.log', :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new('log/datamapper.log', :debug ) $LOG = Logger.new('log/pavstore.log', 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end \ No newline at end of file
simonhn/pav-api
9b7c565a5bf1e6011c706489ca36f07adb171c10
upgrading, but not yet working
diff --git a/Gemfile b/Gemfile index 0d3fae1..a04f50c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,31 @@ source :rubygems gem 'sinatra', '=1.2.8' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' gem 'chronic_duration' gem 'chronic' -gem 'sinatra-respond_to', '=0.7.0' +gem 'sinatra-respond_to', '=0.8.0' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' gem 'stalker' gem 'i18n' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 3d5d095..7641e05 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,91 +1,91 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) newrelic_rpm (3.3.1) numerizer (0.1.1) - rack (1.3.5) + rack (1.4.0) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) sinatra (1.2.8) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) - sinatra-respond_to (0.7.0) + sinatra-respond_to (0.8.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client sinatra (= 1.2.8) - sinatra-respond_to (= 0.7.0) + sinatra-respond_to (= 0.8.0) stalker yajl-ruby diff --git a/pavapi.rb b/pavapi.rb index f771f7a..9ae0aa4 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,294 +1,294 @@ #core stuff require 'rubygems' gem 'sinatra', '=1.2.8' require 'sinatra/base' require_relative 'models' require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types -gem 'sinatra-respond_to', '=0.7.0' +gem 'sinatra-respond_to', '=0.8.0' require 'sinatra/respond_to' require 'bigdecimal' class PavApi < Sinatra::Base configure do set :environment, :development #versioning @version = "v1" register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new('log/datamapper.log', :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new('log/datamapper.log', :debug ) $LOG = Logger.new('log/pavstore.log', 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end \ No newline at end of file
simonhn/pav-api
54104bffad1ebbd4a5a32be35459f455fb750d41
sinatra 1.2.8 and respond_to 0.8.0
diff --git a/Gemfile b/Gemfile index c400852..a04f50c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,31 @@ source :rubygems -gem 'sinatra', '=1.2.6' +gem 'sinatra', '=1.2.8' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' gem 'chronic_duration' gem 'chronic' -gem 'sinatra-respond_to', '=0.7.0' +gem 'sinatra-respond_to', '=0.8.0' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' gem 'stalker' gem 'i18n' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 542443e..7641e05 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,91 +1,91 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) newrelic_rpm (3.3.1) numerizer (0.1.1) - rack (1.3.5) + rack (1.4.0) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) - sinatra (1.2.6) + sinatra (1.2.8) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) - sinatra-respond_to (0.7.0) + sinatra-respond_to (0.8.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client - sinatra (= 1.2.6) - sinatra-respond_to (= 0.7.0) + sinatra (= 1.2.8) + sinatra-respond_to (= 0.8.0) stalker yajl-ruby diff --git a/pavapi.rb b/pavapi.rb index 265dae2..353f197 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,281 +1,281 @@ #versioning @version = "v1" #core stuff require 'rubygems' -gem 'sinatra', '=1.2.6' +gem 'sinatra', '=1.2.8' require 'sinatra' require './models' require './store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' # Enable New Relic #configure :production do #require 'newrelic_rpm' #end #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types -gem 'sinatra-respond_to', '=0.7.0' +gem 'sinatra-respond_to', '=0.8.0' require 'sinatra/respond_to' Sinatra::Application.register Sinatra::RespondTo require 'bigdecimal' #require "sinatra/reloader" if development? configure do #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle #logging DataMapper::Logger.new('log/datamapper.log', :warn ) DataMapper::Model.raise_on_save_failure = true $LOG = Logger.new('log/pavstore.log', 'monthly') # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 unless development? end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 unless development? end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 unless development? end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require './routes/admin' require './routes/artist' require './routes/track' require './routes/album' require './routes/channel' require './routes/play' require './routes/chart' require './routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end \ No newline at end of file
simonhn/pav-api
672324310a31ad5d3ed41957ec628e3a3c3f109d
using sinatra 1.2.8 and respond_to 0.7.0
diff --git a/Gemfile b/Gemfile index 0716a6c..0d3fae1 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,31 @@ source :rubygems -gem 'sinatra' +gem 'sinatra', '=1.2.8' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' gem 'chronic_duration' gem 'chronic' -gem 'sinatra-respond_to' +gem 'sinatra-respond_to', '=0.7.0' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' gem 'stalker' gem 'i18n' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 5597570..3d5d095 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,91 +1,91 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) newrelic_rpm (3.3.1) numerizer (0.1.1) rack (1.3.5) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) - sinatra (1.3.1) + sinatra (1.2.8) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) - sinatra-respond_to (0.8.0) + sinatra-respond_to (0.7.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client - sinatra - sinatra-respond_to + sinatra (= 1.2.8) + sinatra-respond_to (= 0.7.0) stalker yajl-ruby diff --git a/pavapi.rb b/pavapi.rb index 9120dc5..f771f7a 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,294 +1,294 @@ #core stuff require 'rubygems' -gem 'sinatra' +gem 'sinatra', '=1.2.8' require 'sinatra/base' require_relative 'models' require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types -gem 'sinatra-respond_to' +gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' require 'bigdecimal' class PavApi < Sinatra::Base configure do set :environment, :development #versioning @version = "v1" register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end configure :production do set :show_exceptions, false set :haml, { :ugly=>true, :format => :html5 } set :clean_trace, true #logging DataMapper::Logger.new('log/datamapper.log', :warn ) require 'newrelic_rpm' end configure :development do set :show_exceptions, true set :haml, { :ugly=>false, :format => :html5 } enable :logging DataMapper::Logger.new('log/datamapper.log', :debug ) $LOG = Logger.new('log/pavstore.log', 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require_relative 'routes/admin' require_relative 'routes/artist' require_relative 'routes/track' require_relative 'routes/album' require_relative 'routes/channel' require_relative 'routes/play' require_relative 'routes/chart' require_relative 'routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end \ No newline at end of file
simonhn/pav-api
e09cc721ad08b9c321dcb620051c628a12ed82e1
require models instead of duplicating
diff --git a/jobs.rb b/jobs.rb index bc1e1ed..ecd66f3 100644 --- a/jobs.rb +++ b/jobs.rb @@ -1,261 +1,188 @@ #datamapper stuff require 'dm-core' require 'dm-timestamps' require 'dm-aggregates' require 'dm-migrations' -#require -#Models - to be moved to individual files -class Artist - include DataMapper::Resource - property :id, Serial - property :artistmbid, String, :length => 36 - property :artistname, String, :length => 512 - property :artistnote, Text - property :artistlink, Text - property :created_at, DateTime - has n, :tracks, :through => Resource - has n, :channels, :through => Resource -end - -class Album - include DataMapper::Resource - property :id, Serial - property :albummbid, String, :length => 36 - property :albumname, String, :length => 512 - property :albumimage, Text - property :created_at, DateTime - has n, :tracks, :through => Resource -end - -class Track - include DataMapper::Resource - property :id, Serial - property :trackmbid, String, :length => 36 - property :title, String, :length => 512 - property :tracknote, Text - property :tracklink, Text - property :show, Text - property :talent, Text - property :aust, String, :length => 512 - property :duration, Integer - property :publisher, Text - property :datecopyrighted, Integer - property :created_at, DateTime - has n, :artists, :through => Resource - has n, :albums, :through => Resource - has n, :plays - def date - created_at.strftime "%R on %B %d, %Y" - end - def playcount - Play.count(:track_id => self.id); - end -end - -class Play - include DataMapper::Resource - property :id, Serial - property :playedtime, DateTime - property :program_id, String, :length => 512 - belongs_to :track - belongs_to :channel - def date - #converting from utc to aussie time - #playedtime.new_offset(Rational(+20,24)).strftime "%R on %B %d, %Y" - playedtime.strftime "%Y-%m-%d %H:%M:%S" - end -end - -class Channel - include DataMapper::Resource - property :id, Serial - property :channelname, String, :length => 512 - property :channelxml, String, :length => 512 - property :logo, String, :length => 512 - property :channellink, String, :length => 512 - property :programxml, String, :length => 512 - has n, :plays - has n, :artists, :through => Resource -end +require './models.rb' #template systems require 'yajl/json_gem' require 'builder' #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' pwd = File.dirname(File.expand_path(__FILE__)) $LOG = Logger.new(pwd+'/log/queue.log', 'monthly') #setup MySQL connection: @config = YAML::load( File.open(pwd +'/config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #Method that stores each playitem to database. Index is the id of the channel to associate the play with def store_hash(item, index) @albums = nil mbid_hash = nil duration = ChronicDuration.parse(item["duration"].to_s) #there can be multiple artist seperated by '+' so we split them artist_array = item['artist']['artistname'].split("+") artist_array.each{ |artist_item| begin artist = artist_item.strip.force_encoding('UTF-8') track = item['title'].force_encoding('UTF-8') album = item['album']['albumname'].force_encoding('UTF-8') #for each item, lookup in musicbrainz. Returns hash with mbids for track, album and artist if found mbid_hash = mbid_lookup(artist,track,album) puts mbid_hash.inspect rescue StandardError => e $LOG.info("Issue while processing #{artist_item.strip} - #{item['title']} - #{e.backtrace}") end #ARTIST if !mbid_hash.nil? && !mbid_hash["artistmbid"].nil? @artist = Artist.first_or_create({:artistmbid => mbid_hash["artistmbid"]},{:artistmbid => mbid_hash["artistmbid"],:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) else @artist = Artist.first_or_create({:artistname => artist_item.strip},{:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) end #store artist_id / channel_id to a lookup table, for faster selects @artist_channels = @artist.channels << Channel.get(index) @artist_channels.save #ALBUM #creating and saving album if not exists if !item['album']['albumname'].empty? if !mbid_hash.nil? && !mbid_hash["albummbid"].nil? #puts "album mbid found for: " + mbid_hash["albummbid"] @albums = Album.first_or_create({:albummbid => mbid_hash["albummbid"]},{:albummbid => mbid_hash["albummbid"], :albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) else @albums = Album.first_or_create({:albumname => item['album']['albumname']},{:albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) end end #Track #creating and saving track if mbid_hash && !mbid_hash["trackmbid"].nil? @tracks = Track.first_or_create({:trackmbid => mbid_hash["trackmbid"]},{:trackmbid => mbid_hash["trackmbid"],:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:publisher => item['publisher'], :datecopyrighted => item['datecopyrighted'].to_i}) else @tracks = Track.first_or_create({:title => item['title'],:duration => duration},{:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:duration => duration,:publisher => item['publisher'],:datecopyrighted => item['datecopyrighted'].to_i}) end #add the track to album - if album exists if [email protected]? @album_tracks = @albums.tracks << @tracks @album_tracks.save end #add the track to the artist @artist_tracks = @artist.tracks << @tracks @artist_tracks.save #adding play: only add if playedtime does not exsist in the database already play_items = Play.count(:playedtime=>item['playedtime'], :channel_id=>index) #if no program, dont insert anything if item['program_id'] == '' item['program_id'] = nil end if play_items < 1 @play = Play.create(:track_id =>@tracks.id, :channel_id => index, :playedtime=>item['playedtime'], :program_id => item['program_id']) @plays = @tracks.plays << @play @plays.save end } end def mbid_lookup(artist, track, album) result_hash = {} #we can only hit mbrainz once a second so we take a nap sleep 1 service = MusicBrainz::Webservice::Webservice.new(:user_agent => 'pavapi/1.0 ([email protected])') q = MusicBrainz::Webservice::Query.new(service) #TRACK if !album.empty? t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :release=>album, :limit => 5) else t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :limit => 5) end t_results = q.get_tracks(t_filter) puts t_results.inspect #No results from the 'advanced' query, so trying artist and album individualy if t_results.count == 0 #ARTIST sleep 1 t_filter = MusicBrainz::Webservice::ArtistFilter.new(:name=>artist) t_results = q.get_artists(t_filter) if t_results.count > 0 x = t_results.first if x.score == 100 && is_ascii(String(x.entity.name)) && String(x.entity.name).casecmp(artist)==0 #puts 'ARTIST score: ' + String(x.score) + '- artist: ' + String(x.entity.name) + ' - artist mbid '+ String(x.entity.id.uuid) result_hash["artistmbid"] = String(x.entity.id.uuid) end end #ALBUM if !album.empty? sleep 1 t_filter = MusicBrainz::Webservice::ReleaseGroupFilter.new(:artist=>artist, :title=>album) t_results = q.get_release_groups(t_filter) #puts "album results count "+t_results.count.to_s if t_results.count>0 x = t_results.first #puts 'ALBUM score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.id.uuid) +' - release title '+ String(x.entity.title) + ' - orginal album title: '+album if x.score == 100 && is_ascii(String(x.entity.title)) #&& String(x.entity.title).casecmp(album)==0 #puts 'abekat'+x.entity.id.uuid.inspect result_hash["albummbid"] = String(x.entity.id.uuid) end end end elsif t_results.count > 0 t_results.each{ |x| #puts 'score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.artist.id.uuid) + ' - track mbid: ' + String(x.entity.id.uuid) + ' - track: ' + String(x.entity.title) +' - album: ' + String(x.entity.releases[0]) +' - album mbid: '+ String(x.entity.releases[0].id.uuid) if x.score == 100 && is_ascii(String(x.entity.artist)) sleep 1 t_include = MusicBrainz::Webservice::ReleaseIncludes.new(:release_groups=>true) release = q.get_release_by_id(x.entity.releases[0].id.uuid, t_include) result_hash["trackmbid"] = String(x.entity.id.uuid) result_hash["artistmbid"] = String(x.entity.artist.id.uuid) result_hash["albummbid"] = String(release.release_group.id.uuid) end } end return result_hash end def is_ascii(item) cd = CharDet.detect(item) encoding = cd['encoding'] return encoding == 'ascii' end job 'track.store' do |args| store_hash(args['item'], args['channel'].to_i) error do |e, job, args| $LOG.info("error e #{e}") $LOG.info("error job #{job.inspect}") $LOG.info("error args #{args.inspect}") end end
simonhn/pav-api
779907498e60a08e10e275a4be468383cf08c5aa
modular app working
diff --git a/config.ru b/config.ru index f07633a..09fcd01 100644 --- a/config.ru +++ b/config.ru @@ -1,6 +1,4 @@ require 'rubygems' require File.join(File.dirname(__FILE__), 'pavapi.rb') -#require './pavapi' - run PavApi \ No newline at end of file diff --git a/pavapi.rb b/pavapi.rb index 882a080..9120dc5 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,283 +1,294 @@ -#versioning -@version = "v1" - #core stuff require 'rubygems' gem 'sinatra' require 'sinatra/base' -require './models' -require './store_methods' +require_relative 'models' +require_relative 'store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' #use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' -# Enable New Relic -#configure :production do - #require 'newrelic_rpm' -#end - #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types gem 'sinatra-respond_to' require 'sinatra/respond_to' require 'bigdecimal' -#require "sinatra/reloader" if development? class PavApi < Sinatra::Base + configure do + set :environment, :development + + #versioning + @version = "v1" + register Sinatra::RespondTo #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle - #logging - DataMapper::Logger.new('log/datamapper.log', :warn ) - DataMapper::Model.raise_on_save_failure = true - $LOG = Logger.new('log/pavstore.log', 'monthly') # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html + + end + + configure :production do + set :show_exceptions, false + set :haml, { :ugly=>true, :format => :html5 } + set :clean_trace, true + #logging + DataMapper::Logger.new('log/datamapper.log', :warn ) + require 'newrelic_rpm' + end + + configure :development do + set :show_exceptions, true + set :haml, { :ugly=>false, :format => :html5 } + enable :logging + DataMapper::Logger.new('log/datamapper.log', :debug ) + $LOG = Logger.new('log/pavstore.log', 'monthly') end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end - require './routes/admin' + require_relative 'routes/admin' - require './routes/artist' + require_relative 'routes/artist' - require './routes/track' + require_relative 'routes/track' - require './routes/album' + require_relative 'routes/album' - require './routes/channel' + require_relative 'routes/channel' - require './routes/play' + require_relative 'routes/play' - require './routes/chart' + require_relative 'routes/chart' - require './routes/demo' + require_relative 'routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end end \ No newline at end of file
simonhn/pav-api
aa8df15ca260d72947e686ae297af69b072bd69f
modular app, routes not working yet though
diff --git a/Gemfile b/Gemfile index c400852..0716a6c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,31 @@ source :rubygems -gem 'sinatra', '=1.2.6' +gem 'sinatra' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' gem 'chronic_duration' gem 'chronic' -gem 'sinatra-respond_to', '=0.7.0' +gem 'sinatra-respond_to' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' gem 'stalker' gem 'i18n' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 542443e..5597570 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,91 +1,91 @@ GEM remote: http://rubygems.org/ specs: addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) data_objects (0.10.7) addressable (~> 2.1) dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) mime-types (1.17.2) multi_json (1.0.4) newrelic_rpm (3.3.1) numerizer (0.1.1) rack (1.3.5) rack-contrib (1.1.0) rack (>= 0.9.1) rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) - sinatra (1.2.6) + sinatra (1.3.1) rack (~> 1.1) tilt (>= 1.2.2, < 2.0) - sinatra-respond_to (0.7.0) + sinatra-respond_to (0.8.0) sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps i18n json memcached newrelic_rpm rack rack-contrib rack-throttle rbrainz rchardet19 rest-client - sinatra (= 1.2.6) - sinatra-respond_to (= 0.7.0) + sinatra + sinatra-respond_to stalker yajl-ruby diff --git a/config.ru b/config.ru index 911a1ed..f07633a 100644 --- a/config.ru +++ b/config.ru @@ -1,10 +1,6 @@ require 'rubygems' -require 'bundler' -Bundler.require -require './pavapi' +require File.join(File.dirname(__FILE__), 'pavapi.rb') -#set :environment, :production -disable :run -enable :logging, :dump_errors, :raise_errors, :show_exceptions +#require './pavapi' -run Sinatra::Application \ No newline at end of file +run PavApi \ No newline at end of file diff --git a/pavapi.rb b/pavapi.rb index 265dae2..882a080 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,281 +1,283 @@ #versioning @version = "v1" #core stuff require 'rubygems' -gem 'sinatra', '=1.2.6' -require 'sinatra' +gem 'sinatra' +require 'sinatra/base' require './models' require './store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' -use Rack::JSONP +#use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' # Enable New Relic #configure :production do #require 'newrelic_rpm' #end #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types -gem 'sinatra-respond_to', '=0.7.0' +gem 'sinatra-respond_to' require 'sinatra/respond_to' -Sinatra::Application.register Sinatra::RespondTo require 'bigdecimal' #require "sinatra/reloader" if development? - -configure do - #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle - #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle - #logging - DataMapper::Logger.new('log/datamapper.log', :warn ) - DataMapper::Model.raise_on_save_failure = true - $LOG = Logger.new('log/pavstore.log', 'monthly') +class PavApi < Sinatra::Base + configure do + register Sinatra::RespondTo + + #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle + #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle + #logging + DataMapper::Logger.new('log/datamapper.log', :warn ) + DataMapper::Model.raise_on_save_failure = true + $LOG = Logger.new('log/pavstore.log', 'monthly') - # MySQL connection: - @config = YAML::load( File.open( 'config/settings.yml' ) ) - @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; - DataMapper.setup(:default, @connection) - DataMapper.finalize + # MySQL connection: + @config = YAML::load( File.open( 'config/settings.yml' ) ) + @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; + DataMapper.setup(:default, @connection) + DataMapper.finalize - #DataMapper.auto_upgrade! - #DataMapper::auto_migrate! - set :default_content, :html -end + #DataMapper.auto_upgrade! + #DataMapper::auto_migrate! + set :default_content, :html + end -#Caching -before '/*' do - cache_control :public, :must_revalidate, :max_age => 60 unless development? -end + #Caching + before '/*' do + cache_control :public, :must_revalidate, :max_age => 60 + end -before '/demo/*' do - cache_control :public, :must_revalidate, :max_age => 3600 unless development? -end + before '/demo/*' do + cache_control :public, :must_revalidate, :max_age => 3600 + end -before '*/chart/*' do - cache_control :public, :must_revalidate, :max_age => 3600 unless development? -end + before '*/chart/*' do + cache_control :public, :must_revalidate, :max_age => 3600 + end -# Error 404 Page Not Found -not_found do - json_status 404, "Not found" -end + # Error 404 Page Not Found + not_found do + json_status 404, "Not found" + end -error do - json_status 500, env['sinatra.error'].message -end + error do + json_status 500, env['sinatra.error'].message + end -helpers do + helpers do - def protected! - unless authorized? - response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") - throw(:halt, [401, "Not authorized\n"]) + def protected! + unless authorized? + response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") + throw(:halt, [401, "Not authorized\n"]) + end end - end - def authorized? - @auth ||= Rack::Auth::Basic::Request.new(request.env) - @config = YAML::load( File.open( 'config/settings.yml' ) ) - @user = @config['authuser'] - @pass = @config['authpass'] - @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] - end + def authorized? + @auth ||= Rack::Auth::Basic::Request.new(request.env) + @config = YAML::load( File.open( 'config/settings.yml' ) ) + @user = @config['authuser'] + @pass = @config['authpass'] + @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] + end - def json_status(code, reason) - status code - { - :status => code, - :reason => reason - }.to_json - end + def json_status(code, reason) + status code + { + :status => code, + :reason => reason + }.to_json + end - def make_to_from(played_from, played_to) - #both to and from parameters provided - played_from = Chronic.parse(played_from) - played_to = Chronic.parse(played_to) + def make_to_from(played_from, played_to) + #both to and from parameters provided + played_from = Chronic.parse(played_from) + played_to = Chronic.parse(played_to) - if (!played_from.nil? && !played_to.nil?) - return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" - end - #no parameters, sets from a week ago - if (played_from.nil? && played_to.nil?) - now_date = DateTime.now - 7 - return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" - end - #only to parameter, setting from a week before that - if (played_from.nil? && !played_to.nil?) - #one week = 60*60*24*7 - from_date = played_to - 604800 - return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" - end - #only from parameter - if (!played_from.nil? && played_to.nil?) - return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" - end - end + if (!played_from.nil? && !played_to.nil?) + return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" + end + #no parameters, sets from a week ago + if (played_from.nil? && played_to.nil?) + now_date = DateTime.now - 7 + return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" + end + #only to parameter, setting from a week before that + if (played_from.nil? && !played_to.nil?) + #one week = 60*60*24*7 + from_date = played_to - 604800 + return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" + end + #only from parameter + if (!played_from.nil? && played_to.nil?) + return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" + end + end - def isNumeric(s) - Float(s) != nil rescue false - end + def isNumeric(s) + Float(s) != nil rescue false + end - def get_limit(lim) - #if no limit is set, we default to 10 - #a max at 5000 on limit to protect the server - if isNumeric(lim) - if lim.to_i < 5000 - return lim + def get_limit(lim) + #if no limit is set, we default to 10 + #a max at 5000 on limit to protect the server + if isNumeric(lim) + if lim.to_i < 5000 + return lim + else + return 5000 + end else - return 5000 + return 10 end - else - return 10 end - end - def get_artist_query(q) - if (!q.nil?) - return "AND artists.artistname LIKE '%#{q}%' " + def get_artist_query(q) + if (!q.nil?) + return "AND artists.artistname LIKE '%#{q}%' " + end end - end - def get_track_query(q) - if (!q.nil?) - return "AND tracks.title LIKE '%#{q}%' " + def get_track_query(q) + if (!q.nil?) + return "AND tracks.title LIKE '%#{q}%' " + end end - end - def get_album_query(q) - if (!q.nil?) - return "AND albums.albumname LIKE '%#{q}%' " + def get_album_query(q) + if (!q.nil?) + return "AND albums.albumname LIKE '%#{q}%' " + end end - end - def get_all_query(q) - if (!q.nil?) - return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " + def get_all_query(q) + if (!q.nil?) + return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " + end end - end - def get_order_by(order) - if (order=='artist') - return "artists.artistname ASC, plays.playedtime DESC" - elsif (order=='track') - return "tracks.title ASC, plays.playedtime DESC" - else - return "plays.playedtime DESC" + def get_order_by(order) + if (order=='artist') + return "artists.artistname ASC, plays.playedtime DESC" + elsif (order=='track') + return "tracks.title ASC, plays.playedtime DESC" + else + return "plays.playedtime DESC" + end end - end - def get_channel(channel) - if(!channel.nil?) - return "AND plays.channel_id=#{channel}" + def get_channel(channel) + if(!channel.nil?) + return "AND plays.channel_id=#{channel}" + end end - end - def get_program(program) - if(!program.nil?) - return "AND plays.program_id='#{program}'" + def get_program(program) + if(!program.nil?) + return "AND plays.program_id='#{program}'" + end end - end - def merge_tracks(old_id, new_id) - old_track = Track.get(old_id) - new_track = Track.get(new_id) - - if(old_track&&new_track) - - #album - #move tracks from old album to new album - link = AlbumTrack.all(:track_id => old_track.id) - link.each{ |link_item| - @album_load = Album.get(link_item.album_id) - @moved = @album_load.tracks << new_track - @moved.save - } - #delete old album_track relations - link.destroy! - - #artist - #move tracks from old artist to new artist - link = ArtistTrack.all(:track_id => old_track.id) - link.each{ |link_item| - @artist_load = Artist.get(link_item.artist_id) - @moved = @artist_load.tracks << new_track - @moved.save - } - #delete old artist_track relations - link.destroy! - - #plays - plays = Play.all(:track_id => old_track.id) - plays.each{ |link_item| - link_item.update(:track_id => new_id) - } - - #delete old track - old_track.destroy! - end - end -end + def merge_tracks(old_id, new_id) + old_track = Track.get(old_id) + new_track = Track.get(new_id) + + if(old_track&&new_track) + + #album + #move tracks from old album to new album + link = AlbumTrack.all(:track_id => old_track.id) + link.each{ |link_item| + @album_load = Album.get(link_item.album_id) + @moved = @album_load.tracks << new_track + @moved.save + } + #delete old album_track relations + link.destroy! + + #artist + #move tracks from old artist to new artist + link = ArtistTrack.all(:track_id => old_track.id) + link.each{ |link_item| + @artist_load = Artist.get(link_item.artist_id) + @moved = @artist_load.tracks << new_track + @moved.save + } + #delete old artist_track relations + link.destroy! + + #plays + plays = Play.all(:track_id => old_track.id) + plays.each{ |link_item| + link_item.update(:track_id => new_id) + } + + #delete old track + old_track.destroy! + end + end + end -#ROUTES + #ROUTES -# Front page -get '/' do - erb :front -end + # Front page + get '/' do + erb :front + end -require './routes/admin' + require './routes/admin' -require './routes/artist' + require './routes/artist' -require './routes/track' + require './routes/track' -require './routes/album' + require './routes/album' -require './routes/channel' + require './routes/channel' -require './routes/play' + require './routes/play' -require './routes/chart' + require './routes/chart' -require './routes/demo' + require './routes/demo' -# search artist by name -get "/#{@version}/search/:q" do - limit = get_limit(params[:limit]) - @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) - respond_to do |wants| - wants.html { erb :artists } - wants.xml { builder :artists } - wants.json { @artists.to_json } + # search artist by name + get "/#{@version}/search/:q" do + limit = get_limit(params[:limit]) + @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) + respond_to do |wants| + wants.html { erb :artists } + wants.xml { builder :artists } + wants.json { @artists.to_json } + end end end \ No newline at end of file diff --git a/routes/admin.rb b/routes/admin.rb index 60e9a47..11e57c5 100644 --- a/routes/admin.rb +++ b/routes/admin.rb @@ -1,156 +1,159 @@ +class PavApi < Sinatra::Base + #admin dashboard get "/admin" do protected! respond_to do |wants| wants.html { erb :admin } end end #Count all artists get "/admin/stats" do json_outout = {} #@dig_duration_avg = repository(:default).adapter.select("SELECT ROUND(AVG(duration),0) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE tracks.duration < 500 AND`plays`.`channel_id` = 1") #json_outout['dig_duration_avg'] = @dig_duration_avg.first.to_i.to_s #@all_duration_avg = Track.avg(:duration, :duration.lt => 500) #json_outout['all_duration_avg'] = @all_duration_avg.to_i.to_s @artistcount = Artist.count json_outout['all_artistcount'] = @artistcount @artistmbid = (Artist.count(:artistmbid).to_f/@artistcount.to_f)*100 @trackcount = Track.count json_outout['all_trackcount'] = @trackcount @trackmbid = (Track.count(:trackmbid).to_f/@trackcount.to_f)*100 @playcount = Play.count json_outout['all_playcount'] = @playcount @albumcount = Album.count json_outout['all_albumcount'] = @albumcount @albummbid = (Album.count(:albummbid).to_f/@albumcount.to_f)*100 @dig_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_play = Play.all('channel_id'=>1).count @jazz_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_play = Play.all('channel_id'=>2).count @country_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_play = Play.all('channel_id'=>3).count @jjj_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_play = Play.all('channel_id'=>4).count respond_to do |wants| wants.html { erb :stats } wants.json {json_outout.to_json} end end get "/admin/duplicate/artist" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.artistname, d2.artistmbid FROM artists d1 JOIN artists d2 ON d2.artistname = d1.artistname AND d2.id <> d1.id order by artistname, id") respond_to do |wants| wants.html { erb :duplicate_artists } end end post "/admin/merge/artist" do protected! old_artist = Artist.get(params[:id_old]) new_artist = Artist.get(params[:id_new]) if(old_artist&&new_artist) #move tracks from old artist to new artist link = ArtistTrack.all(:artist_id => old_artist.id) link.each{ |link_item| @track_load = Track.get(link_item.track_id) @moved = new_artist.tracks << @track_load @moved.save } #delete old artist_track relations link.destroy! #delete old artist old_artist.destroy! end redirect back end get "/admin/duplicate/album" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.albumname, d2.albummbid FROM albums d1 JOIN albums d2 ON d2.albumname = d1.albumname AND d2.id <> d1.id order by albumname, id") respond_to do |wants| wants.html { erb :duplicate_albums } end end post "/admin/merge/album" do protected! old_album = Album.get(params[:id_old]) old_album_tracks = old_album.tracks new_album = Album.get(params[:id_new]) new_album_tracks = new_album.tracks if(old_album&&new_album) #if there are similar track on the two albums, # move the 'old' tracks to the 'new' tracks before moving album links old_album_tracks.each{ |old_track| new_track = new_album_tracks.find {|e| e.title==old_track.title&&e.id!=old_track.id } if(new_track) merge_tracks(old_track.id, new_track.id) end } #move tracks from old album to new album link = AlbumTrack.all(:album_id => old_album.id) link.each{ |link_item| @track_load = Track.get(link_item.track_id) @moved = new_album.tracks << @track_load @moved.save } #delete old album_track relations link.destroy! #delete old album old_album.destroy! end redirect back end get "/admin/duplicate/track" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.title, d2.trackmbid FROM tracks d1 JOIN tracks d2 ON d2.title = d1.title AND d2.id <> d1.id order by title, id") respond_to do |wants| wants.html { erb :duplicate_tracks } end end post "/admin/merge/track" do protected! merge_tracks(params[:id_old], params[:id_new]) redirect back +end end \ No newline at end of file diff --git a/routes/album.rb b/routes/album.rb index f918440..3b9fe7e 100644 --- a/routes/album.rb +++ b/routes/album.rb @@ -1,73 +1,76 @@ +class PavApi < Sinatra::Base + #show all albums get "/#{@version}/albums" do limit = get_limit(params[:limit]) channel = params[:channel] if channel @albums = Album.all('tracks.plays.channel_id' => channel, :limit=>limit.to_i, :order => [:created_at.desc ]) else @albums = Album.all(:limit => limit.to_i, :order => [:created_at.desc ]) end respond_to do |wants| wants.html { erb :albums } wants.xml { builder :albums } wants.json { @albums.to_json } end end # show album from id get "/#{@version}/album/:id" do if params[:type] == 'mbid' || params[:id].length == 36 @album = Album.first(:albummbid => params[:id]) else @album = Album.get(params[:id]) end respond_to do |wants| wants.html { erb :album } wants.xml { builder :album } wants.json {@album.to_json} end end # edit track from id. if ?type=mbid is added, it will perform a mbid lookup get "/#{@version}/album/:id/edit" do protected! if params[:type] == 'mbid' || params[:id].length == 36 @album = Album.first(:albummbid => params[:id]) else @album = Album.get(params[:id]) end respond_to do |wants| wants.html { erb :album_edit } end end post "/#{@version}/album/:id/edit" do protected! @album = Album.get(params[:id]) raise not_found unless @album @album.attributes = { :albumname => params["albumname"], :albummbid => params["albummbid"], :albumimage => params["albumimage"], :created_at => params["created_at"] } @album.save redirect "/v1/album/#{@album.id}" end # show tracks for an album get "/#{@version}/album/:id/tracks" do if params[:type] == 'mbid' || params[:id].length == 36 @album = Album.first(:albummbid => params[:id]) else @album = Album.get(params[:id]) end @tracks = @album.tracks respond_to do |wants| wants.html { erb :album_tracks } wants.xml { builder :album_tracks } wants.json {@tracks.to_json } end end +end \ No newline at end of file diff --git a/routes/artist.rb b/routes/artist.rb index 3e853a6..a621905 100644 --- a/routes/artist.rb +++ b/routes/artist.rb @@ -1,220 +1,223 @@ +class PavApi < Sinatra::Base + #show all artists, defaults to 10, ordered by created date get "/#{@version}/artists" do limit = get_limit(params[:limit]) channel = params[:channel] if channel @artists = Artist.all('tracks.plays.channel_id' => channel, :limit=>limit.to_i, :order => [:created_at.desc ]) else @artists = Artist.all(:limit => limit.to_i, :order => [:created_at.desc ]) end respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end # show artist from id. if ?type=mbid is added, it will perform a mbid lookup get "/#{@version}/artist/:id" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end respond_to do |wants| wants.html { erb :artist } wants.xml { builder :artist } wants.json { @artist.to_json } end end get "/#{@version}/artist/:id/details" do result = Hash.new #if no channel parameter provided, we assume all channels channel = get_channel(params[:channel]) if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end artist_result = Hash.new artist_result['artist_id'] = @artist.id artist_result['artistname'] = @artist.artistname result["artist"] = artist_result @play_count = repository(:default).adapter.select("SELECT plays.playedtime, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} order by playedtime") if !@play_count.empty? @tracks = repository(:default).adapter.select("SELECT count(plays.id) as play_count, tracks.title, tracks.id FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} group by tracks.id order by playedtime") result["tracks"] = @tracks.collect {|o| {:count => o.play_count, :title => o.title, :track_id => o.id} } @albums = @artist.tracks.albums result["albums"] = @albums.collect {|o| {:album_id => o.id, :albumname => o.albumname, :albumimage => o.albumimage} } result["play_count"] = @play_count.size programs = repository(:default).adapter.select("select count(plays.id) as play_count, program_id from plays, tracks, artist_tracks, artists where artists.id=#{@artist.id} AND artists.id = artist_tracks.artist_id AND artist_tracks.track_id=tracks.id and tracks.id=plays.track_id AND plays.program_id !='' group by program_id") result["programs"] = programs.collect {|o| {:play_count => o.play_count, :program_id => o.program_id} } first_play = @play_count.first #puts 'first played on '+Time.parse(first_play.playedtime.to_s).to_s result["first_play"] = Time.parse(first_play.playedtime.to_s).to_s last_play = @play_count.last #puts 'last played on '+Time.parse(last_play.playedtime.to_s).to_s result["last_play"] = Time.parse(last_play.playedtime.to_s).to_s average_duration = @artist.tracks.avg(:duration) #puts 'average track duration '+average_duration.inspect result["avg_duration"] = average_duration australian = @artist.tracks.first.aust #puts 'australian? '+australian.inspect result["australian"] = australian @artist_chart = repository(:default).adapter.select("select artists.artistname, artists.id, artist_tracks.artist_id, artists.artistmbid, count(*) as cnt from tracks, plays, artists, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id=artists.id #{channel} group by artists.id order by cnt desc") index_number = @artist_chart.index{|x|x[:id][email protected]} real_index = 1+index_number.to_i #puts 'Position on all time chart '+real_index.to_s result["chart_pos"] = real_index #@play_count_range, divides last - first into 10 time slots if @play_count.size > 1 #only makes sense if more than one play @time_range = (Time.parse(last_play.playedtime.to_s) - Time.parse(first_play.playedtime.to_s)) @slice = @time_range / 10 hat = Time.parse(first_play.playedtime.to_s) i = 0 result_array = [] while i < 10 do from = hat hat = hat + @slice to = hat to_from = "AND playedtime <= '#{to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime >= '#{from.strftime("%Y-%m-%d %H:%M:%S")}'" @play_counter = repository(:default).adapter.select("SELECT plays.playedtime, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} #{to_from} order by playedtime") item = Hash.new item["from"] = from.to_s item["to"] = to.to_s item["count"] = @play_counter.size.to_s result_array[i] = item i += 1 end #puts 'time sliced play count '+result_array.inspect result["time_sliced"] = result_array #average play counts per week from first played to now #@play_count.size @new_time_range = (Time.now - Time.parse(first_play.playedtime.to_s)) avg = @play_count.size/(@new_time_range/(60*60*24*7)) #puts 'avg plays per week '+ avg.to_s result["avg_play_week"] = avg else #when only 1 play: result["time_sliced"] = [] result["avg_play_week"] = 0 end #played on other channels? channel_result = Hash.new channels = Channel.all channels.each do |channel| q = repository(:default).adapter.select("SELECT count(*) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} AND plays.channel_id=#{channel.id}") if q.first.to_i>0 channel_result[channel.channelname] = q.first #puts 'played on ' + channel.channelname+' '+q.first.to_s+' times' end end result["channels"] = channel_result @res = result end respond_to do |wants| wants.json { result.to_json } end end # edit artist from id. if ?type=mbid is added, it will perform a mbid lookup get "/#{@version}/artist/:id/edit" do protected! if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end respond_to do |wants| wants.html { erb :artist_edit } end end post "/#{@version}/artist/:id/edit" do protected! @artist = Artist.get(params[:id]) raise not_found unless @artist @artist.attributes = { :artistname => params["artistname"], :artistmbid => params["artistmbid"], :artistlink => params["artistlink"], :artistnote => params["artistnote"] } @artist.save redirect "/v1/artist/#{@artist.id}" end # show tracks from artist get "/#{@version}/artist/:id/tracks" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end @tracks = @artist.tracks @tracks_json = repository(:default).adapter.select("SELECT count(plays.id) as play_count, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} group by tracks.id order by playedtime") respond_to do |wants| wants.html { erb :artist_tracks } wants.xml { builder :artist_tracks } wants.json { @tracks_json.to_json } end end # show albums from artist get "/#{@version}/artist/:id/albums" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end @albums = @artist.tracks.albums respond_to do |wants| wants.html { erb :artist_albums } wants.xml { builder :artist_albums } wants.json { @albums.to_json } end end # show plays from artist get "/#{@version}/artist/:id/plays" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end channel = params[:channel] limit = get_limit(params[:limit]) if channel @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE `plays`.`channel_id` = #{channel} AND artists.id=#{@artist.id} group by tracks.id, plays.playedtime order by plays.playedtime limit #{limit}") else @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE tracks.id AND artists.id=#{@artist.id} group by tracks.id, plays.playedtime order by plays.playedtime limit #{limit}") end hat = @plays.collect {|o| {:title => o.title, :track_id => o.track_id, :trackmbid => o.trackmbid, :artistname => o.artistname, :artist_id => o.artist_id, :artistmbid => o.artistmbid, :playedtime => o.playedtime, :albumname => o.albumname, :albumimage => o.albumimage, :album_id => o.album_id, :albummbid => o.albummbid, :program_id => o.program_id, :channel_id => o.channel_id} } respond_to do |wants| wants.html { erb :artist_plays } wants.xml { builder :artist_plays } wants.json { hat.to_json } end +end end \ No newline at end of file diff --git a/routes/channel.rb b/routes/channel.rb index c285d3d..8f495fb 100644 --- a/routes/channel.rb +++ b/routes/channel.rb @@ -1,32 +1,35 @@ +class PavApi < Sinatra::Base + # show all channels get "/#{@version}/channels" do @channels = Channel.all respond_to do |wants| wants.xml { @channels.to_xml } wants.json { @channels.to_json } end end #create new channel post "/#{@version}/channel" do protected! data = JSON.parse params[:payload].to_json channel = Channel.first_or_create({ :channelname => data['channelname'] }, { :channelname => data['channelname'],:channelxml => data['channelxml'], :logo => data['logo'], :channellink => data['channellink'] }) end #update a channel put "/#{@version}/channel/:id" do protected! channel = Channel.get(params[:id]) data = JSON.parse params[:payload].to_json channel = channel.update(:channelname => data['channelname'],:channelxml => data['channelxml'], :logo => data['logo'], :channellink => data['channellink']) end # show channel from id get "/#{@version}/channel/:id" do @channel = Channel.get(params[:id]) respond_to do |wants| wants.xml { @channel.to_xml } wants.json { @channel.to_json } end +end end \ No newline at end of file diff --git a/routes/chart.rb b/routes/chart.rb index e786a96..d5fcd32 100644 --- a/routes/chart.rb +++ b/routes/chart.rb @@ -1,47 +1,50 @@ +class PavApi < Sinatra::Base + # chart of top tracks get "/#{@version}/chart/track" do program = get_program(params[:program]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) channel = get_channel(params[:channel]) @tracks = repository(:default).adapter.select("select *, cnt from (select tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at, count(*) as cnt from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{program} group by tracks.id order by cnt DESC limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") hat = @tracks.collect {|o| {:count => o.cnt, :title => o.title, :track_id => o.id, :artistname => o.artistname,:artistmbid => o.artistmbid, :trackmbid => o.trackmbid, :albumname => o.albumname, :albummbid => o.albummbid, :albumimage => o.albumimage} } respond_to do |wants| wants.html { erb :track_chart } wants.xml { builder :track_chart } wants.json { hat.to_json } end end # chart of top artist by name get "/#{@version}/chart/artist" do program = get_program(params[:program]) to_from = make_to_from(params[:from], params[:to]) limit = get_limit(params[:limit]) channel = get_channel(params[:channel]) @artists = repository(:default).adapter.select("select artists.id, artists.artistname, artists.artistmbid,count(*) as cnt from (select artist_tracks.artist_id from plays, tracks, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id #{channel} #{to_from} #{program}) as artist_tracks, artists where artist_tracks.artist_id=artists.id group by artists.id order by cnt desc limit #{limit}") #@artists = repository(:default).adapter.select("select sum(cnt) as count, har.artistname, har.id from (select artists.artistname, artists.id, artist_tracks.artist_id, count(*) as cnt from tracks, plays, artists, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id= artists.id #{to_from} group by tracks.id, plays.playedtime) as har group by har.artistname order by count desc limit #{limit}") hat = @artists.collect {|o| {:count => o.cnt, :artistname => o.artistname, :id => o.id, :artistmbid => o.artistmbid} } respond_to do |wants| wants.html { erb :artist_chart } wants.xml { builder :artist_chart } wants.json {hat.to_json} end end get "/#{@version}/chart/album" do program = get_program(params[:program]) to_from = make_to_from(params[:from], params[:to]) limit = get_limit(params[:limit]) channel = get_channel(params[:channel]) @albums = repository(:default).adapter.select("select artists.artistname, artists.artistmbid, albums.albumname, albums.albumimage, albums.id as album_id, albums.albummbid, count(distinct album_tracks.pid) as cnt from (select album_tracks.album_id as aid, tracks.id as tid, plays.id as pid from tracks, plays, album_tracks where tracks.id = plays.track_id AND album_tracks.track_id = tracks.id #{channel} #{to_from} #{program}) as album_tracks, albums, artists, artist_tracks where albums.id = album_tracks.aid AND album_tracks.tid = artist_tracks.track_id AND artists.id = artist_tracks.artist_id group by albums.id order by cnt DESC limit #{limit}") hat = @albums.collect {|o| {:count => o.cnt, :artistname => o.artistname, :artistmbid => o.artistmbid, :albumname => o.albumname, :album_id => o.album_id, :albummbid => o.albummbid,:albumimage => o.albumimage} } respond_to do |wants| wants.html { erb :album_chart } wants.xml { builder :album_chart } wants.json {hat.to_json} end +end end \ No newline at end of file diff --git a/routes/demo.rb b/routes/demo.rb index 24ce176..6edfbb5 100644 --- a/routes/demo.rb +++ b/routes/demo.rb @@ -1,124 +1,127 @@ +class PavApi < Sinatra::Base + get '/demo/?' do respond_to do |wants| wants.html{erb :demo} end end get '/demo/album-charts' do from_date = DateTime.now - 7 @from_date_string = from_date.strftime("%b %e") to_date = DateTime.now @to_date_string = to_date.strftime("%b %e") respond_to do |wants| wants.html{erb :album_chart_all} end end get '/demo/program-chart' do redirect '/demo/program-chart/track' end get '/demo/program-chart/track' do @program = params[:program] @program ||= 'super_request' @span = params[:span] @span ||= 7 respond_to do |wants| wants.html{erb :program_chart_track} end end get '/demo/program-chart/artist' do @program = params[:program] @program ||= 'super_request' @span = params[:span] @span ||= 7 respond_to do |wants| wants.html{erb :program_chart_artist} end end get '/demo/program-chart/artist-expand' do @program = params[:program] @program ||= 'super_request' @span = params[:span] @span ||= 7 respond_to do |wants| wants.html{erb :program_chart_artist_expand} end end get '/demo/program-chart/album' do @program = params[:program] @program ||= 'super_request' @span = params[:span] @span ||= 7 respond_to do |wants| wants.html{erb :program_chart_album} end end get '/demo/jjj' do cache_control :public, :max_age => 600 artistmbid = {} har ='a' hur = 'b' @artists = repository(:default).adapter.select("select artists.artistname, artists.id, artist_tracks.artist_id, artists.artistmbid, count(*) as cnt from tracks, plays, artists, artist_tracks where plays.channel_id=4 AND tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id=artists.id group by artists.id order by cnt desc limit 10") #hat = @artists.collect {|o| {:count => o.cnt, :artistname => o.artistname, :id => o.id, :artistmbid => o.artistmbid} } all = Hash.new @artists.each{ |o| begin if o.artistmbid #puts o.artistname begin result = RestClient.get 'http://www.abc.net.au/triplej/media/artists/'+o.artistmbid+'/all-media.xml' if(result.code==200) all[o.artistname] = Hash.new all[o.artistname].store("media",Hash.new()) all[o.artistname].store("info",Hash.new()) all[o.artistname].fetch("info").store("mbid",o.artistmbid) all[o.artistname].fetch("info").store("count",o.cnt) xml = Crack::XML.parse(result) if(xml["rss"]["channel"]["item"].kind_of?(Array)) xml["rss"]["channel"]["item"].each_with_index{|ha,i| if !ha["title"].empty? && !ha["media:thumbnail"].first.nil? har = ha["title"] da = ha["media:thumbnail"] if da.kind_of?(Array) hur = da.first["url"] all[o.artistname].fetch("media").store(ha["title"],hur) else hur = da["url"] all[o.artistname].fetch("media").store(ha["title"],hur) end if ha["media:content"].kind_of?(Array) all[o.artistname].fetch("media").store(ha["media:content"].first["medium"],ha["media:content"].first["url"]) else all[o.artistname].fetch("media").store(ha["media:content"]["medium"],ha["media:content"]["url"]) end end } else if(!xml["rss"]["channel"]["item"]["title"].nil? && !xml["rss"]["channel"]["item"]["media:thumbnail"]["url"].nil?) har = xml["rss"]["channel"]["item"]["title"] hur = xml["rss"]["channel"]["item"]["media:thumbnail"]["url"] end end #john = @artists.map {|o| {:count => o.cnt, :artistname => o.artistname, :id => o.id, :artistmbid => o.artistmbid, :media=> {:title => har.to_s, :thumb=>hur.to_s}} } #puts john.inspect end rescue => e end end end } @hat = all respond_to do |wants| wants.html { erb :jjj } wants.json { all.to_json } end end +end diff --git a/routes/play.rb b/routes/play.rb index 61fc9ca..87f47da 100644 --- a/routes/play.rb +++ b/routes/play.rb @@ -1,34 +1,37 @@ +class PavApi < Sinatra::Base + #PLAY get "/#{@version}/plays" do #DATE_FORMAT(playedtime, '%d %m %Y %H %i %S') artist_query = get_artist_query(params[:artist_query]) track_query = get_track_query(params[:track_query]) album_query = get_album_query(params[:album_query]) query_all = get_all_query(params[:q]) order_by = get_order_by(params[:order_by]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) channel = get_channel(params[:channel]); program = get_program(params[:program]) if artist_query or album_query or query_all or params[:order_by]=='artist' @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE plays.id #{channel} #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}") else @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{track_query} #{program} order by #{order_by} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") end hat = @plays.collect {|o| {:title => o.title, :track_id => o.track_id, :trackmbid => o.trackmbid, :artistname => o.artistname, :artist_id => o.artist_id, :artistmbid => o.artistmbid, :playedtime => o.playedtime, :albumname => o.albumname, :albumimage => o.albumimage, :album_id => o.album_id, :albummbid => o.albummbid, :program_id => o.program_id, :channel_id => o.channel_id} } respond_to do |wants| wants.html { erb :plays } wants.xml { builder :plays } wants.json { hat.to_json } end end get "/#{@version}/play/:id" do @play = Play.get(params[:id]) respond_to do |wants| wants.json { @play.to_json } end +end end \ No newline at end of file diff --git a/routes/track.rb b/routes/track.rb index ed3a789..791cb67 100644 --- a/routes/track.rb +++ b/routes/track.rb @@ -1,129 +1,132 @@ +class PavApi < Sinatra::Base + #add new track item (an item in the playout xml) post "/#{@version}/track" do protected! begin data = JSON.parse params[:payload].to_json if !data['item']['artist']['artistname'].nil? && Play.count(:playedtime => data['item']['playedtime'], :channel_id => data['channel'])==0 Stalker.enqueue('track.store', :item => data['item'],:channel => data['channel']) #Delayed::Job.enqueue StoreTrackJob.new(data['item'], data['channel']) #store_hash(data['item'], data['channel']) end rescue StandardError => e $LOG.info("Post method end: Issue while processing #{data['item']['artist']['artistname']} - #{data['channel']}, #{e.backtrace}") end end #show tracks get "/#{@version}/tracks" do limit = get_limit(params[:limit]) channel = params[:channel] if channel @tracks = Track.all(Track.plays.channel_id => channel, :limit=>limit.to_i, :order => [:created_at.desc]) else @tracks = Track.all(:limit => limit.to_i, :order => [:created_at.desc ]) end respond_to do |wants| wants.html { erb :tracks } wants.xml { builder :tracks } wants.json {@tracks.to_json} end end # show track get "/#{@version}/track/:id" do if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end respond_to do |wants| wants.html { erb :track } wants.xml { builder :track } wants.json {@track.to_json} end end # edit track from id. if ?type=mbid is added, it will perform a mbid lookup get "/#{@version}/track/:id/edit" do protected! if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end respond_to do |wants| wants.html { erb :track_edit } end end post "/#{@version}/track/:id/edit" do protected! @track = Track.get(params[:id]) raise not_found unless @track @track.attributes = { :title => params["title"], :trackmbid => params["trackmbid"], :tracklink => params["tracklink"], :tracknote => params["tracknote"], :talent => params["talent"], :aust => params["aust"], :datecopyrighted => params["datecopyrighted"], :show => params["show"], :publisher => params["publisher"], :created_at => params["created_at"] } @track.save redirect "/v1/track/#{@track.id}" end #show artists for a track get "/#{@version}/track/:id/artists" do if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end @artists = @track.artists respond_to do |wants| wants.html { erb :track_artists } wants.xml { builder :track_artists } wants.json {@artists.to_json} end end #show albums for a track get "/#{@version}/track/:id/albums" do if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end @albums = @track.albums respond_to do |wants| wants.html { erb :track_albums } wants.xml { builder :track_albums } wants.json {@albums.to_json} end end # show plays for a track get "/#{@version}/track/:id/plays" do if params[:type] == 'mbid' || params[:id].length == 36 @track = Track.first(:trackmbid => params[:id]) else @track = Track.get(params[:id]) end @plays = @track.plays respond_to do |wants| wants.html { erb :track_plays } wants.xml { builder :track_plays } wants.json {@plays.to_json} end end +end \ No newline at end of file
simonhn/pav-api
8c05ee3a54535144832e001dacd9d65038cb8a79
simpler channels query. queries with search now uses the old slower query version
diff --git a/routes/play.rb b/routes/play.rb index 54f26da..61fc9ca 100644 --- a/routes/play.rb +++ b/routes/play.rb @@ -1,34 +1,34 @@ #PLAY get "/#{@version}/plays" do #DATE_FORMAT(playedtime, '%d %m %Y %H %i %S') artist_query = get_artist_query(params[:artist_query]) track_query = get_track_query(params[:track_query]) album_query = get_album_query(params[:album_query]) query_all = get_all_query(params[:q]) order_by = get_order_by(params[:order_by]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) - channel = params[:channel] + channel = get_channel(params[:channel]); program = get_program(params[:program]) - if channel - #@plays = repository(:default).adapter.select("select * from tracks, plays, artists, artist_tracks, albums, album_tracks where plays.channel_id=#{channel} AND tracks.id=plays.track_id AND artists.id=artist_tracks.artist_id AND artist_tracks.track_id=tracks.id AND albums.id = album_tracks.album_id AND tracks.id = album_tracks.track_id #{to_from} group by tracks.id, plays.playedtime order by plays.playedtime DESC limit #{limit}") - @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id AND plays.channel_id = #{channel} #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") + + if artist_query or album_query or query_all or params[:order_by]=='artist' + @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE plays.id #{channel} #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}") else - #@plays = repository(:default).adapter.select("select * from tracks, plays, artists, artist_tracks, albums, album_tracks where tracks.id=plays.track_id AND artists.id=artist_tracks.artist_id AND artist_tracks.track_id=tracks.id AND albums.id = album_tracks.album_id AND tracks.id = album_tracks.track_id #{to_from} group by tracks.id, plays.playedtime order by plays.playedtime DESC limit #{limit}") - @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id AND tracks.id #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") + @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{track_query} #{program} order by #{order_by} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") end + hat = @plays.collect {|o| {:title => o.title, :track_id => o.track_id, :trackmbid => o.trackmbid, :artistname => o.artistname, :artist_id => o.artist_id, :artistmbid => o.artistmbid, :playedtime => o.playedtime, :albumname => o.albumname, :albumimage => o.albumimage, :album_id => o.album_id, :albummbid => o.albummbid, :program_id => o.program_id, :channel_id => o.channel_id} } respond_to do |wants| wants.html { erb :plays } wants.xml { builder :plays } wants.json { hat.to_json } end end get "/#{@version}/play/:id" do @play = Play.get(params[:id]) respond_to do |wants| wants.json { @play.to_json } end end \ No newline at end of file
simonhn/pav-api
33c2cb9714e5033c8447ef37264fe53e3394563b
making admin pages more user friendly
diff --git a/public/css/master.css b/public/css/master.css index 77bf135..e24d555 100644 --- a/public/css/master.css +++ b/public/css/master.css @@ -1,24 +1,25 @@ h1{ font-size: 3em; font-weight: 300; } ul li a{ font-weight: normal; } ul li ul li a{ font-weight: normal; } .row .span5{ background-color: #F8F8F8; border: 1px #CCC solid; padding:1em; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.1); -moz-box-shadow: 0 1px 2px rgba(0,0,0,.1); box-shadow: 0 1px 2px rgba(0,0,0,.1); float:right; } +form{position: fixed;left: 800px;top:0px} \ No newline at end of file diff --git a/routes/admin.rb b/routes/admin.rb index e2195ef..60e9a47 100644 --- a/routes/admin.rb +++ b/routes/admin.rb @@ -1,152 +1,156 @@ #admin dashboard get "/admin" do protected! respond_to do |wants| wants.html { erb :admin } end end #Count all artists get "/admin/stats" do json_outout = {} - @dig_duration_avg = repository(:default).adapter.select("SELECT ROUND(AVG(duration),0) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE tracks.duration < 500 AND`plays`.`channel_id` = 1") - json_outout['dig_duration_avg'] = @dig_duration_avg.first.to_i.to_s + #@dig_duration_avg = repository(:default).adapter.select("SELECT ROUND(AVG(duration),0) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE tracks.duration < 500 AND`plays`.`channel_id` = 1") + #json_outout['dig_duration_avg'] = @dig_duration_avg.first.to_i.to_s - @all_duration_avg = Track.avg(:duration, :duration.lt => 500) - json_outout['all_duration_avg'] = @all_duration_avg.to_i.to_s + #@all_duration_avg = Track.avg(:duration, :duration.lt => 500) + #json_outout['all_duration_avg'] = @all_duration_avg.to_i.to_s @artistcount = Artist.count json_outout['all_artistcount'] = @artistcount @artistmbid = (Artist.count(:artistmbid).to_f/@artistcount.to_f)*100 @trackcount = Track.count json_outout['all_trackcount'] = @trackcount @trackmbid = (Track.count(:trackmbid).to_f/@trackcount.to_f)*100 @playcount = Play.count json_outout['all_playcount'] = @playcount @albumcount = Album.count json_outout['all_albumcount'] = @albumcount @albummbid = (Album.count(:albummbid).to_f/@albumcount.to_f)*100 @dig_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 1") @dig_play = Play.all('channel_id'=>1).count @jazz_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 2") @jazz_play = Play.all('channel_id'=>2).count @country_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 3") @country_play = Play.all('channel_id'=>3).count @jjj_track = repository(:default).adapter.select("SELECT COUNT(distinct tracks.id) FROM `tracks` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_artist = repository(:default).adapter.select("SELECT COUNT(distinct artists.id) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_album = repository(:default).adapter.select("SELECT COUNT(distinct albums.id) FROM `albums` INNER JOIN `album_tracks` ON `albums`.`id` = `album_tracks`.`album_id` INNER JOIN `tracks` ON `album_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `plays`.`channel_id` = 4") @jjj_play = Play.all('channel_id'=>4).count respond_to do |wants| wants.html { erb :stats } wants.json {json_outout.to_json} end end get "/admin/duplicate/artist" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.artistname, d2.artistmbid FROM artists d1 JOIN artists d2 ON d2.artistname = d1.artistname AND d2.id <> d1.id order by artistname, id") respond_to do |wants| wants.html { erb :duplicate_artists } end end post "/admin/merge/artist" do protected! old_artist = Artist.get(params[:id_old]) new_artist = Artist.get(params[:id_new]) if(old_artist&&new_artist) #move tracks from old artist to new artist link = ArtistTrack.all(:artist_id => old_artist.id) link.each{ |link_item| @track_load = Track.get(link_item.track_id) @moved = new_artist.tracks << @track_load @moved.save } #delete old artist_track relations link.destroy! #delete old artist old_artist.destroy! end + redirect back + end get "/admin/duplicate/album" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.albumname, d2.albummbid FROM albums d1 JOIN albums d2 ON d2.albumname = d1.albumname AND d2.id <> d1.id order by albumname, id") respond_to do |wants| wants.html { erb :duplicate_albums } end end post "/admin/merge/album" do protected! old_album = Album.get(params[:id_old]) old_album_tracks = old_album.tracks new_album = Album.get(params[:id_new]) new_album_tracks = new_album.tracks if(old_album&&new_album) #if there are similar track on the two albums, # move the 'old' tracks to the 'new' tracks before moving album links old_album_tracks.each{ |old_track| new_track = new_album_tracks.find {|e| e.title==old_track.title&&e.id!=old_track.id } if(new_track) merge_tracks(old_track.id, new_track.id) end } #move tracks from old album to new album link = AlbumTrack.all(:album_id => old_album.id) link.each{ |link_item| @track_load = Track.get(link_item.track_id) @moved = new_album.tracks << @track_load @moved.save } #delete old album_track relations link.destroy! #delete old album old_album.destroy! end + redirect back end get "/admin/duplicate/track" do protected! @list = repository(:default).adapter.select("SELECT distinct d2.id, d2.title, d2.trackmbid FROM tracks d1 JOIN tracks d2 ON d2.title = d1.title AND d2.id <> d1.id order by title, id") respond_to do |wants| wants.html { erb :duplicate_tracks } end end post "/admin/merge/track" do protected! - merge_tracks(params[:id_old], params[:id_new]) + merge_tracks(params[:id_old], params[:id_new]) + redirect back end \ No newline at end of file diff --git a/views/duplicate_albums.html.erb b/views/duplicate_albums.html.erb index 9d08403..3c0b087 100644 --- a/views/duplicate_albums.html.erb +++ b/views/duplicate_albums.html.erb @@ -1,33 +1,50 @@ <p> <form action='/admin/merge/album' method="POST" class="form-stacked"> <label for="id_old">Album to delete</label> <input type="text" name="id_old" /> <label for="id_new">Album to keep</label> <input type="text" name="id_new" /> - <input type="submit" value="Merge!" /> + <input class="btn small danger" type="submit" value="Merge!" /> + <input class="btn small" type="reset"/> </form> </p> <p> <table> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <% @list.each do |track| %> <tr> + <td><button class="keep btn small" data-keep="<%= track.id %>">keep</button></td> + <td><button class="delete btn small" data-delete="<%= track.id %>">delete</button></td> <td><a href="/v1/album/<%= track.id %>"><%= track.id %></td> <td> <span><% if !track.albummbid.nil? %><a href="http://musicbrainz.org/release-group/<%= track.albummbid %>.html"><%= track.albumname %></a> <% else %> <%= track.albumname %><% end %></span> </span> </td> </tr> <% end %> </tbody> </table> </p> +<script> + $('.keep').bind('click', function(e) { + $("input[name='id_new']").val(''); + var id = $(this).attr('data-keep'); + $("input[name='id_new']").val(id); + }); + + $('.delete').bind('click', function(e) { + $("input[name='id_old']").val(''); + var id = $(this).attr('data-delete'); + $("input[name='id_old']").val(id); + }); + + </script> diff --git a/views/duplicate_artists.html.erb b/views/duplicate_artists.html.erb index cb9aa23..ec9018c 100644 --- a/views/duplicate_artists.html.erb +++ b/views/duplicate_artists.html.erb @@ -1,31 +1,49 @@ <p> <form action='/admin/merge/artist' method="POST" class="form-stacked"> <label for="id_old">Artist to delete</label> <input type="text" name="id_old" /> <label for="id_new">Artist to keep</label> <input type="text" name="id_new" /> - <input type="submit" value="Merge!" /> + <input class="btn small danger" type="submit" value="Merge!" /> + <input class="btn small" type="reset"/> </form> </p> <p> <table> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <% @list.each do |track| %> <tr> + <td><button class="keep btn small" data-keep="<%= track.id %>">keep</button></td> + <td><button class="delete btn small" data-delete="<%= track.id %>">delete</button></td> <td><a href="/v1/artist/<%= track.id %>"><%= track.id %></td> <td> <span><% if !track.artistmbid.nil? %><a href="http://musicbrainz.org/artist/<%= track.artistmbid %>.html"><%= track.artistname %></a> <% else %> <%= track.artistname %><% end %></span> </span> </td> </tr> <% end %> </tbody> </table> -</p> \ No newline at end of file +</p> + +<script> + $('.keep').bind('click', function(e) { + $("input[name='id_new']").val(''); + var id = $(this).attr('data-keep'); + $("input[name='id_new']").val(id); + }); + + $('.delete').bind('click', function(e) { + $("input[name='id_old']").val(''); + var id = $(this).attr('data-delete'); + $("input[name='id_old']").val(id); + }); + + </script> diff --git a/views/duplicate_tracks.html.erb b/views/duplicate_tracks.html.erb index 5de5a57..55e29c3 100644 --- a/views/duplicate_tracks.html.erb +++ b/views/duplicate_tracks.html.erb @@ -1,31 +1,49 @@ <p> <form action='/admin/merge/track' method="POST" class="form-stacked"> <label for="id_old">Track to delete</label> <input type="text" name="id_old" /> <label for="id_new">Track to keep</label> <input type="text" name="id_new" /> - <input type="submit" value="Merge!" /> + <input class="btn small danger" type="submit" value="Merge!" /> + <input class="btn small" type="reset"/> </form> </p> <p> <table> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <% @list.each do |track| %> <tr> + <td><button class="keep btn small" data-keep="<%= track.id %>">keep</button></td> + <td><button class="delete btn small" data-delete="<%= track.id %>">delete</button></td> <td><a href="/v1/track/<%= track.id %>"><%= track.id %></td> <td> <span><% if !track.trackmbid.nil? %><a href="http://musicbrainz.org/track/<%= track.trackmbid %>.html"><%= track.title %></a> <% else %> <%= track.title %><% end %></span> </span> - </td> + </td> </tr> <% end %> </tbody> </table> -</p> \ No newline at end of file +</p> + +<script> + $('.keep').bind('click', function(e) { + $("input[name='id_new']").val(''); + var id = $(this).attr('data-keep'); + $("input[name='id_new']").val(id); + }); + + $('.delete').bind('click', function(e) { + $("input[name='id_old']").val(''); + var id = $(this).attr('data-delete'); + $("input[name='id_old']").val(id); + }); + + </script> \ No newline at end of file diff --git a/views/layout.html.erb b/views/layout.html.erb index 6e7ba72..2846493 100644 --- a/views/layout.html.erb +++ b/views/layout.html.erb @@ -1,27 +1,27 @@ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>pav api</title> <link rel="stylesheet" href="/css/bootstrap-1.4.0.css" type="text/css" /> <link rel="stylesheet" href="/css/master.css" type="text/css" /> - +<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <link rel="shortcut icon" href="/images/favicon.ico"/> </head> <body> <div class="container"> <a href="http://github.com/simonhn"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a> <header id="main"> <hgroup> <a href="/"><h1>pav:api</h1></a> </hgroup> </header> <div id="main-content"> <%= yield %> </div> </div> </body> </html> \ No newline at end of file
simonhn/pav-api
8c21eadbd45075ddf7fef08db91b4473fb4a88c1
downgrading to sinatra 1.2.6 because of errors in posting http responses
diff --git a/Gemfile b/Gemfile index 665e758..c400852 100644 --- a/Gemfile +++ b/Gemfile @@ -1,37 +1,31 @@ source :rubygems -gem 'sinatra' +gem 'sinatra', '=1.2.6' gem 'json' gem 'rack' gem 'rack-contrib', :require => 'rack/contrib' gem 'builder' gem 'rbrainz' gem 'rchardet19' gem 'rest-client', :require=>'rest_client' gem 'crack' -gem 'meta-spotify' - gem 'chronic_duration' gem 'chronic' -gem 'sinatra-respond_to' +gem 'sinatra-respond_to', '=0.7.0' gem 'dm-core' gem 'dm-mysql-adapter' gem 'dm-serializer' gem 'dm-timestamps' gem 'dm-aggregates' gem 'dm-migrations' gem 'rack-throttle', :require => 'rack/throttle' -gem 'rack-cors', :require => 'rack/cors' gem 'memcached' gem 'yajl-ruby', :require=> 'yajl/json_gem' gem 'newrelic_rpm' -gem 'delayed_job' -gem 'delayed_job_data_mapper' gem 'stalker' -gem 'i18n' -gem 'foreman' \ No newline at end of file +gem 'i18n' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 771e232..542443e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,124 +1,91 @@ GEM remote: http://rubygems.org/ specs: - activesupport (3.1.3) - multi_json (~> 1.0) addressable (2.2.6) beanstalk-client (1.1.1) builder (3.0.0) chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) crack (0.3.1) - daemons (1.1.4) data_objects (0.10.7) addressable (~> 2.1) - delayed_job (2.1.4) - activesupport (~> 3.0) - daemons - delayed_job_data_mapper (1.0.0.rc) - delayed_job (~> 2.1) - dm-aggregates - dm-core - dm-observer dm-aggregates (1.2.0) dm-core (~> 1.2.0) dm-core (1.2.0) addressable (~> 2.2.6) dm-do-adapter (1.2.0) data_objects (~> 0.10.6) dm-core (~> 1.2.0) dm-migrations (1.2.0) dm-core (~> 1.2.0) dm-mysql-adapter (1.2.0) dm-do-adapter (~> 1.2.0) do_mysql (~> 0.10.6) - dm-observer (1.2.0) - dm-core (~> 1.2.0) dm-serializer (1.2.1) dm-core (~> 1.2.0) fastercsv (~> 1.5.4) json (~> 1.6.1) json_pure (~> 1.6.1) multi_json (~> 1.0.3) dm-timestamps (1.2.0) dm-core (~> 1.2.0) do_mysql (0.10.7) data_objects (= 0.10.7) fastercsv (1.5.4) - foreman (0.27.0) - term-ansicolor (~> 1.0.5) - thor (>= 0.13.6) - httparty (0.5.0) - crack (>= 0.1.1) i18n (0.6.0) json (1.6.3) json_pure (1.6.3) memcached (1.3.5) - meta-spotify (0.1.6) - crack (>= 0.1.4) - httparty (>= 0.4.5, < 0.8) mime-types (1.17.2) multi_json (1.0.4) - newrelic_rpm (3.3.0) + newrelic_rpm (3.3.1) numerizer (0.1.1) rack (1.3.5) rack-contrib (1.1.0) rack (>= 0.9.1) - rack-cors (0.2.4) - rack - rack-protection (1.1.4) - rack rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) rest-client (1.6.7) mime-types (>= 1.16) - sinatra (1.3.1) - rack (~> 1.3, >= 1.3.4) - rack-protection (~> 1.1, >= 1.1.2) - tilt (~> 1.3, >= 1.3.3) - sinatra-respond_to (0.8.0) - sinatra (~> 1.3) + sinatra (1.2.6) + rack (~> 1.1) + tilt (>= 1.2.2, < 2.0) + sinatra-respond_to (0.7.0) + sinatra (~> 1.2) stalker (0.9.0) beanstalk-client json_pure - term-ansicolor (1.0.7) - thor (0.14.6) tilt (1.3.3) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack - delayed_job - delayed_job_data_mapper dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps - foreman i18n json memcached - meta-spotify newrelic_rpm rack rack-contrib - rack-cors rack-throttle rbrainz rchardet19 rest-client - sinatra - sinatra-respond_to + sinatra (= 1.2.6) + sinatra-respond_to (= 0.7.0) stalker yajl-ruby diff --git a/jobs.rb b/jobs.rb index 8a8f0e9..bc1e1ed 100644 --- a/jobs.rb +++ b/jobs.rb @@ -1,261 +1,261 @@ #datamapper stuff require 'dm-core' require 'dm-timestamps' require 'dm-aggregates' require 'dm-migrations' #require #Models - to be moved to individual files class Artist include DataMapper::Resource property :id, Serial property :artistmbid, String, :length => 36 property :artistname, String, :length => 512 property :artistnote, Text property :artistlink, Text property :created_at, DateTime has n, :tracks, :through => Resource has n, :channels, :through => Resource end class Album include DataMapper::Resource property :id, Serial property :albummbid, String, :length => 36 property :albumname, String, :length => 512 property :albumimage, Text property :created_at, DateTime has n, :tracks, :through => Resource end class Track include DataMapper::Resource property :id, Serial property :trackmbid, String, :length => 36 property :title, String, :length => 512 property :tracknote, Text property :tracklink, Text property :show, Text property :talent, Text property :aust, String, :length => 512 property :duration, Integer property :publisher, Text property :datecopyrighted, Integer property :created_at, DateTime has n, :artists, :through => Resource has n, :albums, :through => Resource has n, :plays def date created_at.strftime "%R on %B %d, %Y" end def playcount Play.count(:track_id => self.id); end end class Play include DataMapper::Resource property :id, Serial property :playedtime, DateTime property :program_id, String, :length => 512 belongs_to :track belongs_to :channel def date #converting from utc to aussie time #playedtime.new_offset(Rational(+20,24)).strftime "%R on %B %d, %Y" playedtime.strftime "%Y-%m-%d %H:%M:%S" end end class Channel include DataMapper::Resource property :id, Serial property :channelname, String, :length => 512 property :channelxml, String, :length => 512 property :logo, String, :length => 512 property :channellink, String, :length => 512 property :programxml, String, :length => 512 has n, :plays has n, :artists, :through => Resource end #template systems require 'yajl/json_gem' require 'builder' #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' pwd = File.dirname(File.expand_path(__FILE__)) $LOG = Logger.new(pwd+'/log/queue.log', 'monthly') #setup MySQL connection: @config = YAML::load( File.open(pwd +'/config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #Method that stores each playitem to database. Index is the id of the channel to associate the play with def store_hash(item, index) @albums = nil mbid_hash = nil duration = ChronicDuration.parse(item["duration"].to_s) #there can be multiple artist seperated by '+' so we split them artist_array = item['artist']['artistname'].split("+") artist_array.each{ |artist_item| begin artist = artist_item.strip.force_encoding('UTF-8') track = item['title'].force_encoding('UTF-8') album = item['album']['albumname'].force_encoding('UTF-8') #for each item, lookup in musicbrainz. Returns hash with mbids for track, album and artist if found mbid_hash = mbid_lookup(artist,track,album) puts mbid_hash.inspect rescue StandardError => e $LOG.info("Issue while processing #{artist_item.strip} - #{item['title']} - #{e.backtrace}") end #ARTIST if !mbid_hash.nil? && !mbid_hash["artistmbid"].nil? @artist = Artist.first_or_create({:artistmbid => mbid_hash["artistmbid"]},{:artistmbid => mbid_hash["artistmbid"],:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) else @artist = Artist.first_or_create({:artistname => artist_item.strip},{:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) end #store artist_id / channel_id to a lookup table, for faster selects @artist_channels = @artist.channels << Channel.get(index) @artist_channels.save #ALBUM #creating and saving album if not exists if !item['album']['albumname'].empty? if !mbid_hash.nil? && !mbid_hash["albummbid"].nil? #puts "album mbid found for: " + mbid_hash["albummbid"] @albums = Album.first_or_create({:albummbid => mbid_hash["albummbid"]},{:albummbid => mbid_hash["albummbid"], :albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) else @albums = Album.first_or_create({:albumname => item['album']['albumname']},{:albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) end end #Track #creating and saving track if mbid_hash && !mbid_hash["trackmbid"].nil? @tracks = Track.first_or_create({:trackmbid => mbid_hash["trackmbid"]},{:trackmbid => mbid_hash["trackmbid"],:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:publisher => item['publisher'], :datecopyrighted => item['datecopyrighted'].to_i}) else @tracks = Track.first_or_create({:title => item['title'],:duration => duration},{:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:duration => duration,:publisher => item['publisher'],:datecopyrighted => item['datecopyrighted'].to_i}) end #add the track to album - if album exists if [email protected]? @album_tracks = @albums.tracks << @tracks @album_tracks.save end #add the track to the artist @artist_tracks = @artist.tracks << @tracks @artist_tracks.save #adding play: only add if playedtime does not exsist in the database already play_items = Play.count(:playedtime=>item['playedtime'], :channel_id=>index) #if no program, dont insert anything if item['program_id'] == '' item['program_id'] = nil end if play_items < 1 @play = Play.create(:track_id =>@tracks.id, :channel_id => index, :playedtime=>item['playedtime'], :program_id => item['program_id']) @plays = @tracks.plays << @play @plays.save end } end def mbid_lookup(artist, track, album) result_hash = {} #we can only hit mbrainz once a second so we take a nap sleep 1 - service = MusicBrainz::Webservice::Webservice.new(:user_agent => 'hat') + service = MusicBrainz::Webservice::Webservice.new(:user_agent => 'pavapi/1.0 ([email protected])') q = MusicBrainz::Webservice::Query.new(service) #TRACK if !album.empty? t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :release=>album, :limit => 5) else t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :limit => 5) end t_results = q.get_tracks(t_filter) puts t_results.inspect #No results from the 'advanced' query, so trying artist and album individualy if t_results.count == 0 #ARTIST sleep 1 t_filter = MusicBrainz::Webservice::ArtistFilter.new(:name=>artist) t_results = q.get_artists(t_filter) if t_results.count > 0 x = t_results.first if x.score == 100 && is_ascii(String(x.entity.name)) && String(x.entity.name).casecmp(artist)==0 #puts 'ARTIST score: ' + String(x.score) + '- artist: ' + String(x.entity.name) + ' - artist mbid '+ String(x.entity.id.uuid) result_hash["artistmbid"] = String(x.entity.id.uuid) end end #ALBUM if !album.empty? sleep 1 t_filter = MusicBrainz::Webservice::ReleaseGroupFilter.new(:artist=>artist, :title=>album) t_results = q.get_release_groups(t_filter) #puts "album results count "+t_results.count.to_s if t_results.count>0 x = t_results.first #puts 'ALBUM score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.id.uuid) +' - release title '+ String(x.entity.title) + ' - orginal album title: '+album if x.score == 100 && is_ascii(String(x.entity.title)) #&& String(x.entity.title).casecmp(album)==0 #puts 'abekat'+x.entity.id.uuid.inspect result_hash["albummbid"] = String(x.entity.id.uuid) end end end elsif t_results.count > 0 t_results.each{ |x| #puts 'score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.artist.id.uuid) + ' - track mbid: ' + String(x.entity.id.uuid) + ' - track: ' + String(x.entity.title) +' - album: ' + String(x.entity.releases[0]) +' - album mbid: '+ String(x.entity.releases[0].id.uuid) if x.score == 100 && is_ascii(String(x.entity.artist)) sleep 1 t_include = MusicBrainz::Webservice::ReleaseIncludes.new(:release_groups=>true) release = q.get_release_by_id(x.entity.releases[0].id.uuid, t_include) result_hash["trackmbid"] = String(x.entity.id.uuid) result_hash["artistmbid"] = String(x.entity.artist.id.uuid) result_hash["albummbid"] = String(release.release_group.id.uuid) end } end return result_hash end def is_ascii(item) cd = CharDet.detect(item) encoding = cd['encoding'] return encoding == 'ascii' end job 'track.store' do |args| store_hash(args['item'], args['channel'].to_i) error do |e, job, args| $LOG.info("error e #{e}") $LOG.info("error job #{job.inspect}") $LOG.info("error args #{args.inspect}") end end diff --git a/pavapi.rb b/pavapi.rb index 6700a41..265dae2 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,279 +1,281 @@ #versioning @version = "v1" #core stuff require 'rubygems' +gem 'sinatra', '=1.2.6' require 'sinatra' require './models' require './store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' # Enable New Relic #configure :production do #require 'newrelic_rpm' #end #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' #for serving different content types +gem 'sinatra-respond_to', '=0.7.0' require 'sinatra/respond_to' Sinatra::Application.register Sinatra::RespondTo require 'bigdecimal' #require "sinatra/reloader" if development? configure do #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle #logging DataMapper::Logger.new('log/datamapper.log', :warn ) DataMapper::Model.raise_on_save_failure = true $LOG = Logger.new('log/pavstore.log', 'monthly') # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 unless development? end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 unless development? end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 unless development? end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require './routes/admin' require './routes/artist' require './routes/track' require './routes/album' require './routes/channel' require './routes/play' require './routes/chart' require './routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end \ No newline at end of file
simonhn/pav-api
b411d51ab8b038cc0f854d729f0cb5e7028b5c08
various small things
diff --git a/.gitignore b/.gitignore index ab90ad8..86d802c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,14 @@ log/*.log config/settings.yml config/deploy.rb config/deploy/* .bundle\n +.yardoc/ +Capfile +Rakefile +config/capistrano_database.rb +config/deploy.rb.old +doc/ +log/ +*.pid +*.output \ No newline at end of file diff --git a/Procfile b/Procfile deleted file mode 100644 index 0348c11..0000000 --- a/Procfile +++ /dev/null @@ -1 +0,0 @@ -worker: bundle exec stalk jobs.rb diff --git a/config/settings.yml.erb b/config/settings.yml.erb index a10e835..5cd6ab6 100644 --- a/config/settings.yml.erb +++ b/config/settings.yml.erb @@ -1,15 +1,15 @@ # store your custom template at foo/bar/database.yml.erb #set :template_dir, "config" # # example of database template adapter: mysql host: localhost -username: simonhn -database: <%= Capistrano::CLI.ui.ask("Enter MySQL database to connect to: ") %> +username: <%= Capistrano::CLI.ui.ask("Enter MySQL user: ") %> password: <%= Capistrano::CLI.ui.ask("Enter MySQL database password: ") %> +database: <%= Capistrano::CLI.ui.ask("Enter MySQL database to connect to: ") %> encoding: utf8 timeout: 5000 -authuser: admin +authuser: <%= Capistrano::CLI.ui.ask("Enter http auth user: ") %> authpass: <%= Capistrano::CLI.ui.ask("Enter http auth password: ") %> \ No newline at end of file diff --git a/jobs.rb b/jobs.rb index eaba3da..8a8f0e9 100644 --- a/jobs.rb +++ b/jobs.rb @@ -1,257 +1,261 @@ #datamapper stuff require 'dm-core' require 'dm-timestamps' require 'dm-aggregates' require 'dm-migrations' #require #Models - to be moved to individual files class Artist include DataMapper::Resource property :id, Serial property :artistmbid, String, :length => 36 property :artistname, String, :length => 512 property :artistnote, Text property :artistlink, Text property :created_at, DateTime has n, :tracks, :through => Resource has n, :channels, :through => Resource end class Album include DataMapper::Resource property :id, Serial property :albummbid, String, :length => 36 property :albumname, String, :length => 512 property :albumimage, Text property :created_at, DateTime has n, :tracks, :through => Resource end class Track include DataMapper::Resource property :id, Serial property :trackmbid, String, :length => 36 property :title, String, :length => 512 property :tracknote, Text property :tracklink, Text property :show, Text property :talent, Text property :aust, String, :length => 512 property :duration, Integer property :publisher, Text property :datecopyrighted, Integer property :created_at, DateTime has n, :artists, :through => Resource has n, :albums, :through => Resource has n, :plays def date created_at.strftime "%R on %B %d, %Y" end def playcount Play.count(:track_id => self.id); end end class Play include DataMapper::Resource property :id, Serial property :playedtime, DateTime property :program_id, String, :length => 512 belongs_to :track belongs_to :channel def date #converting from utc to aussie time #playedtime.new_offset(Rational(+20,24)).strftime "%R on %B %d, %Y" playedtime.strftime "%Y-%m-%d %H:%M:%S" end end class Channel include DataMapper::Resource property :id, Serial property :channelname, String, :length => 512 property :channelxml, String, :length => 512 property :logo, String, :length => 512 property :channellink, String, :length => 512 property :programxml, String, :length => 512 has n, :plays has n, :artists, :through => Resource end #template systems require 'yajl/json_gem' require 'builder' #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' pwd = File.dirname(File.expand_path(__FILE__)) $LOG = Logger.new(pwd+'/log/queue.log', 'monthly') #setup MySQL connection: @config = YAML::load( File.open(pwd +'/config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #Method that stores each playitem to database. Index is the id of the channel to associate the play with def store_hash(item, index) @albums = nil mbid_hash = nil duration = ChronicDuration.parse(item["duration"].to_s) #there can be multiple artist seperated by '+' so we split them artist_array = item['artist']['artistname'].split("+") artist_array.each{ |artist_item| begin + artist = artist_item.strip.force_encoding('UTF-8') + track = item['title'].force_encoding('UTF-8') + album = item['album']['albumname'].force_encoding('UTF-8') #for each item, lookup in musicbrainz. Returns hash with mbids for track, album and artist if found - mbid_hash = mbid_lookup(artist_item.strip, item['title'], item['album']['albumname']) + mbid_hash = mbid_lookup(artist,track,album) + puts mbid_hash.inspect rescue StandardError => e $LOG.info("Issue while processing #{artist_item.strip} - #{item['title']} - #{e.backtrace}") end #ARTIST if !mbid_hash.nil? && !mbid_hash["artistmbid"].nil? @artist = Artist.first_or_create({:artistmbid => mbid_hash["artistmbid"]},{:artistmbid => mbid_hash["artistmbid"],:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) else @artist = Artist.first_or_create({:artistname => artist_item.strip},{:artistname => artist_item.strip, :artistnote => item['artist']['artistnote'], :artistlink => item['artist']['artistlink']}) end #store artist_id / channel_id to a lookup table, for faster selects @artist_channels = @artist.channels << Channel.get(index) @artist_channels.save #ALBUM #creating and saving album if not exists if !item['album']['albumname'].empty? if !mbid_hash.nil? && !mbid_hash["albummbid"].nil? #puts "album mbid found for: " + mbid_hash["albummbid"] @albums = Album.first_or_create({:albummbid => mbid_hash["albummbid"]},{:albummbid => mbid_hash["albummbid"], :albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) else @albums = Album.first_or_create({:albumname => item['album']['albumname']},{:albumname => item['album']['albumname'], :albumimage=>item['album']['albumimage']}) end end #Track #creating and saving track if mbid_hash && !mbid_hash["trackmbid"].nil? @tracks = Track.first_or_create({:trackmbid => mbid_hash["trackmbid"]},{:trackmbid => mbid_hash["trackmbid"],:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:publisher => item['publisher'], :datecopyrighted => item['datecopyrighted'].to_i}) else @tracks = Track.first_or_create({:title => item['title'],:duration => duration},{:title => item['title'],:show => item['show'],:talent => item['talent'],:aust => item['aust'],:tracklink => item['tracklink'],:tracknote => item['tracknote'],:duration => duration,:publisher => item['publisher'],:datecopyrighted => item['datecopyrighted'].to_i}) end #add the track to album - if album exists if [email protected]? @album_tracks = @albums.tracks << @tracks @album_tracks.save end #add the track to the artist @artist_tracks = @artist.tracks << @tracks @artist_tracks.save #adding play: only add if playedtime does not exsist in the database already play_items = Play.count(:playedtime=>item['playedtime'], :channel_id=>index) #if no program, dont insert anything if item['program_id'] == '' item['program_id'] = nil end if play_items < 1 @play = Play.create(:track_id =>@tracks.id, :channel_id => index, :playedtime=>item['playedtime'], :program_id => item['program_id']) @plays = @tracks.plays << @play @plays.save end } end def mbid_lookup(artist, track, album) result_hash = {} #we can only hit mbrainz once a second so we take a nap sleep 1 - service = MusicBrainz::Webservice::Webservice.new(:user_agent => 'pavapi/1.0') + service = MusicBrainz::Webservice::Webservice.new(:user_agent => 'hat') q = MusicBrainz::Webservice::Query.new(service) #TRACK if !album.empty? t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :release=>album, :limit => 5) else t_filter = MusicBrainz::Webservice::TrackFilter.new(:artist=>artist, :title=>track, :limit => 5) end t_results = q.get_tracks(t_filter) - + puts t_results.inspect #No results from the 'advanced' query, so trying artist and album individualy if t_results.count == 0 #ARTIST sleep 1 t_filter = MusicBrainz::Webservice::ArtistFilter.new(:name=>artist) t_results = q.get_artists(t_filter) if t_results.count > 0 x = t_results.first if x.score == 100 && is_ascii(String(x.entity.name)) && String(x.entity.name).casecmp(artist)==0 #puts 'ARTIST score: ' + String(x.score) + '- artist: ' + String(x.entity.name) + ' - artist mbid '+ String(x.entity.id.uuid) result_hash["artistmbid"] = String(x.entity.id.uuid) end end #ALBUM if !album.empty? sleep 1 t_filter = MusicBrainz::Webservice::ReleaseGroupFilter.new(:artist=>artist, :title=>album) t_results = q.get_release_groups(t_filter) #puts "album results count "+t_results.count.to_s if t_results.count>0 x = t_results.first #puts 'ALBUM score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.id.uuid) +' - release title '+ String(x.entity.title) + ' - orginal album title: '+album if x.score == 100 && is_ascii(String(x.entity.title)) #&& String(x.entity.title).casecmp(album)==0 #puts 'abekat'+x.entity.id.uuid.inspect result_hash["albummbid"] = String(x.entity.id.uuid) end end end elsif t_results.count > 0 t_results.each{ |x| #puts 'score: ' + String(x.score) + '- artist: ' + String(x.entity.artist) + ' - artist mbid '+ String(x.entity.artist.id.uuid) + ' - track mbid: ' + String(x.entity.id.uuid) + ' - track: ' + String(x.entity.title) +' - album: ' + String(x.entity.releases[0]) +' - album mbid: '+ String(x.entity.releases[0].id.uuid) if x.score == 100 && is_ascii(String(x.entity.artist)) sleep 1 t_include = MusicBrainz::Webservice::ReleaseIncludes.new(:release_groups=>true) release = q.get_release_by_id(x.entity.releases[0].id.uuid, t_include) result_hash["trackmbid"] = String(x.entity.id.uuid) result_hash["artistmbid"] = String(x.entity.artist.id.uuid) result_hash["albummbid"] = String(release.release_group.id.uuid) end } end return result_hash end def is_ascii(item) cd = CharDet.detect(item) encoding = cd['encoding'] return encoding == 'ascii' end job 'track.store' do |args| store_hash(args['item'], args['channel'].to_i) error do |e, job, args| $LOG.info("error e #{e}") $LOG.info("error job #{job.inspect}") $LOG.info("error args #{args.inspect}") end end diff --git a/public/css/bootstrap-1.4.0.css b/public/css/bootstrap-1.4.0.css new file mode 100644 index 0000000..a981ecd --- /dev/null +++ b/public/css/bootstrap-1.4.0.css @@ -0,0 +1,2467 @@ +/*! + * Bootstrap v1.4.0 + * + * Copyright 2011 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + * Date: Sun Nov 20 21:42:29 PST 2011 + */ +/* Reset.less + * Props to Eric Meyer (meyerweb.com) for his CSS reset file. We're using an adapted version here that cuts out some of the reset HTML elements we will never need here (i.e., dfn, samp, etc). + * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ +html, body { + margin: 0; + padding: 0; +} +h1, +h2, +h3, +h4, +h5, +h6, +p, +blockquote, +pre, +a, +abbr, +acronym, +address, +cite, +code, +del, +dfn, +em, +img, +q, +s, +samp, +small, +strike, +strong, +sub, +sup, +tt, +var, +dd, +dl, +dt, +li, +ol, +ul, +fieldset, +form, +label, +legend, +button, +table, +caption, +tbody, +tfoot, +thead, +tr, +th, +td { + margin: 0; + padding: 0; + border: 0; + font-weight: normal; + font-style: normal; + font-size: 100%; + line-height: 1; + font-family: inherit; +} +table { + border-collapse: collapse; + border-spacing: 0; +} +ol, ul { + list-style: none; +} +q:before, +q:after, +blockquote:before, +blockquote:after { + content: ""; +} +html { + overflow-y: scroll; + font-size: 100%; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} +a:focus { + outline: thin dotted; +} +a:hover, a:active { + outline: 0; +} +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +nav, +section { + display: block; +} +audio, canvas, video { + display: inline-block; + *display: inline; + *zoom: 1; +} +audio:not([controls]) { + display: none; +} +sub, sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} +sup { + top: -0.5em; +} +sub { + bottom: -0.25em; +} +img { + border: 0; + -ms-interpolation-mode: bicubic; +} +button, +input, +select, +textarea { + font-size: 100%; + margin: 0; + vertical-align: baseline; + *vertical-align: middle; +} +button, input { + line-height: normal; + *overflow: visible; +} +button::-moz-focus-inner, input::-moz-focus-inner { + border: 0; + padding: 0; +} +button, +input[type="button"], +input[type="reset"], +input[type="submit"] { + cursor: pointer; + -webkit-appearance: button; +} +input[type="search"] { + -webkit-appearance: textfield; + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; +} +input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} +textarea { + overflow: auto; + vertical-align: top; +} +/* Variables.less + * Variables to customize the look and feel of Bootstrap + * ----------------------------------------------------- */ +/* Mixins.less + * Snippets of reusable CSS to develop faster and keep code readable + * ----------------------------------------------------------------- */ +/* + * Scaffolding + * Basic and global styles for generating a grid system, structural layout, and page templates + * ------------------------------------------------------------------------------------------- */ +body { + background-color: #ffffff; + margin: 0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 13px; + font-weight: normal; + line-height: 18px; + color: #404040; +} +.container { + width: 940px; + margin-left: auto; + margin-right: auto; + zoom: 1; +} +.container:before, .container:after { + display: table; + content: ""; + zoom: 1; +} +.container:after { + clear: both; +} +.container-fluid { + position: relative; + min-width: 940px; + padding-left: 20px; + padding-right: 20px; + zoom: 1; +} +.container-fluid:before, .container-fluid:after { + display: table; + content: ""; + zoom: 1; +} +.container-fluid:after { + clear: both; +} +.container-fluid > .sidebar { + position: absolute; + top: 0; + left: 20px; + width: 220px; +} +.container-fluid > .content { + margin-left: 240px; +} +a { + color: #0069d6; + text-decoration: none; + line-height: inherit; + font-weight: inherit; +} +a:hover { + color: #00438a; + text-decoration: underline; +} +.pull-right { + float: right; +} +.pull-left { + float: left; +} +.hide { + display: none; +} +.show { + display: block; +} +.row { + zoom: 1; + margin-left: -20px; +} +.row:before, .row:after { + display: table; + content: ""; + zoom: 1; +} +.row:after { + clear: both; +} +.row > [class*="span"] { + display: inline; + float: left; + margin-left: 20px; +} +.span1 { + width: 40px; +} +.span2 { + width: 100px; +} +.span3 { + width: 160px; +} +.span4 { + width: 220px; +} +.span5 { + width: 280px; +} +.span6 { + width: 340px; +} +.span7 { + width: 400px; +} +.span8 { + width: 460px; +} +.span9 { + width: 520px; +} +.span10 { + width: 580px; +} +.span11 { + width: 640px; +} +.span12 { + width: 700px; +} +.span13 { + width: 760px; +} +.span14 { + width: 820px; +} +.span15 { + width: 880px; +} +.span16 { + width: 940px; +} +.span17 { + width: 1000px; +} +.span18 { + width: 1060px; +} +.span19 { + width: 1120px; +} +.span20 { + width: 1180px; +} +.span21 { + width: 1240px; +} +.span22 { + width: 1300px; +} +.span23 { + width: 1360px; +} +.span24 { + width: 1420px; +} +.row > .offset1 { + margin-left: 80px; +} +.row > .offset2 { + margin-left: 140px; +} +.row > .offset3 { + margin-left: 200px; +} +.row > .offset4 { + margin-left: 260px; +} +.row > .offset5 { + margin-left: 320px; +} +.row > .offset6 { + margin-left: 380px; +} +.row > .offset7 { + margin-left: 440px; +} +.row > .offset8 { + margin-left: 500px; +} +.row > .offset9 { + margin-left: 560px; +} +.row > .offset10 { + margin-left: 620px; +} +.row > .offset11 { + margin-left: 680px; +} +.row > .offset12 { + margin-left: 740px; +} +.span-one-third { + width: 300px; +} +.span-two-thirds { + width: 620px; +} +.row > .offset-one-third { + margin-left: 340px; +} +.row > .offset-two-thirds { + margin-left: 660px; +} +/* Typography.less + * Headings, body text, lists, code, and more for a versatile and durable typography system + * ---------------------------------------------------------------------------------------- */ +p { + font-size: 13px; + font-weight: normal; + line-height: 18px; + margin-bottom: 9px; +} +p small { + font-size: 11px; + color: #bfbfbf; +} +h1, +h2, +h3, +h4, +h5, +h6 { + font-weight: bold; + color: #404040; +} +h1 small, +h2 small, +h3 small, +h4 small, +h5 small, +h6 small { + color: #bfbfbf; +} +h1 { + margin-bottom: 18px; + font-size: 30px; + line-height: 36px; +} +h1 small { + font-size: 18px; +} +h2 { + font-size: 24px; + line-height: 36px; +} +h2 small { + font-size: 14px; +} +h3, +h4, +h5, +h6 { + line-height: 36px; +} +h3 { + font-size: 18px; +} +h3 small { + font-size: 14px; +} +h4 { + font-size: 16px; +} +h4 small { + font-size: 12px; +} +h5 { + font-size: 14px; +} +h6 { + font-size: 13px; + color: #bfbfbf; + text-transform: uppercase; +} +ul, ol { + margin: 0 0 18px 25px; +} +ul ul, +ul ol, +ol ol, +ol ul { + margin-bottom: 0; +} +ul { + list-style: disc; +} +ol { + list-style: decimal; +} +li { + line-height: 18px; + color: #808080; +} +ul.unstyled { + list-style: none; + margin-left: 0; +} +dl { + margin-bottom: 18px; +} +dl dt, dl dd { + line-height: 18px; +} +dl dt { + font-weight: bold; +} +dl dd { + margin-left: 9px; +} +hr { + margin: 20px 0 19px; + border: 0; + border-bottom: 1px solid #eee; +} +strong { + font-style: inherit; + font-weight: bold; +} +em { + font-style: italic; + font-weight: inherit; + line-height: inherit; +} +.muted { + color: #bfbfbf; +} +blockquote { + margin-bottom: 18px; + border-left: 5px solid #eee; + padding-left: 15px; +} +blockquote p { + font-size: 14px; + font-weight: 300; + line-height: 18px; + margin-bottom: 0; +} +blockquote small { + display: block; + font-size: 12px; + font-weight: 300; + line-height: 18px; + color: #bfbfbf; +} +blockquote small:before { + content: '\2014 \00A0'; +} +address { + display: block; + line-height: 18px; + margin-bottom: 18px; +} +code, pre { + padding: 0 3px 2px; + font-family: Monaco, Andale Mono, Courier New, monospace; + font-size: 12px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +code { + background-color: #fee9cc; + color: rgba(0, 0, 0, 0.75); + padding: 1px 3px; +} +pre { + background-color: #f5f5f5; + display: block; + padding: 8.5px; + margin: 0 0 18px; + line-height: 18px; + font-size: 12px; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.15); + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + white-space: pre; + white-space: pre-wrap; + word-wrap: break-word; +} +/* Forms.less + * Base styles for various input types, form layouts, and states + * ------------------------------------------------------------- */ +form { + margin-bottom: 18px; +} +fieldset { + margin-bottom: 18px; + padding-top: 18px; +} +fieldset legend { + display: block; + padding-left: 150px; + font-size: 19.5px; + line-height: 1; + color: #404040; + *padding: 0 0 5px 145px; + /* IE6-7 */ + + *line-height: 1.5; + /* IE6-7 */ + +} +form .clearfix { + margin-bottom: 18px; + zoom: 1; +} +form .clearfix:before, form .clearfix:after { + display: table; + content: ""; + zoom: 1; +} +form .clearfix:after { + clear: both; +} +label, +input, +select, +textarea { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 13px; + font-weight: normal; + line-height: normal; +} +label { + padding-top: 6px; + font-size: 13px; + line-height: 18px; + float: left; + width: 130px; + text-align: right; + color: #404040; +} +form .input { + margin-left: 150px; +} +input[type=checkbox], input[type=radio] { + cursor: pointer; +} +input, +textarea, +select, +.uneditable-input { + display: inline-block; + width: 210px; + height: 18px; + padding: 4px; + font-size: 13px; + line-height: 18px; + color: #808080; + border: 1px solid #ccc; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +select { + padding: initial; +} +input[type=checkbox], input[type=radio] { + width: auto; + height: auto; + padding: 0; + margin: 3px 0; + *margin-top: 0; + /* IE6-7 */ + + line-height: normal; + border: none; +} +input[type=file] { + background-color: #ffffff; + padding: initial; + border: initial; + line-height: initial; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} +input[type=button], input[type=reset], input[type=submit] { + width: auto; + height: auto; +} +select, input[type=file] { + height: 27px; + *height: auto; + line-height: 27px; + *margin-top: 4px; + /* For IE7, add top margin to align select with labels */ + +} +select[multiple] { + height: inherit; + background-color: #ffffff; +} +textarea { + height: auto; +} +.uneditable-input { + background-color: #ffffff; + display: block; + border-color: #eee; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + cursor: not-allowed; +} +:-moz-placeholder { + color: #bfbfbf; +} +::-webkit-input-placeholder { + color: #bfbfbf; +} +input, textarea { + -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; + -moz-transition: border linear 0.2s, box-shadow linear 0.2s; + -ms-transition: border linear 0.2s, box-shadow linear 0.2s; + -o-transition: border linear 0.2s, box-shadow linear 0.2s; + transition: border linear 0.2s, box-shadow linear 0.2s; + -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1); + -moz-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1); +} +input:focus, textarea:focus { + outline: 0; + border-color: rgba(82, 168, 236, 0.8); + -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6); + -moz-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6); + box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 8px rgba(82, 168, 236, 0.6); +} +input[type=file]:focus, input[type=checkbox]:focus, select:focus { + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + outline: 1px dotted #666; +} +form .clearfix.error > label, form .clearfix.error .help-block, form .clearfix.error .help-inline { + color: #b94a48; +} +form .clearfix.error input, form .clearfix.error textarea { + color: #b94a48; + border-color: #ee5f5b; +} +form .clearfix.error input:focus, form .clearfix.error textarea:focus { + border-color: #e9322d; + -webkit-box-shadow: 0 0 6px #f8b9b7; + -moz-box-shadow: 0 0 6px #f8b9b7; + box-shadow: 0 0 6px #f8b9b7; +} +form .clearfix.error .input-prepend .add-on, form .clearfix.error .input-append .add-on { + color: #b94a48; + background-color: #fce6e6; + border-color: #b94a48; +} +form .clearfix.warning > label, form .clearfix.warning .help-block, form .clearfix.warning .help-inline { + color: #c09853; +} +form .clearfix.warning input, form .clearfix.warning textarea { + color: #c09853; + border-color: #ccae64; +} +form .clearfix.warning input:focus, form .clearfix.warning textarea:focus { + border-color: #be9a3f; + -webkit-box-shadow: 0 0 6px #e5d6b1; + -moz-box-shadow: 0 0 6px #e5d6b1; + box-shadow: 0 0 6px #e5d6b1; +} +form .clearfix.warning .input-prepend .add-on, form .clearfix.warning .input-append .add-on { + color: #c09853; + background-color: #d2b877; + border-color: #c09853; +} +form .clearfix.success > label, form .clearfix.success .help-block, form .clearfix.success .help-inline { + color: #468847; +} +form .clearfix.success input, form .clearfix.success textarea { + color: #468847; + border-color: #57a957; +} +form .clearfix.success input:focus, form .clearfix.success textarea:focus { + border-color: #458845; + -webkit-box-shadow: 0 0 6px #9acc9a; + -moz-box-shadow: 0 0 6px #9acc9a; + box-shadow: 0 0 6px #9acc9a; +} +form .clearfix.success .input-prepend .add-on, form .clearfix.success .input-append .add-on { + color: #468847; + background-color: #bcddbc; + border-color: #468847; +} +.input-mini, +input.mini, +textarea.mini, +select.mini { + width: 60px; +} +.input-small, +input.small, +textarea.small, +select.small { + width: 90px; +} +.input-medium, +input.medium, +textarea.medium, +select.medium { + width: 150px; +} +.input-large, +input.large, +textarea.large, +select.large { + width: 210px; +} +.input-xlarge, +input.xlarge, +textarea.xlarge, +select.xlarge { + width: 270px; +} +.input-xxlarge, +input.xxlarge, +textarea.xxlarge, +select.xxlarge { + width: 530px; +} +textarea.xxlarge { + overflow-y: auto; +} +input.span1, textarea.span1 { + display: inline-block; + float: none; + width: 30px; + margin-left: 0; +} +input.span2, textarea.span2 { + display: inline-block; + float: none; + width: 90px; + margin-left: 0; +} +input.span3, textarea.span3 { + display: inline-block; + float: none; + width: 150px; + margin-left: 0; +} +input.span4, textarea.span4 { + display: inline-block; + float: none; + width: 210px; + margin-left: 0; +} +input.span5, textarea.span5 { + display: inline-block; + float: none; + width: 270px; + margin-left: 0; +} +input.span6, textarea.span6 { + display: inline-block; + float: none; + width: 330px; + margin-left: 0; +} +input.span7, textarea.span7 { + display: inline-block; + float: none; + width: 390px; + margin-left: 0; +} +input.span8, textarea.span8 { + display: inline-block; + float: none; + width: 450px; + margin-left: 0; +} +input.span9, textarea.span9 { + display: inline-block; + float: none; + width: 510px; + margin-left: 0; +} +input.span10, textarea.span10 { + display: inline-block; + float: none; + width: 570px; + margin-left: 0; +} +input.span11, textarea.span11 { + display: inline-block; + float: none; + width: 630px; + margin-left: 0; +} +input.span12, textarea.span12 { + display: inline-block; + float: none; + width: 690px; + margin-left: 0; +} +input.span13, textarea.span13 { + display: inline-block; + float: none; + width: 750px; + margin-left: 0; +} +input.span14, textarea.span14 { + display: inline-block; + float: none; + width: 810px; + margin-left: 0; +} +input.span15, textarea.span15 { + display: inline-block; + float: none; + width: 870px; + margin-left: 0; +} +input.span16, textarea.span16 { + display: inline-block; + float: none; + width: 930px; + margin-left: 0; +} +input[disabled], +select[disabled], +textarea[disabled], +input[readonly], +select[readonly], +textarea[readonly] { + background-color: #f5f5f5; + border-color: #ddd; + cursor: not-allowed; +} +.actions { + background: #f5f5f5; + margin-top: 18px; + margin-bottom: 18px; + padding: 17px 20px 18px 150px; + border-top: 1px solid #ddd; + -webkit-border-radius: 0 0 3px 3px; + -moz-border-radius: 0 0 3px 3px; + border-radius: 0 0 3px 3px; +} +.actions .secondary-action { + float: right; +} +.actions .secondary-action a { + line-height: 30px; +} +.actions .secondary-action a:hover { + text-decoration: underline; +} +.help-inline, .help-block { + font-size: 13px; + line-height: 18px; + color: #bfbfbf; +} +.help-inline { + padding-left: 5px; + *position: relative; + /* IE6-7 */ + + *top: -5px; + /* IE6-7 */ + +} +.help-block { + display: block; + max-width: 600px; +} +.inline-inputs { + color: #808080; +} +.inline-inputs span { + padding: 0 2px 0 1px; +} +.input-prepend input, .input-append input { + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; +} +.input-prepend .add-on, .input-append .add-on { + position: relative; + background: #f5f5f5; + border: 1px solid #ccc; + z-index: 2; + float: left; + display: block; + width: auto; + min-width: 16px; + height: 18px; + padding: 4px 4px 4px 5px; + margin-right: -1px; + font-weight: normal; + line-height: 18px; + color: #bfbfbf; + text-align: center; + text-shadow: 0 1px 0 #ffffff; + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} +.input-prepend .active, .input-append .active { + background: #a9dba9; + border-color: #46a546; +} +.input-prepend .add-on { + *margin-top: 1px; + /* IE6-7 */ + +} +.input-append input { + float: left; + -webkit-border-radius: 3px 0 0 3px; + -moz-border-radius: 3px 0 0 3px; + border-radius: 3px 0 0 3px; +} +.input-append .add-on { + -webkit-border-radius: 0 3px 3px 0; + -moz-border-radius: 0 3px 3px 0; + border-radius: 0 3px 3px 0; + margin-right: 0; + margin-left: -1px; +} +.inputs-list { + margin: 0 0 5px; + width: 100%; +} +.inputs-list li { + display: block; + padding: 0; + width: 100%; +} +.inputs-list label { + display: block; + float: none; + width: auto; + padding: 0; + margin-left: 20px; + line-height: 18px; + text-align: left; + white-space: normal; +} +.inputs-list label strong { + color: #808080; +} +.inputs-list label small { + font-size: 11px; + font-weight: normal; +} +.inputs-list .inputs-list { + margin-left: 25px; + margin-bottom: 10px; + padding-top: 0; +} +.inputs-list:first-child { + padding-top: 6px; +} +.inputs-list li + li { + padding-top: 2px; +} +.inputs-list input[type=radio], .inputs-list input[type=checkbox] { + margin-bottom: 0; + margin-left: -20px; + float: left; +} +.form-stacked { + padding-left: 20px; +} +.form-stacked fieldset { + padding-top: 9px; +} +.form-stacked legend { + padding-left: 0; +} +.form-stacked label { + display: block; + float: none; + width: auto; + font-weight: bold; + text-align: left; + line-height: 20px; + padding-top: 0; +} +.form-stacked .clearfix { + margin-bottom: 9px; +} +.form-stacked .clearfix div.input { + margin-left: 0; +} +.form-stacked .inputs-list { + margin-bottom: 0; +} +.form-stacked .inputs-list li { + padding-top: 0; +} +.form-stacked .inputs-list li label { + font-weight: normal; + padding-top: 0; +} +.form-stacked div.clearfix.error { + padding-top: 10px; + padding-bottom: 10px; + padding-left: 10px; + margin-top: 0; + margin-left: -10px; +} +.form-stacked .actions { + margin-left: -20px; + padding-left: 20px; +} +/* + * Tables.less + * Tables for, you guessed it, tabular data + * ---------------------------------------- */ +table { + width: 100%; + margin-bottom: 18px; + padding: 0; + font-size: 13px; + border-collapse: collapse; +} +table th, table td { + padding: 10px 10px 9px; + line-height: 18px; + text-align: left; +} +table th { + padding-top: 9px; + font-weight: bold; + vertical-align: middle; +} +table td { + vertical-align: top; + border-top: 1px solid #ddd; +} +table tbody th { + border-top: 1px solid #ddd; + vertical-align: top; +} +.condensed-table th, .condensed-table td { + padding: 5px 5px 4px; +} +.bordered-table { + border: 1px solid #ddd; + border-collapse: separate; + *border-collapse: collapse; + /* IE7, collapse table to remove spacing */ + + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.bordered-table th + th, .bordered-table td + td, .bordered-table th + td { + border-left: 1px solid #ddd; +} +.bordered-table thead tr:first-child th:first-child, .bordered-table tbody tr:first-child td:first-child { + -webkit-border-radius: 4px 0 0 0; + -moz-border-radius: 4px 0 0 0; + border-radius: 4px 0 0 0; +} +.bordered-table thead tr:first-child th:last-child, .bordered-table tbody tr:first-child td:last-child { + -webkit-border-radius: 0 4px 0 0; + -moz-border-radius: 0 4px 0 0; + border-radius: 0 4px 0 0; +} +.bordered-table tbody tr:last-child td:first-child { + -webkit-border-radius: 0 0 0 4px; + -moz-border-radius: 0 0 0 4px; + border-radius: 0 0 0 4px; +} +.bordered-table tbody tr:last-child td:last-child { + -webkit-border-radius: 0 0 4px 0; + -moz-border-radius: 0 0 4px 0; + border-radius: 0 0 4px 0; +} +table .span1 { + width: 20px; +} +table .span2 { + width: 60px; +} +table .span3 { + width: 100px; +} +table .span4 { + width: 140px; +} +table .span5 { + width: 180px; +} +table .span6 { + width: 220px; +} +table .span7 { + width: 260px; +} +table .span8 { + width: 300px; +} +table .span9 { + width: 340px; +} +table .span10 { + width: 380px; +} +table .span11 { + width: 420px; +} +table .span12 { + width: 460px; +} +table .span13 { + width: 500px; +} +table .span14 { + width: 540px; +} +table .span15 { + width: 580px; +} +table .span16 { + width: 620px; +} +.zebra-striped tbody tr:nth-child(odd) td, .zebra-striped tbody tr:nth-child(odd) th { + background-color: #f9f9f9; +} +.zebra-striped tbody tr:hover td, .zebra-striped tbody tr:hover th { + background-color: #f5f5f5; +} +table .header { + cursor: pointer; +} +table .header:after { + content: ""; + float: right; + margin-top: 7px; + border-width: 0 4px 4px; + border-style: solid; + border-color: #000 transparent; + visibility: hidden; +} +table .headerSortUp, table .headerSortDown { + background-color: rgba(141, 192, 219, 0.25); + text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); +} +table .header:hover:after { + visibility: visible; +} +table .headerSortDown:after, table .headerSortDown:hover:after { + visibility: visible; + filter: alpha(opacity=60); + -khtml-opacity: 0.6; + -moz-opacity: 0.6; + opacity: 0.6; +} +table .headerSortUp:after { + border-bottom: none; + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 4px solid #000; + visibility: visible; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + filter: alpha(opacity=60); + -khtml-opacity: 0.6; + -moz-opacity: 0.6; + opacity: 0.6; +} +table .blue { + color: #049cdb; + border-bottom-color: #049cdb; +} +table .headerSortUp.blue, table .headerSortDown.blue { + background-color: #ade6fe; +} +table .green { + color: #46a546; + border-bottom-color: #46a546; +} +table .headerSortUp.green, table .headerSortDown.green { + background-color: #cdeacd; +} +table .red { + color: #9d261d; + border-bottom-color: #9d261d; +} +table .headerSortUp.red, table .headerSortDown.red { + background-color: #f4c8c5; +} +table .yellow { + color: #ffc40d; + border-bottom-color: #ffc40d; +} +table .headerSortUp.yellow, table .headerSortDown.yellow { + background-color: #fff6d9; +} +table .orange { + color: #f89406; + border-bottom-color: #f89406; +} +table .headerSortUp.orange, table .headerSortDown.orange { + background-color: #fee9cc; +} +table .purple { + color: #7a43b6; + border-bottom-color: #7a43b6; +} +table .headerSortUp.purple, table .headerSortDown.purple { + background-color: #e2d5f0; +} +/* Patterns.less + * Repeatable UI elements outside the base styles provided from the scaffolding + * ---------------------------------------------------------------------------- */ +.topbar { + height: 40px; + position: fixed; + top: 0; + left: 0; + right: 0; + z-index: 10000; + overflow: visible; +} +.topbar a { + color: #bfbfbf; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); +} +.topbar h3 a:hover, .topbar .brand:hover, .topbar ul .active > a { + background-color: #333; + background-color: rgba(255, 255, 255, 0.05); + color: #ffffff; + text-decoration: none; +} +.topbar h3 { + position: relative; +} +.topbar h3 a, .topbar .brand { + float: left; + display: block; + padding: 8px 20px 12px; + margin-left: -20px; + color: #ffffff; + font-size: 20px; + font-weight: 200; + line-height: 1; +} +.topbar p { + margin: 0; + line-height: 40px; +} +.topbar p a:hover { + background-color: transparent; + color: #ffffff; +} +.topbar form { + float: left; + margin: 5px 0 0 0; + position: relative; + filter: alpha(opacity=100); + -khtml-opacity: 1; + -moz-opacity: 1; + opacity: 1; +} +.topbar form.pull-right { + float: right; +} +.topbar input { + background-color: #444; + background-color: rgba(255, 255, 255, 0.3); + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: normal; + font-weight: 13px; + line-height: 1; + padding: 4px 9px; + color: #ffffff; + color: rgba(255, 255, 255, 0.75); + border: 1px solid #111; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); + -webkit-transition: none; + -moz-transition: none; + -ms-transition: none; + -o-transition: none; + transition: none; +} +.topbar input:-moz-placeholder { + color: #e6e6e6; +} +.topbar input::-webkit-input-placeholder { + color: #e6e6e6; +} +.topbar input:hover { + background-color: #bfbfbf; + background-color: rgba(255, 255, 255, 0.5); + color: #ffffff; +} +.topbar input:focus, .topbar input.focused { + outline: 0; + background-color: #ffffff; + color: #404040; + text-shadow: 0 1px 0 #ffffff; + border: 0; + padding: 5px 10px; + -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); +} +.topbar-inner, .topbar .fill { + background-color: #222; + background-color: #222222; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#333333), to(#222222)); + background-image: -moz-linear-gradient(top, #333333, #222222); + background-image: -ms-linear-gradient(top, #333333, #222222); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #333333), color-stop(100%, #222222)); + background-image: -webkit-linear-gradient(top, #333333, #222222); + background-image: -o-linear-gradient(top, #333333, #222222); + background-image: linear-gradient(top, #333333, #222222); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0); + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1); +} +.topbar div > ul, .nav { + display: block; + float: left; + margin: 0 10px 0 0; + position: relative; + left: 0; +} +.topbar div > ul > li, .nav > li { + display: block; + float: left; +} +.topbar div > ul a, .nav a { + display: block; + float: none; + padding: 10px 10px 11px; + line-height: 19px; + text-decoration: none; +} +.topbar div > ul a:hover, .nav a:hover { + color: #ffffff; + text-decoration: none; +} +.topbar div > ul .active > a, .nav .active > a { + background-color: #222; + background-color: rgba(0, 0, 0, 0.5); +} +.topbar div > ul.secondary-nav, .nav.secondary-nav { + float: right; + margin-left: 10px; + margin-right: 0; +} +.topbar div > ul.secondary-nav .menu-dropdown, +.nav.secondary-nav .menu-dropdown, +.topbar div > ul.secondary-nav .dropdown-menu, +.nav.secondary-nav .dropdown-menu { + right: 0; + border: 0; +} +.topbar div > ul a.menu:hover, +.nav a.menu:hover, +.topbar div > ul li.open .menu, +.nav li.open .menu, +.topbar div > ul .dropdown-toggle:hover, +.nav .dropdown-toggle:hover, +.topbar div > ul .dropdown.open .dropdown-toggle, +.nav .dropdown.open .dropdown-toggle { + background: #444; + background: rgba(255, 255, 255, 0.05); +} +.topbar div > ul .menu-dropdown, +.nav .menu-dropdown, +.topbar div > ul .dropdown-menu, +.nav .dropdown-menu { + background-color: #333; +} +.topbar div > ul .menu-dropdown a.menu, +.nav .menu-dropdown a.menu, +.topbar div > ul .dropdown-menu a.menu, +.nav .dropdown-menu a.menu, +.topbar div > ul .menu-dropdown .dropdown-toggle, +.nav .menu-dropdown .dropdown-toggle, +.topbar div > ul .dropdown-menu .dropdown-toggle, +.nav .dropdown-menu .dropdown-toggle { + color: #ffffff; +} +.topbar div > ul .menu-dropdown a.menu.open, +.nav .menu-dropdown a.menu.open, +.topbar div > ul .dropdown-menu a.menu.open, +.nav .dropdown-menu a.menu.open, +.topbar div > ul .menu-dropdown .dropdown-toggle.open, +.nav .menu-dropdown .dropdown-toggle.open, +.topbar div > ul .dropdown-menu .dropdown-toggle.open, +.nav .dropdown-menu .dropdown-toggle.open { + background: #444; + background: rgba(255, 255, 255, 0.05); +} +.topbar div > ul .menu-dropdown li a, +.nav .menu-dropdown li a, +.topbar div > ul .dropdown-menu li a, +.nav .dropdown-menu li a { + color: #999; + text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5); +} +.topbar div > ul .menu-dropdown li a:hover, +.nav .menu-dropdown li a:hover, +.topbar div > ul .dropdown-menu li a:hover, +.nav .dropdown-menu li a:hover { + background-color: #191919; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#292929), to(#191919)); + background-image: -moz-linear-gradient(top, #292929, #191919); + background-image: -ms-linear-gradient(top, #292929, #191919); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #292929), color-stop(100%, #191919)); + background-image: -webkit-linear-gradient(top, #292929, #191919); + background-image: -o-linear-gradient(top, #292929, #191919); + background-image: linear-gradient(top, #292929, #191919); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#292929', endColorstr='#191919', GradientType=0); + color: #ffffff; +} +.topbar div > ul .menu-dropdown .active a, +.nav .menu-dropdown .active a, +.topbar div > ul .dropdown-menu .active a, +.nav .dropdown-menu .active a { + color: #ffffff; +} +.topbar div > ul .menu-dropdown .divider, +.nav .menu-dropdown .divider, +.topbar div > ul .dropdown-menu .divider, +.nav .dropdown-menu .divider { + background-color: #222; + border-color: #444; +} +.topbar ul .menu-dropdown li a, .topbar ul .dropdown-menu li a { + padding: 4px 15px; +} +li.menu, .dropdown { + position: relative; +} +a.menu:after, .dropdown-toggle:after { + width: 0; + height: 0; + display: inline-block; + content: "&darr;"; + text-indent: -99999px; + vertical-align: top; + margin-top: 8px; + margin-left: 4px; + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 4px solid #ffffff; + filter: alpha(opacity=50); + -khtml-opacity: 0.5; + -moz-opacity: 0.5; + opacity: 0.5; +} +.menu-dropdown, .dropdown-menu { + background-color: #ffffff; + float: left; + display: none; + position: absolute; + top: 40px; + z-index: 900; + min-width: 160px; + max-width: 220px; + _width: 160px; + margin-left: 0; + margin-right: 0; + padding: 6px 0; + zoom: 1; + border-color: #999; + border-color: rgba(0, 0, 0, 0.2); + border-style: solid; + border-width: 0 1px 1px; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; + -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; +} +.menu-dropdown li, .dropdown-menu li { + float: none; + display: block; + background-color: none; +} +.menu-dropdown .divider, .dropdown-menu .divider { + height: 1px; + margin: 5px 0; + overflow: hidden; + background-color: #eee; + border-bottom: 1px solid #ffffff; +} +.topbar .dropdown-menu a, .dropdown-menu a { + display: block; + padding: 4px 15px; + clear: both; + font-weight: normal; + line-height: 18px; + color: #808080; + text-shadow: 0 1px 0 #ffffff; +} +.topbar .dropdown-menu a:hover, +.dropdown-menu a:hover, +.topbar .dropdown-menu a.hover, +.dropdown-menu a.hover { + background-color: #dddddd; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#eeeeee), to(#dddddd)); + background-image: -moz-linear-gradient(top, #eeeeee, #dddddd); + background-image: -ms-linear-gradient(top, #eeeeee, #dddddd); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #eeeeee), color-stop(100%, #dddddd)); + background-image: -webkit-linear-gradient(top, #eeeeee, #dddddd); + background-image: -o-linear-gradient(top, #eeeeee, #dddddd); + background-image: linear-gradient(top, #eeeeee, #dddddd); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#dddddd', GradientType=0); + color: #404040; + text-decoration: none; + -webkit-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.025), inset 0 -1px rgba(0, 0, 0, 0.025); + -moz-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.025), inset 0 -1px rgba(0, 0, 0, 0.025); + box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.025), inset 0 -1px rgba(0, 0, 0, 0.025); +} +.open .menu, +.dropdown.open .menu, +.open .dropdown-toggle, +.dropdown.open .dropdown-toggle { + color: #ffffff; + background: #ccc; + background: rgba(0, 0, 0, 0.3); +} +.open .menu-dropdown, +.dropdown.open .menu-dropdown, +.open .dropdown-menu, +.dropdown.open .dropdown-menu { + display: block; +} +.tabs, .pills { + margin: 0 0 18px; + padding: 0; + list-style: none; + zoom: 1; +} +.tabs:before, +.pills:before, +.tabs:after, +.pills:after { + display: table; + content: ""; + zoom: 1; +} +.tabs:after, .pills:after { + clear: both; +} +.tabs > li, .pills > li { + float: left; +} +.tabs > li > a, .pills > li > a { + display: block; +} +.tabs { + border-color: #ddd; + border-style: solid; + border-width: 0 0 1px; +} +.tabs > li { + position: relative; + margin-bottom: -1px; +} +.tabs > li > a { + padding: 0 15px; + margin-right: 2px; + line-height: 34px; + border: 1px solid transparent; + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; +} +.tabs > li > a:hover { + text-decoration: none; + background-color: #eee; + border-color: #eee #eee #ddd; +} +.tabs .active > a, .tabs .active > a:hover { + color: #808080; + background-color: #ffffff; + border: 1px solid #ddd; + border-bottom-color: transparent; + cursor: default; +} +.tabs .menu-dropdown, .tabs .dropdown-menu { + top: 35px; + border-width: 1px; + -webkit-border-radius: 0 6px 6px 6px; + -moz-border-radius: 0 6px 6px 6px; + border-radius: 0 6px 6px 6px; +} +.tabs a.menu:after, .tabs .dropdown-toggle:after { + border-top-color: #999; + margin-top: 15px; + margin-left: 5px; +} +.tabs li.open.menu .menu, .tabs .open.dropdown .dropdown-toggle { + border-color: #999; +} +.tabs li.open a.menu:after, .tabs .dropdown.open .dropdown-toggle:after { + border-top-color: #555; +} +.pills a { + margin: 5px 3px 5px 0; + padding: 0 15px; + line-height: 30px; + text-shadow: 0 1px 1px #ffffff; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; +} +.pills a:hover { + color: #ffffff; + text-decoration: none; + text-shadow: 0 1px 1px rgba(0, 0, 0, 0.25); + background-color: #00438a; +} +.pills .active a { + color: #ffffff; + text-shadow: 0 1px 1px rgba(0, 0, 0, 0.25); + background-color: #0069d6; +} +.pills-vertical > li { + float: none; +} +.tab-content > .tab-pane, +.pill-content > .pill-pane, +.tab-content > div, +.pill-content > div { + display: none; +} +.tab-content > .active, .pill-content > .active { + display: block; +} +.breadcrumb { + padding: 7px 14px; + margin: 0 0 18px; + background-color: #f5f5f5; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#ffffff), to(#f5f5f5)); + background-image: -moz-linear-gradient(top, #ffffff, #f5f5f5); + background-image: -ms-linear-gradient(top, #ffffff, #f5f5f5); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #f5f5f5)); + background-image: -webkit-linear-gradient(top, #ffffff, #f5f5f5); + background-image: -o-linear-gradient(top, #ffffff, #f5f5f5); + background-image: linear-gradient(top, #ffffff, #f5f5f5); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f5f5f5', GradientType=0); + border: 1px solid #ddd; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: inset 0 1px 0 #ffffff; + -moz-box-shadow: inset 0 1px 0 #ffffff; + box-shadow: inset 0 1px 0 #ffffff; +} +.breadcrumb li { + display: inline; + text-shadow: 0 1px 0 #ffffff; +} +.breadcrumb .divider { + padding: 0 5px; + color: #bfbfbf; +} +.breadcrumb .active a { + color: #404040; +} +.hero-unit { + background-color: #f5f5f5; + margin-bottom: 30px; + padding: 60px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} +.hero-unit h1 { + margin-bottom: 0; + font-size: 60px; + line-height: 1; + letter-spacing: -1px; +} +.hero-unit p { + font-size: 18px; + font-weight: 200; + line-height: 27px; +} +footer { + margin-top: 17px; + padding-top: 17px; + border-top: 1px solid #eee; +} +.page-header { + margin-bottom: 17px; + border-bottom: 1px solid #ddd; + -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + -moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); +} +.page-header h1 { + margin-bottom: 8px; +} +.btn.danger, +.alert-message.danger, +.btn.danger:hover, +.alert-message.danger:hover, +.btn.error, +.alert-message.error, +.btn.error:hover, +.alert-message.error:hover, +.btn.success, +.alert-message.success, +.btn.success:hover, +.alert-message.success:hover, +.btn.info, +.alert-message.info, +.btn.info:hover, +.alert-message.info:hover { + color: #ffffff; +} +.btn .close, .alert-message .close { + font-family: Arial, sans-serif; + line-height: 18px; +} +.btn.danger, +.alert-message.danger, +.btn.error, +.alert-message.error { + background-color: #c43c35; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#ee5f5b), to(#c43c35)); + background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -ms-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ee5f5b), color-stop(100%, #c43c35)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); + background-image: linear-gradient(top, #ee5f5b, #c43c35); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ee5f5b', endColorstr='#c43c35', GradientType=0); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + border-color: #c43c35 #c43c35 #882a25; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); +} +.btn.success, .alert-message.success { + background-color: #57a957; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#62c462), to(#57a957)); + background-image: -moz-linear-gradient(top, #62c462, #57a957); + background-image: -ms-linear-gradient(top, #62c462, #57a957); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #62c462), color-stop(100%, #57a957)); + background-image: -webkit-linear-gradient(top, #62c462, #57a957); + background-image: -o-linear-gradient(top, #62c462, #57a957); + background-image: linear-gradient(top, #62c462, #57a957); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#62c462', endColorstr='#57a957', GradientType=0); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + border-color: #57a957 #57a957 #3d773d; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); +} +.btn.info, .alert-message.info { + background-color: #339bb9; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#5bc0de), to(#339bb9)); + background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); + background-image: -ms-linear-gradient(top, #5bc0de, #339bb9); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5bc0de), color-stop(100%, #339bb9)); + background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); + background-image: -o-linear-gradient(top, #5bc0de, #339bb9); + background-image: linear-gradient(top, #5bc0de, #339bb9); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#5bc0de', endColorstr='#339bb9', GradientType=0); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + border-color: #339bb9 #339bb9 #22697d; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); +} +.btn { + cursor: pointer; + display: inline-block; + background-color: #e6e6e6; + background-repeat: no-repeat; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), color-stop(25%, #ffffff), to(#e6e6e6)); + background-image: -webkit-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6); + background-image: -moz-linear-gradient(top, #ffffff, #ffffff 25%, #e6e6e6); + background-image: -ms-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6); + background-image: -o-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6); + background-image: linear-gradient(#ffffff, #ffffff 25%, #e6e6e6); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e6e6e6', GradientType=0); + padding: 5px 14px 6px; + text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); + color: #333; + font-size: 13px; + line-height: normal; + border: 1px solid #ccc; + border-bottom-color: #bbb; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + -webkit-transition: 0.1s linear all; + -moz-transition: 0.1s linear all; + -ms-transition: 0.1s linear all; + -o-transition: 0.1s linear all; + transition: 0.1s linear all; +} +.btn:hover { + background-position: 0 -15px; + color: #333; + text-decoration: none; +} +.btn:focus { + outline: 1px dotted #666; +} +.btn.primary { + color: #ffffff; + background-color: #0064cd; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#049cdb), to(#0064cd)); + background-image: -moz-linear-gradient(top, #049cdb, #0064cd); + background-image: -ms-linear-gradient(top, #049cdb, #0064cd); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #049cdb), color-stop(100%, #0064cd)); + background-image: -webkit-linear-gradient(top, #049cdb, #0064cd); + background-image: -o-linear-gradient(top, #049cdb, #0064cd); + background-image: linear-gradient(top, #049cdb, #0064cd); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#049cdb', endColorstr='#0064cd', GradientType=0); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + border-color: #0064cd #0064cd #003f81; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); +} +.btn.active, .btn:active { + -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); +} +.btn.disabled { + cursor: default; + background-image: none; + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + filter: alpha(opacity=65); + -khtml-opacity: 0.65; + -moz-opacity: 0.65; + opacity: 0.65; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} +.btn[disabled] { + cursor: default; + background-image: none; + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + filter: alpha(opacity=65); + -khtml-opacity: 0.65; + -moz-opacity: 0.65; + opacity: 0.65; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} +.btn.large { + font-size: 15px; + line-height: normal; + padding: 9px 14px 9px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} +.btn.small { + padding: 7px 9px 7px; + font-size: 11px; +} +:root .alert-message, :root .btn { + border-radius: 0 \0; +} +button.btn::-moz-focus-inner, input[type=submit].btn::-moz-focus-inner { + padding: 0; + border: 0; +} +.close { + float: right; + color: #000000; + font-size: 20px; + font-weight: bold; + line-height: 13.5px; + text-shadow: 0 1px 0 #ffffff; + filter: alpha(opacity=25); + -khtml-opacity: 0.25; + -moz-opacity: 0.25; + opacity: 0.25; +} +.close:hover { + color: #000000; + text-decoration: none; + filter: alpha(opacity=40); + -khtml-opacity: 0.4; + -moz-opacity: 0.4; + opacity: 0.4; +} +.alert-message { + position: relative; + padding: 7px 15px; + margin-bottom: 18px; + color: #404040; + background-color: #eedc94; + background-repeat: repeat-x; + background-image: -khtml-gradient(linear, left top, left bottom, from(#fceec1), to(#eedc94)); + background-image: -moz-linear-gradient(top, #fceec1, #eedc94); + background-image: -ms-linear-gradient(top, #fceec1, #eedc94); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fceec1), color-stop(100%, #eedc94)); + background-image: -webkit-linear-gradient(top, #fceec1, #eedc94); + background-image: -o-linear-gradient(top, #fceec1, #eedc94); + background-image: linear-gradient(top, #fceec1, #eedc94); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fceec1', endColorstr='#eedc94', GradientType=0); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + border-color: #eedc94 #eedc94 #e4c652; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + border-width: 1px; + border-style: solid; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25); +} +.alert-message .close { + margin-top: 1px; + *margin-top: 0; +} +.alert-message a { + font-weight: bold; + color: #404040; +} +.alert-message.danger p a, +.alert-message.error p a, +.alert-message.success p a, +.alert-message.info p a { + color: #ffffff; +} +.alert-message h5 { + line-height: 18px; +} +.alert-message p { + margin-bottom: 0; +} +.alert-message div { + margin-top: 5px; + margin-bottom: 2px; + line-height: 28px; +} +.alert-message .btn { + -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.25); + -moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.25); + box-shadow: 0 1px 0 rgba(255, 255, 255, 0.25); +} +.alert-message.block-message { + background-image: none; + background-color: #fdf5d9; + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + padding: 14px; + border-color: #fceec1; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} +.alert-message.block-message ul, .alert-message.block-message p { + margin-right: 30px; +} +.alert-message.block-message ul { + margin-bottom: 0; +} +.alert-message.block-message li { + color: #404040; +} +.alert-message.block-message .alert-actions { + margin-top: 5px; +} +.alert-message.block-message.error, .alert-message.block-message.success, .alert-message.block-message.info { + color: #404040; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); +} +.alert-message.block-message.error { + background-color: #fddfde; + border-color: #fbc7c6; +} +.alert-message.block-message.success { + background-color: #d1eed1; + border-color: #bfe7bf; +} +.alert-message.block-message.info { + background-color: #ddf4fb; + border-color: #c6edf9; +} +.alert-message.block-message.danger p a, +.alert-message.block-message.error p a, +.alert-message.block-message.success p a, +.alert-message.block-message.info p a { + color: #404040; +} +.pagination { + height: 36px; + margin: 18px 0; +} +.pagination ul { + float: left; + margin: 0; + border: 1px solid #ddd; + border: 1px solid rgba(0, 0, 0, 0.15); + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); +} +.pagination li { + display: inline; +} +.pagination a { + float: left; + padding: 0 14px; + line-height: 34px; + border-right: 1px solid; + border-right-color: #ddd; + border-right-color: rgba(0, 0, 0, 0.15); + *border-right-color: #ddd; + /* IE6-7 */ + + text-decoration: none; +} +.pagination a:hover, .pagination .active a { + background-color: #c7eefe; +} +.pagination .disabled a, .pagination .disabled a:hover { + background-color: transparent; + color: #bfbfbf; +} +.pagination .next a { + border: 0; +} +.well { + background-color: #f5f5f5; + margin-bottom: 20px; + padding: 19px; + min-height: 20px; + border: 1px solid #eee; + border: 1px solid rgba(0, 0, 0, 0.05); + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); +} +.well blockquote { + border-color: #ddd; + border-color: rgba(0, 0, 0, 0.15); +} +.modal-backdrop { + background-color: #000000; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 10000; +} +.modal-backdrop.fade { + opacity: 0; +} +.modal-backdrop, .modal-backdrop.fade.in { + filter: alpha(opacity=80); + -khtml-opacity: 0.8; + -moz-opacity: 0.8; + opacity: 0.8; +} +.modal { + position: fixed; + top: 50%; + left: 50%; + z-index: 11000; + width: 560px; + margin: -250px 0 0 -280px; + background-color: #ffffff; + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, 0.3); + *border: 1px solid #999; + /* IE6-7 */ + + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; +} +.modal .close { + margin-top: 7px; +} +.modal.fade { + -webkit-transition: opacity .3s linear, top .3s ease-out; + -moz-transition: opacity .3s linear, top .3s ease-out; + -ms-transition: opacity .3s linear, top .3s ease-out; + -o-transition: opacity .3s linear, top .3s ease-out; + transition: opacity .3s linear, top .3s ease-out; + top: -25%; +} +.modal.fade.in { + top: 50%; +} +.modal-header { + border-bottom: 1px solid #eee; + padding: 5px 15px; +} +.modal-body { + padding: 15px; +} +.modal-body form { + margin-bottom: 0; +} +.modal-footer { + background-color: #f5f5f5; + padding: 14px 15px 15px; + border-top: 1px solid #ddd; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; + -webkit-box-shadow: inset 0 1px 0 #ffffff; + -moz-box-shadow: inset 0 1px 0 #ffffff; + box-shadow: inset 0 1px 0 #ffffff; + zoom: 1; + margin-bottom: 0; +} +.modal-footer:before, .modal-footer:after { + display: table; + content: ""; + zoom: 1; +} +.modal-footer:after { + clear: both; +} +.modal-footer .btn { + float: right; + margin-left: 5px; +} +.modal .popover, .modal .twipsy { + z-index: 12000; +} +.twipsy { + display: block; + position: absolute; + visibility: visible; + padding: 5px; + font-size: 11px; + z-index: 1000; + filter: alpha(opacity=80); + -khtml-opacity: 0.8; + -moz-opacity: 0.8; + opacity: 0.8; +} +.twipsy.fade.in { + filter: alpha(opacity=80); + -khtml-opacity: 0.8; + -moz-opacity: 0.8; + opacity: 0.8; +} +.twipsy.above .twipsy-arrow { + bottom: 0; + left: 50%; + margin-left: -5px; + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-top: 5px solid #000000; +} +.twipsy.left .twipsy-arrow { + top: 50%; + right: 0; + margin-top: -5px; + border-top: 5px solid transparent; + border-bottom: 5px solid transparent; + border-left: 5px solid #000000; +} +.twipsy.below .twipsy-arrow { + top: 0; + left: 50%; + margin-left: -5px; + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-bottom: 5px solid #000000; +} +.twipsy.right .twipsy-arrow { + top: 50%; + left: 0; + margin-top: -5px; + border-top: 5px solid transparent; + border-bottom: 5px solid transparent; + border-right: 5px solid #000000; +} +.twipsy-inner { + padding: 3px 8px; + background-color: #000000; + color: white; + text-align: center; + max-width: 200px; + text-decoration: none; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.twipsy-arrow { + position: absolute; + width: 0; + height: 0; +} +.popover { + position: absolute; + top: 0; + left: 0; + z-index: 1000; + padding: 5px; + display: none; +} +.popover.above .arrow { + bottom: 0; + left: 50%; + margin-left: -5px; + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-top: 5px solid #000000; +} +.popover.right .arrow { + top: 50%; + left: 0; + margin-top: -5px; + border-top: 5px solid transparent; + border-bottom: 5px solid transparent; + border-right: 5px solid #000000; +} +.popover.below .arrow { + top: 0; + left: 50%; + margin-left: -5px; + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-bottom: 5px solid #000000; +} +.popover.left .arrow { + top: 50%; + right: 0; + margin-top: -5px; + border-top: 5px solid transparent; + border-bottom: 5px solid transparent; + border-left: 5px solid #000000; +} +.popover .arrow { + position: absolute; + width: 0; + height: 0; +} +.popover .inner { + background: #000000; + background: rgba(0, 0, 0, 0.8); + padding: 3px; + overflow: hidden; + width: 280px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); +} +.popover .title { + background-color: #f5f5f5; + padding: 9px 15px; + line-height: 1; + -webkit-border-radius: 3px 3px 0 0; + -moz-border-radius: 3px 3px 0 0; + border-radius: 3px 3px 0 0; + border-bottom: 1px solid #eee; +} +.popover .content { + background-color: #ffffff; + padding: 14px; + -webkit-border-radius: 0 0 3px 3px; + -moz-border-radius: 0 0 3px 3px; + border-radius: 0 0 3px 3px; + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; +} +.popover .content p, .popover .content ul, .popover .content ol { + margin-bottom: 0; +} +.fade { + -webkit-transition: opacity 0.15s linear; + -moz-transition: opacity 0.15s linear; + -ms-transition: opacity 0.15s linear; + -o-transition: opacity 0.15s linear; + transition: opacity 0.15s linear; + opacity: 0; +} +.fade.in { + opacity: 1; +} +.label { + padding: 1px 3px 2px; + font-size: 9.75px; + font-weight: bold; + color: #ffffff; + text-transform: uppercase; + white-space: nowrap; + background-color: #bfbfbf; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; +} +.label.important { + background-color: #c43c35; +} +.label.warning { + background-color: #f89406; +} +.label.success { + background-color: #46a546; +} +.label.notice { + background-color: #62cffc; +} +.media-grid { + margin-left: -20px; + margin-bottom: 0; + zoom: 1; +} +.media-grid:before, .media-grid:after { + display: table; + content: ""; + zoom: 1; +} +.media-grid:after { + clear: both; +} +.media-grid li { + display: inline; +} +.media-grid a { + float: left; + padding: 4px; + margin: 0 0 18px 20px; + border: 1px solid #ddd; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075); +} +.media-grid a img { + display: block; +} +.media-grid a:hover { + border-color: #0069d6; + -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); +} \ No newline at end of file diff --git a/routes/artist.rb b/routes/artist.rb index 4f257a4..3e853a6 100644 --- a/routes/artist.rb +++ b/routes/artist.rb @@ -1,220 +1,220 @@ #show all artists, defaults to 10, ordered by created date get "/#{@version}/artists" do limit = get_limit(params[:limit]) channel = params[:channel] if channel @artists = Artist.all('tracks.plays.channel_id' => channel, :limit=>limit.to_i, :order => [:created_at.desc ]) else @artists = Artist.all(:limit => limit.to_i, :order => [:created_at.desc ]) end respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end # show artist from id. if ?type=mbid is added, it will perform a mbid lookup get "/#{@version}/artist/:id" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end respond_to do |wants| wants.html { erb :artist } wants.xml { builder :artist } wants.json { @artist.to_json } end end get "/#{@version}/artist/:id/details" do result = Hash.new #if no channel parameter provided, we assume all channels channel = get_channel(params[:channel]) if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end artist_result = Hash.new artist_result['artist_id'] = @artist.id artist_result['artistname'] = @artist.artistname result["artist"] = artist_result @play_count = repository(:default).adapter.select("SELECT plays.playedtime, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} order by playedtime") if !@play_count.empty? - @tracks = repository(:default).adapter.select("SELECT count(plays.id) as play_count, tracks.title, tracks.id FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} group by tracks.id order by playedtime") + @tracks = repository(:default).adapter.select("SELECT count(plays.id) as play_count, tracks.title, tracks.id FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} group by tracks.id order by playedtime") result["tracks"] = @tracks.collect {|o| {:count => o.play_count, :title => o.title, :track_id => o.id} } @albums = @artist.tracks.albums result["albums"] = @albums.collect {|o| {:album_id => o.id, :albumname => o.albumname, :albumimage => o.albumimage} } result["play_count"] = @play_count.size programs = repository(:default).adapter.select("select count(plays.id) as play_count, program_id from plays, tracks, artist_tracks, artists where artists.id=#{@artist.id} AND artists.id = artist_tracks.artist_id AND artist_tracks.track_id=tracks.id and tracks.id=plays.track_id AND plays.program_id !='' group by program_id") result["programs"] = programs.collect {|o| {:play_count => o.play_count, :program_id => o.program_id} } first_play = @play_count.first #puts 'first played on '+Time.parse(first_play.playedtime.to_s).to_s result["first_play"] = Time.parse(first_play.playedtime.to_s).to_s last_play = @play_count.last #puts 'last played on '+Time.parse(last_play.playedtime.to_s).to_s result["last_play"] = Time.parse(last_play.playedtime.to_s).to_s average_duration = @artist.tracks.avg(:duration) #puts 'average track duration '+average_duration.inspect result["avg_duration"] = average_duration australian = @artist.tracks.first.aust #puts 'australian? '+australian.inspect result["australian"] = australian @artist_chart = repository(:default).adapter.select("select artists.artistname, artists.id, artist_tracks.artist_id, artists.artistmbid, count(*) as cnt from tracks, plays, artists, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id=artists.id #{channel} group by artists.id order by cnt desc") index_number = @artist_chart.index{|x|x[:id][email protected]} real_index = 1+index_number.to_i #puts 'Position on all time chart '+real_index.to_s result["chart_pos"] = real_index #@play_count_range, divides last - first into 10 time slots if @play_count.size > 1 #only makes sense if more than one play @time_range = (Time.parse(last_play.playedtime.to_s) - Time.parse(first_play.playedtime.to_s)) @slice = @time_range / 10 hat = Time.parse(first_play.playedtime.to_s) i = 0 result_array = [] while i < 10 do from = hat hat = hat + @slice to = hat to_from = "AND playedtime <= '#{to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime >= '#{from.strftime("%Y-%m-%d %H:%M:%S")}'" @play_counter = repository(:default).adapter.select("SELECT plays.playedtime, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} #{channel} #{to_from} order by playedtime") item = Hash.new item["from"] = from.to_s item["to"] = to.to_s item["count"] = @play_counter.size.to_s result_array[i] = item i += 1 end #puts 'time sliced play count '+result_array.inspect result["time_sliced"] = result_array #average play counts per week from first played to now #@play_count.size @new_time_range = (Time.now - Time.parse(first_play.playedtime.to_s)) avg = @play_count.size/(@new_time_range/(60*60*24*7)) #puts 'avg plays per week '+ avg.to_s result["avg_play_week"] = avg else #when only 1 play: result["time_sliced"] = [] result["avg_play_week"] = 0 end #played on other channels? channel_result = Hash.new channels = Channel.all channels.each do |channel| q = repository(:default).adapter.select("SELECT count(*) FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} AND plays.channel_id=#{channel.id}") if q.first.to_i>0 channel_result[channel.channelname] = q.first #puts 'played on ' + channel.channelname+' '+q.first.to_s+' times' end end result["channels"] = channel_result @res = result end respond_to do |wants| wants.json { result.to_json } end end # edit artist from id. if ?type=mbid is added, it will perform a mbid lookup get "/#{@version}/artist/:id/edit" do protected! if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end respond_to do |wants| wants.html { erb :artist_edit } end end post "/#{@version}/artist/:id/edit" do protected! @artist = Artist.get(params[:id]) raise not_found unless @artist @artist.attributes = { :artistname => params["artistname"], :artistmbid => params["artistmbid"], :artistlink => params["artistlink"], :artistnote => params["artistnote"] } @artist.save redirect "/v1/artist/#{@artist.id}" end # show tracks from artist get "/#{@version}/artist/:id/tracks" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end @tracks = @artist.tracks @tracks_json = repository(:default).adapter.select("SELECT count(plays.id) as play_count, tracks.title FROM `artists` INNER JOIN `artist_tracks` ON `artists`.`id` = `artist_tracks`.`artist_id` INNER JOIN `tracks` ON `artist_tracks`.`track_id` = `tracks`.`id` INNER JOIN `plays` ON `tracks`.`id` = `plays`.`track_id` WHERE `artists`.`id` = #{@artist.id} group by tracks.id order by playedtime") respond_to do |wants| wants.html { erb :artist_tracks } wants.xml { builder :artist_tracks } wants.json { @tracks_json.to_json } end end # show albums from artist get "/#{@version}/artist/:id/albums" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end @albums = @artist.tracks.albums respond_to do |wants| wants.html { erb :artist_albums } wants.xml { builder :artist_albums } wants.json { @albums.to_json } end end # show plays from artist get "/#{@version}/artist/:id/plays" do if params[:type] == 'mbid' || params[:id].length == 36 @artist = Artist.first(:artistmbid => params[:id]) else @artist = Artist.get(params[:id]) end channel = params[:channel] limit = get_limit(params[:limit]) if channel @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE `plays`.`channel_id` = #{channel} AND artists.id=#{@artist.id} group by tracks.id, plays.playedtime order by plays.playedtime limit #{limit}") else @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE tracks.id AND artists.id=#{@artist.id} group by tracks.id, plays.playedtime order by plays.playedtime limit #{limit}") end hat = @plays.collect {|o| {:title => o.title, :track_id => o.track_id, :trackmbid => o.trackmbid, :artistname => o.artistname, :artist_id => o.artist_id, :artistmbid => o.artistmbid, :playedtime => o.playedtime, :albumname => o.albumname, :albumimage => o.albumimage, :album_id => o.album_id, :albummbid => o.albummbid, :program_id => o.program_id, :channel_id => o.channel_id} } respond_to do |wants| wants.html { erb :artist_plays } wants.xml { builder :artist_plays } wants.json { hat.to_json } end end \ No newline at end of file diff --git a/views/layout.html.erb b/views/layout.html.erb index 9734455..6e7ba72 100644 --- a/views/layout.html.erb +++ b/views/layout.html.erb @@ -1,27 +1,27 @@ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>pav api</title> -<link rel="stylesheet" href="/css/bootstrap-1.0.0.css" type="text/css" /> +<link rel="stylesheet" href="/css/bootstrap-1.4.0.css" type="text/css" /> <link rel="stylesheet" href="/css/master.css" type="text/css" /> <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <link rel="shortcut icon" href="/images/favicon.ico"/> </head> <body> <div class="container"> <a href="http://github.com/simonhn"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" /></a> <header id="main"> <hgroup> <a href="/"><h1>pav:api</h1></a> </hgroup> </header> <div id="main-content"> <%= yield %> </div> </div> </body> </html> \ No newline at end of file
simonhn/pav-api
5290c54029de197acd85b16e6199083af0816243
updating all gems
diff --git a/Gemfile.lock b/Gemfile.lock index f33a9a5..771e232 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,117 +1,124 @@ GEM remote: http://rubygems.org/ specs: - activesupport (3.0.9) + activesupport (3.1.3) + multi_json (~> 1.0) addressable (2.2.6) - beanstalk-client (1.1.0) + beanstalk-client (1.1.1) builder (3.0.0) - chronic (0.6.2) + chronic (0.6.6) chronic_duration (0.9.6) numerizer (~> 0.1.1) - crack (0.1.8) + crack (0.3.1) daemons (1.1.4) - data_objects (0.10.6) + data_objects (0.10.7) addressable (~> 2.1) delayed_job (2.1.4) activesupport (~> 3.0) daemons delayed_job_data_mapper (1.0.0.rc) delayed_job (~> 2.1) dm-aggregates dm-core dm-observer - dm-aggregates (1.1.0) - dm-core (~> 1.1.0) - dm-core (1.1.0) - addressable (~> 2.2.4) - dm-do-adapter (1.1.0) - data_objects (~> 0.10.2) - dm-core (~> 1.1.0) - dm-migrations (1.1.0) - dm-core (~> 1.1.0) - dm-mysql-adapter (1.1.0) - dm-do-adapter (~> 1.1.0) - do_mysql (~> 0.10.2) - dm-observer (1.1.0) - dm-core (~> 1.1.0) - dm-serializer (1.1.0) - dm-core (~> 1.1.0) + dm-aggregates (1.2.0) + dm-core (~> 1.2.0) + dm-core (1.2.0) + addressable (~> 2.2.6) + dm-do-adapter (1.2.0) + data_objects (~> 0.10.6) + dm-core (~> 1.2.0) + dm-migrations (1.2.0) + dm-core (~> 1.2.0) + dm-mysql-adapter (1.2.0) + dm-do-adapter (~> 1.2.0) + do_mysql (~> 0.10.6) + dm-observer (1.2.0) + dm-core (~> 1.2.0) + dm-serializer (1.2.1) + dm-core (~> 1.2.0) fastercsv (~> 1.5.4) - json (~> 1.4.6) - dm-timestamps (1.1.0) - dm-core (~> 1.1.0) - do_mysql (0.10.6) - data_objects (= 0.10.6) + json (~> 1.6.1) + json_pure (~> 1.6.1) + multi_json (~> 1.0.3) + dm-timestamps (1.2.0) + dm-core (~> 1.2.0) + do_mysql (0.10.7) + data_objects (= 0.10.7) fastercsv (1.5.4) - foreman (0.19.0) + foreman (0.27.0) term-ansicolor (~> 1.0.5) thor (>= 0.13.6) - httparty (0.7.8) - crack (= 0.1.8) + httparty (0.5.0) + crack (>= 0.1.1) i18n (0.6.0) - json (1.4.6) - json_pure (1.5.3) - memcached (1.3) - meta-spotify (0.1.5) + json (1.6.3) + json_pure (1.6.3) + memcached (1.3.5) + meta-spotify (0.1.6) crack (>= 0.1.4) - httparty (>= 0.4.5) - mime-types (1.16) - newrelic_rpm (3.1.1) + httparty (>= 0.4.5, < 0.8) + mime-types (1.17.2) + multi_json (1.0.4) + newrelic_rpm (3.3.0) numerizer (0.1.1) - rack (1.3.2) + rack (1.3.5) rack-contrib (1.1.0) rack (>= 0.9.1) rack-cors (0.2.4) rack + rack-protection (1.1.4) + rack rack-throttle (0.3.0) rack (>= 1.0.0) rbrainz (0.5.2) rchardet19 (1.3.5) - rest-client (1.6.3) + rest-client (1.6.7) mime-types (>= 1.16) - sinatra (1.2.6) - rack (~> 1.1) - tilt (>= 1.2.2, < 2.0) - sinatra-respond_to (0.7.0) - sinatra (~> 1.2) + sinatra (1.3.1) + rack (~> 1.3, >= 1.3.4) + rack-protection (~> 1.1, >= 1.1.2) + tilt (~> 1.3, >= 1.3.3) + sinatra-respond_to (0.8.0) + sinatra (~> 1.3) stalker (0.9.0) beanstalk-client json_pure - term-ansicolor (1.0.6) + term-ansicolor (1.0.7) thor (0.14.6) - tilt (1.3.2) - yajl-ruby (0.8.2) + tilt (1.3.3) + yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES builder chronic chronic_duration crack delayed_job delayed_job_data_mapper dm-aggregates dm-core dm-migrations dm-mysql-adapter dm-serializer dm-timestamps foreman i18n json memcached meta-spotify newrelic_rpm rack rack-contrib rack-cors rack-throttle rbrainz rchardet19 rest-client sinatra sinatra-respond_to stalker yajl-ruby
simonhn/pav-api
1aff8c634a5249fea0388b1da200d3187b342888
tweaking albums chart query
diff --git a/routes/chart.rb b/routes/chart.rb index 3d26f97..e786a96 100644 --- a/routes/chart.rb +++ b/routes/chart.rb @@ -1,47 +1,47 @@ # chart of top tracks get "/#{@version}/chart/track" do program = get_program(params[:program]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) channel = get_channel(params[:channel]) @tracks = repository(:default).adapter.select("select *, cnt from (select tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at, count(*) as cnt from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{program} group by tracks.id order by cnt DESC limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") hat = @tracks.collect {|o| {:count => o.cnt, :title => o.title, :track_id => o.id, :artistname => o.artistname,:artistmbid => o.artistmbid, :trackmbid => o.trackmbid, :albumname => o.albumname, :albummbid => o.albummbid, :albumimage => o.albumimage} } respond_to do |wants| wants.html { erb :track_chart } wants.xml { builder :track_chart } wants.json { hat.to_json } end end # chart of top artist by name get "/#{@version}/chart/artist" do program = get_program(params[:program]) to_from = make_to_from(params[:from], params[:to]) limit = get_limit(params[:limit]) channel = get_channel(params[:channel]) @artists = repository(:default).adapter.select("select artists.id, artists.artistname, artists.artistmbid,count(*) as cnt from (select artist_tracks.artist_id from plays, tracks, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id #{channel} #{to_from} #{program}) as artist_tracks, artists where artist_tracks.artist_id=artists.id group by artists.id order by cnt desc limit #{limit}") #@artists = repository(:default).adapter.select("select sum(cnt) as count, har.artistname, har.id from (select artists.artistname, artists.id, artist_tracks.artist_id, count(*) as cnt from tracks, plays, artists, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id= artists.id #{to_from} group by tracks.id, plays.playedtime) as har group by har.artistname order by count desc limit #{limit}") hat = @artists.collect {|o| {:count => o.cnt, :artistname => o.artistname, :id => o.id, :artistmbid => o.artistmbid} } respond_to do |wants| wants.html { erb :artist_chart } wants.xml { builder :artist_chart } wants.json {hat.to_json} end end get "/#{@version}/chart/album" do program = get_program(params[:program]) to_from = make_to_from(params[:from], params[:to]) limit = get_limit(params[:limit]) channel = get_channel(params[:channel]) - @albums = repository(:default).adapter.select("select artists.artistname, artists.artistmbid, albums.albumname, albums.albumimage, albums.id as album_id, albums.albummbid, count(distinct plays.id) as cnt from tracks, artists, plays, albums, album_tracks, artist_tracks where tracks.id=plays.track_id AND albums.id=album_tracks.album_id AND album_tracks.track_id=tracks.id AND tracks.id=artist_tracks.track_id AND artists.id=artist_tracks.artist_id #{channel} #{to_from} #{program} group by albums.id order by cnt DESC limit #{limit}") + @albums = repository(:default).adapter.select("select artists.artistname, artists.artistmbid, albums.albumname, albums.albumimage, albums.id as album_id, albums.albummbid, count(distinct album_tracks.pid) as cnt from (select album_tracks.album_id as aid, tracks.id as tid, plays.id as pid from tracks, plays, album_tracks where tracks.id = plays.track_id AND album_tracks.track_id = tracks.id #{channel} #{to_from} #{program}) as album_tracks, albums, artists, artist_tracks where albums.id = album_tracks.aid AND album_tracks.tid = artist_tracks.track_id AND artists.id = artist_tracks.artist_id group by albums.id order by cnt DESC limit #{limit}") hat = @albums.collect {|o| {:count => o.cnt, :artistname => o.artistname, :artistmbid => o.artistmbid, :albumname => o.albumname, :album_id => o.album_id, :albummbid => o.albummbid,:albumimage => o.albumimage} } respond_to do |wants| wants.html { erb :album_chart } wants.xml { builder :album_chart } wants.json {hat.to_json} end end \ No newline at end of file
simonhn/pav-api
29904cdccba1b168574b8beb692e945c09ce2057
removing cors, doing it in varnish instead
diff --git a/pavapi.rb b/pavapi.rb index f5fe781..6700a41 100644 --- a/pavapi.rb +++ b/pavapi.rb @@ -1,286 +1,279 @@ #versioning @version = "v1" #core stuff require 'rubygems' require 'sinatra' require './models' require './store_methods' #Queueing with delayed job #require 'delayed_job' #require 'delayed_job_data_mapper' #require './storetrackjob' require 'stalker' #template systems require 'yajl/json_gem' require 'rack/contrib/jsonp' require 'builder' use Rack::JSONP #for xml fetch and parse require 'rest_client' require 'crack' #musicbrainz stuff require 'rbrainz' include MusicBrainz require 'rchardet19' require 'logger' #time parsing require 'chronic_duration' require 'chronic' # Enable New Relic #configure :production do #require 'newrelic_rpm' #end #throttling #require 'rack/throttle' #require 'memcached' #require './throttler' -require 'rack/cors' #for serving different content types require 'sinatra/respond_to' Sinatra::Application.register Sinatra::RespondTo require 'bigdecimal' #require "sinatra/reloader" if development? configure do #use Throttler, :min => 300.0, :cache => Memcached.new, :key_prefix => :throttle #use Rack::Throttle::Throttler, :min => 1.0, :cache => Memcached.new, :key_prefix => :throttle - use Rack::Cors do - allow do - origins '*' - resource '/*', :headers => :any, :methods => :get - end - end #logging DataMapper::Logger.new('log/datamapper.log', :warn ) DataMapper::Model.raise_on_save_failure = true $LOG = Logger.new('log/pavstore.log', 'monthly') # MySQL connection: @config = YAML::load( File.open( 'config/settings.yml' ) ) @connection = "#{@config['adapter']}://#{@config['username']}:#{@config['password']}@#{@config['host']}/#{@config['database']}"; DataMapper.setup(:default, @connection) DataMapper.finalize #DataMapper.auto_upgrade! #DataMapper::auto_migrate! set :default_content, :html end #Caching before '/*' do cache_control :public, :must_revalidate, :max_age => 60 unless development? end before '/demo/*' do cache_control :public, :must_revalidate, :max_age => 3600 unless development? end before '*/chart/*' do cache_control :public, :must_revalidate, :max_age => 3600 unless development? end # Error 404 Page Not Found not_found do json_status 404, "Not found" end error do json_status 500, env['sinatra.error'].message end helpers do def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Auth needed for post requests") throw(:halt, [401, "Not authorized\n"]) end end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @config = YAML::load( File.open( 'config/settings.yml' ) ) @user = @config['authuser'] @pass = @config['authpass'] @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [@user.to_s, @pass.to_s] end def json_status(code, reason) status code { :status => code, :reason => reason }.to_json end def make_to_from(played_from, played_to) #both to and from parameters provided played_from = Chronic.parse(played_from) played_to = Chronic.parse(played_to) if (!played_from.nil? && !played_to.nil?) return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end #no parameters, sets from a week ago if (played_from.nil? && played_to.nil?) now_date = DateTime.now - 7 return "AND playedtime > '#{now_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only to parameter, setting from a week before that if (played_from.nil? && !played_to.nil?) #one week = 60*60*24*7 from_date = played_to - 604800 return "AND playedtime < '#{played_to.strftime("%Y-%m-%d %H:%M:%S")}' AND playedtime > '#{from_date.strftime("%Y-%m-%d %H:%M:%S")}'" end #only from parameter if (!played_from.nil? && played_to.nil?) return "AND playedtime > '#{played_from.strftime("%Y-%m-%d %H:%M:%S")}'" end end def isNumeric(s) Float(s) != nil rescue false end def get_limit(lim) #if no limit is set, we default to 10 #a max at 5000 on limit to protect the server if isNumeric(lim) if lim.to_i < 5000 return lim else return 5000 end else return 10 end end def get_artist_query(q) if (!q.nil?) return "AND artists.artistname LIKE '%#{q}%' " end end def get_track_query(q) if (!q.nil?) return "AND tracks.title LIKE '%#{q}%' " end end def get_album_query(q) if (!q.nil?) return "AND albums.albumname LIKE '%#{q}%' " end end def get_all_query(q) if (!q.nil?) return "AND (albums.albumname LIKE '%#{q}%' OR albums.albumname LIKE '%#{q}%' OR artists.artistname LIKE '%#{q}%') " end end def get_order_by(order) if (order=='artist') return "artists.artistname ASC, plays.playedtime DESC" elsif (order=='track') return "tracks.title ASC, plays.playedtime DESC" else return "plays.playedtime DESC" end end def get_channel(channel) if(!channel.nil?) return "AND plays.channel_id=#{channel}" end end def get_program(program) if(!program.nil?) return "AND plays.program_id='#{program}'" end end def merge_tracks(old_id, new_id) old_track = Track.get(old_id) new_track = Track.get(new_id) if(old_track&&new_track) #album #move tracks from old album to new album link = AlbumTrack.all(:track_id => old_track.id) link.each{ |link_item| @album_load = Album.get(link_item.album_id) @moved = @album_load.tracks << new_track @moved.save } #delete old album_track relations link.destroy! #artist #move tracks from old artist to new artist link = ArtistTrack.all(:track_id => old_track.id) link.each{ |link_item| @artist_load = Artist.get(link_item.artist_id) @moved = @artist_load.tracks << new_track @moved.save } #delete old artist_track relations link.destroy! #plays plays = Play.all(:track_id => old_track.id) plays.each{ |link_item| link_item.update(:track_id => new_id) } #delete old track old_track.destroy! end end end #ROUTES # Front page get '/' do erb :front end require './routes/admin' require './routes/artist' require './routes/track' require './routes/album' require './routes/channel' require './routes/play' require './routes/chart' require './routes/demo' # search artist by name get "/#{@version}/search/:q" do limit = get_limit(params[:limit]) @artists = Artist.all(:artistname.like =>'%'+params[:q]+'%', :limit => limit.to_i) respond_to do |wants| wants.html { erb :artists } wants.xml { builder :artists } wants.json { @artists.to_json } end end \ No newline at end of file
simonhn/pav-api
04d620c9ecc6909c7c4b317b8a0c60309b23bccc
making plays a looot faster, the charts slighly so
diff --git a/routes/chart.rb b/routes/chart.rb index 26e0e0a..3d26f97 100644 --- a/routes/chart.rb +++ b/routes/chart.rb @@ -1,47 +1,47 @@ # chart of top tracks get "/#{@version}/chart/track" do program = get_program(params[:program]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) channel = get_channel(params[:channel]) - @tracks = repository(:default).adapter.select("select *, count(distinct plays.id) as cnt from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id where tracks.id #{channel} #{to_from} #{program} group by tracks.id order by cnt DESC limit #{limit}") + @tracks = repository(:default).adapter.select("select *, cnt from (select tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at, count(*) as cnt from tracks,plays where tracks.id = plays.track_id #{channel} #{to_from} #{program} group by tracks.id order by cnt DESC limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") hat = @tracks.collect {|o| {:count => o.cnt, :title => o.title, :track_id => o.id, :artistname => o.artistname,:artistmbid => o.artistmbid, :trackmbid => o.trackmbid, :albumname => o.albumname, :albummbid => o.albummbid, :albumimage => o.albumimage} } respond_to do |wants| wants.html { erb :track_chart } wants.xml { builder :track_chart } wants.json { hat.to_json } end end # chart of top artist by name get "/#{@version}/chart/artist" do program = get_program(params[:program]) to_from = make_to_from(params[:from], params[:to]) limit = get_limit(params[:limit]) channel = get_channel(params[:channel]) - @artists = repository(:default).adapter.select("select artists.artistname, artists.id, artist_tracks.artist_id, artists.artistmbid, count(*) as cnt from tracks, plays, artists, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id=artists.id #{channel} #{to_from} #{program} group by artists.id order by cnt desc limit #{limit}") + @artists = repository(:default).adapter.select("select artists.id, artists.artistname, artists.artistmbid,count(*) as cnt from (select artist_tracks.artist_id from plays, tracks, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id #{channel} #{to_from} #{program}) as artist_tracks, artists where artist_tracks.artist_id=artists.id group by artists.id order by cnt desc limit #{limit}") #@artists = repository(:default).adapter.select("select sum(cnt) as count, har.artistname, har.id from (select artists.artistname, artists.id, artist_tracks.artist_id, count(*) as cnt from tracks, plays, artists, artist_tracks where tracks.id=plays.track_id AND tracks.id=artist_tracks.track_id AND artist_tracks.artist_id= artists.id #{to_from} group by tracks.id, plays.playedtime) as har group by har.artistname order by count desc limit #{limit}") hat = @artists.collect {|o| {:count => o.cnt, :artistname => o.artistname, :id => o.id, :artistmbid => o.artistmbid} } respond_to do |wants| wants.html { erb :artist_chart } wants.xml { builder :artist_chart } wants.json {hat.to_json} end end get "/#{@version}/chart/album" do program = get_program(params[:program]) to_from = make_to_from(params[:from], params[:to]) limit = get_limit(params[:limit]) channel = get_channel(params[:channel]) @albums = repository(:default).adapter.select("select artists.artistname, artists.artistmbid, albums.albumname, albums.albumimage, albums.id as album_id, albums.albummbid, count(distinct plays.id) as cnt from tracks, artists, plays, albums, album_tracks, artist_tracks where tracks.id=plays.track_id AND albums.id=album_tracks.album_id AND album_tracks.track_id=tracks.id AND tracks.id=artist_tracks.track_id AND artists.id=artist_tracks.artist_id #{channel} #{to_from} #{program} group by albums.id order by cnt DESC limit #{limit}") hat = @albums.collect {|o| {:count => o.cnt, :artistname => o.artistname, :artistmbid => o.artistmbid, :albumname => o.albumname, :album_id => o.album_id, :albummbid => o.albummbid,:albumimage => o.albumimage} } respond_to do |wants| wants.html { erb :album_chart } wants.xml { builder :album_chart } wants.json {hat.to_json} end end \ No newline at end of file diff --git a/routes/play.rb b/routes/play.rb index 8458890..54f26da 100644 --- a/routes/play.rb +++ b/routes/play.rb @@ -1,34 +1,34 @@ #PLAY get "/#{@version}/plays" do #DATE_FORMAT(playedtime, '%d %m %Y %H %i %S') artist_query = get_artist_query(params[:artist_query]) track_query = get_track_query(params[:track_query]) album_query = get_album_query(params[:album_query]) query_all = get_all_query(params[:q]) order_by = get_order_by(params[:order_by]) limit = get_limit(params[:limit]) to_from = make_to_from(params[:from], params[:to]) channel = params[:channel] program = get_program(params[:program]) if channel #@plays = repository(:default).adapter.select("select * from tracks, plays, artists, artist_tracks, albums, album_tracks where plays.channel_id=#{channel} AND tracks.id=plays.track_id AND artists.id=artist_tracks.artist_id AND artist_tracks.track_id=tracks.id AND albums.id = album_tracks.album_id AND tracks.id = album_tracks.track_id #{to_from} group by tracks.id, plays.playedtime order by plays.playedtime DESC limit #{limit}") - @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE `plays`.`channel_id` = #{channel} #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}") + @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id AND plays.channel_id = #{channel} #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") else #@plays = repository(:default).adapter.select("select * from tracks, plays, artists, artist_tracks, albums, album_tracks where tracks.id=plays.track_id AND artists.id=artist_tracks.artist_id AND artist_tracks.track_id=tracks.id AND albums.id = album_tracks.album_id AND tracks.id = album_tracks.track_id #{to_from} group by tracks.id, plays.playedtime order by plays.playedtime DESC limit #{limit}") - @plays = repository(:default).adapter.select("select * from tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id Inner Join plays ON tracks.id = plays.track_id WHERE tracks.id #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}") + @plays = repository(:default).adapter.select("select * from (select plays.playedtime, plays.program_id, plays.channel_id, tracks.id, tracks.title, tracks.trackmbid, tracks.tracknote, tracks.tracklink, tracks.show, tracks.talent, tracks.aust, tracks.duration, tracks.publisher,tracks.datecopyrighted, tracks.created_at from tracks,plays where tracks.id = plays.track_id AND tracks.id #{to_from} #{artist_query} #{album_query} #{track_query} #{query_all} #{program} order by #{order_by} limit #{limit}) as tracks Left Outer Join album_tracks ON album_tracks.track_id = tracks.id Left Outer Join albums ON album_tracks.album_id = albums.id Inner Join artist_tracks ON artist_tracks.track_id = tracks.id Inner Join artists ON artists.id = artist_tracks.artist_id") end hat = @plays.collect {|o| {:title => o.title, :track_id => o.track_id, :trackmbid => o.trackmbid, :artistname => o.artistname, :artist_id => o.artist_id, :artistmbid => o.artistmbid, :playedtime => o.playedtime, :albumname => o.albumname, :albumimage => o.albumimage, :album_id => o.album_id, :albummbid => o.albummbid, :program_id => o.program_id, :channel_id => o.channel_id} } respond_to do |wants| wants.html { erb :plays } wants.xml { builder :plays } wants.json { hat.to_json } end end get "/#{@version}/play/:id" do @play = Play.get(params[:id]) respond_to do |wants| wants.json { @play.to_json } end end \ No newline at end of file