repo
string | commit
string | message
string | diff
string |
---|---|---|---|
ELLIOTTCABLE/task_master
|
3a865d0bf65e9d0e66e834e8597ac98a53af1301
|
Added a documentation coverage checker task
|
diff --git a/Rakefile.rb b/Rakefile.rb
index 558d034..1aa9191 100644
--- a/Rakefile.rb
+++ b/Rakefile.rb
@@ -1,130 +1,151 @@
($:.unshift File.expand_path(File.join( File.dirname(__FILE__), 'lib' ))).uniq!
require 'task_master'
# =======================
# = Gem packaging tasks =
# =======================
begin
require 'echoe'
task :package => :'package:install'
task :manifest => :'package:manifest'
namespace :package do
Echoe.new('task_master', TaskMaster::Version) do |g|
g.project = 'task-master'
g.author = ['elliottcable']
g.email = ['[email protected]']
g.summary = 'Clean up that Rakefile, you piece of illiterate scum! *whip crack*'
g.url = 'http://github.com/elliottcable/task_master'
g.development_dependencies = ['elliottcable-echoe >= 3.0.2', 'rspec', 'rcov', 'yard', 'stringray']
g.manifest_name = '.manifest'
g.retain_gemspec = true
g.rakefile_name = 'Rakefile.rb'
g.ignore_pattern = /^\.git\/|^meta\/|\.gemspec/
end
desc 'tests packaged files to ensure they are all present'
task :verify => :package do
# An error message will be displayed if files are missing
if system %(ruby -e "require 'rubygems'; require 'pkg/task_master-#{TaskMaster::Version}/lib/task_master'")
puts "\nThe library files are present"
end
end
end
rescue LoadError
desc 'You need the `elliottcable-echoe` gem to package task_master'
task :package
end
# =======================
# = Spec/Coverage tasks =
# =======================
begin
require 'spec'
require 'rcov'
require 'spec/rake/spectask'
task :default => :'coverage:run'
task :coverage => :'coverage:run'
namespace :coverage do
Spec::Rake::SpecTask.new(:run) do |t|
t.spec_opts = ["--format", "specdoc"]
t.spec_opts << "--colour" unless ENV['CI']
t.spec_files = Dir['spec/**/*_spec.rb'].sort
t.libs = ['lib']
t.rcov = true
t.rcov_opts = [ '--include-file', '"^lib"', '--exclude-only', '".*"']
t.rcov_dir = File.join('meta', 'coverage')
end
begin
require 'spec/rake/verify_rcov'
# For the moment, this is the only way I know of to fix RCov. I may
# release the fix as it's own gem at some point in the near future.
require 'stringray/core_ext/spec/rake/verify_rcov'
RCov::VerifyTask.new(:verify) do |t|
- t.threshold = 95.0
+ t.threshold = 50.0
t.index_html = File.join('meta', 'coverage', 'index.html')
t.require_exact_threshold = false
end
rescue LoadError
desc 'You need the `stringray` gem to verify coverage'
task :verify
end
task :open do
system 'open ' + File.join('meta', 'coverage', 'index.html') if PLATFORM['darwin']
end
end
rescue LoadError
desc 'You need the `rcov` and `rspec` gems to run specs/coverage'
task :coverage
end
# =======================
# = Documentation tasks =
# =======================
begin
require 'yard'
require 'yard/rake/yardoc_task'
task :documentation => :'documentation:generate'
namespace :documentation do
YARD::Rake::YardocTask.new :generate do |t|
t.files = ['lib/**/*.rb']
t.options = ['--output-dir', File.join('meta', 'documentation'),
'--readme', 'README.markdown']
end
YARD::Rake::YardocTask.new :dotyardoc do |t|
t.files = ['lib/**/*.rb']
t.options = ['--no-output',
'--readme', 'README.markdown']
end
+ class Numeric
+ def pretty_inspect(decimal_points = 3)
+ bits = self.to_s.split('.')
+ bits[0] = bits[0].reverse.scan(/\d{1,3}/).join(',').reverse
+ bits[1] = bits[1][0...decimal_points] if bits[1]
+ bits.join('.')
+ end
+ end
+
+ task :verify do
+ documentation_threshold = 50.0
+ doc = YARD::CLI::Yardoc.new; doc.generate = false; doc.run
+
+ percent_documented = (
+ YARD::Registry.all.select {|o| !o.docstring.empty? }.size /
+ YARD::Registry.all.size.to_f
+ ) * 100
+ puts "Documentation coverage: #{percent_documented.pretty_inspect(1)}% (threshold: #{documentation_threshold.pretty_inspect(1)}%)"
+ end
+
task :open do
system 'open ' + File.join('meta', 'documentation', 'index.html') if PLATFORM['darwin']
end
end
rescue LoadError
desc 'You need the `yard` gem to generate documentation'
task :documentation
end
# =========
# = Other =
# =========
desc 'Removes all meta producs'
task :clobber do
`rm -rf #{File.expand_path(File.join( File.dirname(__FILE__), 'meta' ))}`
end
desc 'Check everything over before commiting'
task :aok => [:'documentation:generate', :'documentation:open',
:'package:manifest', :'package:package',
- :'coverage:run', :'coverage:open', :'coverage:verify']
+ :'coverage:run', :'coverage:open',
+ :'coverage:verify', :'documentation:verify']
task :ci => [:'documentation:generate', :'coverage:run', :'coverage:verify']
\ No newline at end of file
|
ELLIOTTCABLE/task_master
|
aaf251f1f17e6d93a09123ee36cdfe47c0818378
|
Using ::new, not ::configure
|
diff --git a/README.markdown b/README.markdown
index d35e457..ac93fd3 100644
--- a/README.markdown
+++ b/README.markdown
@@ -1,95 +1,95 @@
task_master
===========
*task_master* is a suite to help you clean up your [Rakefile][]. It allows you to
quickly and easily create task groups that preform specific tasks and require
specific common [RubyGems][] and project metadata, and allows you to keep your
Rakefile quite DRY. It supports many meta-project tools, and allows you to
easily write your own task groups for any tools that it doesn't support.
[Rakefile]: <http://rake.rubyforge.org/files/doc/rakefile_rdoc.html> "Rakefile Format RDoc"
[RubyGems]: <http://rubygems.org/read/chapter/1#page22> "What is a RubyGem?"
Usage
-----
require 'task_master'
- TaskMaster.configure MyProject do |project|
+ TaskMaster.new MyProject do |project|
project.name = 'My Project'
project.unix = 'my_project'
project[:echoe].project = 'my-project' # Rubyforge project name
project.libs = ['lib', 'othershit']
project.file[:rakefile] = 'Rakefile.rb'
project.file[:manifest] = '.manifest'
project.file[:readme] = 'README.markdown'
project[:yard].markup = 'markdown' # YARD readme markup
project[:rcov].threshold = 95.0
end
tasking :package, 'Echoe'
tasking :documentation, 'YARD'
tasking :specs, 'RSpec'
Installation
------------
You can install task_master as a pre-built gem, or as a gem generated directly
from the source.
The easiest way to install task_master is to use [RubyGems][] to acquire the
latest 'release' version from [RubyForge][], using the `gem` command line tool:
sudo gem install task_master # You'll be asked for your account password.
Alternatively, you can acquire it (possibly slightly more up-to-date,
depending on how often I update the gemspec) from GitHub as follows:
# If you've ever done this before, you don't need to do it now - see http://gems.github.com
gem sources -a http://gems.github.com
sudo gem install elliottcable-task_master # You'll be asked for your account password.
Finally, you can build a gem from the latest source yourself. You need [git][],
as well as [rake][] and elliottcable's clone of [echoe][]:
git clone git://github.com/elliottcable/task_master.git
cd task_master
# If you've ever done this before, you don't need to do it now - see http://gems.github.com
gem sources -a http://gems.github.com
sudo gem install elliottcable-echoe # You'll be asked for your account password.
rake install # You'll be asked for your account password.
[RubyGems]: <http://rubyforge.org/projects/rubygems/> "RubyGems - Ruby package manager"
[RubyForge]: <http://rubyforge.org/projects/task-master/> "task_master on RubyForge"
[git]: <http://git-scm.com/> "git - Fast Version Control System"
[Rake]: <http://rake.rubyforge.org/> "RAKE - Ruby Make"
[echoe]: <http://github.com/fauna/echoe> "If you don't want to hoe, echoe"
Contributing
------------
You can contribute bug fixes or new features to task_master by forking the project
on GitHub (you'll need to register for an account first), and sending me a
pull request once you've committed your changes.
Links
-----
- [GitHub](http://github.com/elliottcable/task_master "task_master on GitHub") is the
project's primary repository host, and currently also the project's home
page
- [RubyForge](http://rubyforge.org/projects/task-master "task_master on RubyForge") is
out primary RubyGem host, as well as an alternative repository host
- [integrity](http://integrit.yreality.net/task_master "task_master on yreality's integrity server")
is our continuous integration server - if the top build on that page is
green, you can assume the latest git HEAD is safe to run/install/utilize.
- [Gitorious](http://gitorious.org/projects/task_master "task_master on Gitorious") is
an alternative repository host
- [repo.or.cz](http://repo.or.cz/w/task_master.git "task_master on repo.or.cz") is
an alternative repository host
License
-------
task_master is copyright 2008 by elliott cable.
task_master is released under the [GNU General Public License v3.0][gpl], which
allows you to freely utilize, modify, and distribute all task_master's source code
(subject to the terms of the aforementioned license).
[gpl]: <http://www.gnu.org/licenses/gpl.txt> "The GNU General Public License v3.0"
\ No newline at end of file
|
ELLIOTTCABLE/task_master
|
9e2f652ba8ae3a72bfa3f6c2bfd115892925240d
|
Added an example of planned usage
|
diff --git a/README.markdown b/README.markdown
index f048c4d..d35e457 100644
--- a/README.markdown
+++ b/README.markdown
@@ -1,79 +1,95 @@
task_master
===========
*task_master* is a suite to help you clean up your [Rakefile][]. It allows you to
quickly and easily create task groups that preform specific tasks and require
specific common [RubyGems][] and project metadata, and allows you to keep your
Rakefile quite DRY. It supports many meta-project tools, and allows you to
easily write your own task groups for any tools that it doesn't support.
[Rakefile]: <http://rake.rubyforge.org/files/doc/rakefile_rdoc.html> "Rakefile Format RDoc"
[RubyGems]: <http://rubygems.org/read/chapter/1#page22> "What is a RubyGem?"
Usage
-----
-FIXME: Usage summary
+ require 'task_master'
+
+ TaskMaster.configure MyProject do |project|
+ project.name = 'My Project'
+ project.unix = 'my_project'
+ project[:echoe].project = 'my-project' # Rubyforge project name
+ project.libs = ['lib', 'othershit']
+ project.file[:rakefile] = 'Rakefile.rb'
+ project.file[:manifest] = '.manifest'
+ project.file[:readme] = 'README.markdown'
+ project[:yard].markup = 'markdown' # YARD readme markup
+ project[:rcov].threshold = 95.0
+ end
+
+ tasking :package, 'Echoe'
+ tasking :documentation, 'YARD'
+ tasking :specs, 'RSpec'
Installation
------------
You can install task_master as a pre-built gem, or as a gem generated directly
from the source.
The easiest way to install task_master is to use [RubyGems][] to acquire the
latest 'release' version from [RubyForge][], using the `gem` command line tool:
sudo gem install task_master # You'll be asked for your account password.
Alternatively, you can acquire it (possibly slightly more up-to-date,
depending on how often I update the gemspec) from GitHub as follows:
# If you've ever done this before, you don't need to do it now - see http://gems.github.com
gem sources -a http://gems.github.com
sudo gem install elliottcable-task_master # You'll be asked for your account password.
Finally, you can build a gem from the latest source yourself. You need [git][],
as well as [rake][] and elliottcable's clone of [echoe][]:
git clone git://github.com/elliottcable/task_master.git
cd task_master
# If you've ever done this before, you don't need to do it now - see http://gems.github.com
gem sources -a http://gems.github.com
sudo gem install elliottcable-echoe # You'll be asked for your account password.
rake install # You'll be asked for your account password.
[RubyGems]: <http://rubyforge.org/projects/rubygems/> "RubyGems - Ruby package manager"
[RubyForge]: <http://rubyforge.org/projects/task-master/> "task_master on RubyForge"
[git]: <http://git-scm.com/> "git - Fast Version Control System"
[Rake]: <http://rake.rubyforge.org/> "RAKE - Ruby Make"
[echoe]: <http://github.com/fauna/echoe> "If you don't want to hoe, echoe"
Contributing
------------
You can contribute bug fixes or new features to task_master by forking the project
on GitHub (you'll need to register for an account first), and sending me a
pull request once you've committed your changes.
Links
-----
- [GitHub](http://github.com/elliottcable/task_master "task_master on GitHub") is the
project's primary repository host, and currently also the project's home
page
- [RubyForge](http://rubyforge.org/projects/task-master "task_master on RubyForge") is
out primary RubyGem host, as well as an alternative repository host
- [integrity](http://integrit.yreality.net/task_master "task_master on yreality's integrity server")
is our continuous integration server - if the top build on that page is
green, you can assume the latest git HEAD is safe to run/install/utilize.
- [Gitorious](http://gitorious.org/projects/task_master "task_master on Gitorious") is
an alternative repository host
- [repo.or.cz](http://repo.or.cz/w/task_master.git "task_master on repo.or.cz") is
an alternative repository host
License
-------
task_master is copyright 2008 by elliott cable.
task_master is released under the [GNU General Public License v3.0][gpl], which
allows you to freely utilize, modify, and distribute all task_master's source code
(subject to the terms of the aforementioned license).
[gpl]: <http://www.gnu.org/licenses/gpl.txt> "The GNU General Public License v3.0"
\ No newline at end of file
|
ELLIOTTCABLE/task_master
|
753791de3e4378fc20474360c470902f0dea446d
|
/me unrolls his whip...
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..17cf82a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+.yardoc
+pkg/
+meta/
\ No newline at end of file
diff --git a/.manifest b/.manifest
new file mode 100644
index 0000000..ed5b704
--- /dev/null
+++ b/.manifest
@@ -0,0 +1,7 @@
+lib/task_master/tasking.rb
+lib/task_master.rb
+Rakefile.rb
+README.markdown
+spec/spec_helper.rb
+spec/task_master_spec.rb
+.manifest
diff --git a/README.markdown b/README.markdown
new file mode 100644
index 0000000..f048c4d
--- /dev/null
+++ b/README.markdown
@@ -0,0 +1,79 @@
+task_master
+===========
+
+*task_master* is a suite to help you clean up your [Rakefile][]. It allows you to
+quickly and easily create task groups that preform specific tasks and require
+specific common [RubyGems][] and project metadata, and allows you to keep your
+Rakefile quite DRY. It supports many meta-project tools, and allows you to
+easily write your own task groups for any tools that it doesn't support.
+
+[Rakefile]: <http://rake.rubyforge.org/files/doc/rakefile_rdoc.html> "Rakefile Format RDoc"
+[RubyGems]: <http://rubygems.org/read/chapter/1#page22> "What is a RubyGem?"
+
+Usage
+-----
+FIXME: Usage summary
+
+Installation
+------------
+You can install task_master as a pre-built gem, or as a gem generated directly
+from the source.
+
+The easiest way to install task_master is to use [RubyGems][] to acquire the
+latest 'release' version from [RubyForge][], using the `gem` command line tool:
+
+ sudo gem install task_master # You'll be asked for your account password.
+
+Alternatively, you can acquire it (possibly slightly more up-to-date,
+depending on how often I update the gemspec) from GitHub as follows:
+
+ # If you've ever done this before, you don't need to do it now - see http://gems.github.com
+ gem sources -a http://gems.github.com
+ sudo gem install elliottcable-task_master # You'll be asked for your account password.
+
+Finally, you can build a gem from the latest source yourself. You need [git][],
+as well as [rake][] and elliottcable's clone of [echoe][]:
+
+ git clone git://github.com/elliottcable/task_master.git
+ cd task_master
+ # If you've ever done this before, you don't need to do it now - see http://gems.github.com
+ gem sources -a http://gems.github.com
+ sudo gem install elliottcable-echoe # You'll be asked for your account password.
+ rake install # You'll be asked for your account password.
+
+[RubyGems]: <http://rubyforge.org/projects/rubygems/> "RubyGems - Ruby package manager"
+[RubyForge]: <http://rubyforge.org/projects/task-master/> "task_master on RubyForge"
+[git]: <http://git-scm.com/> "git - Fast Version Control System"
+[Rake]: <http://rake.rubyforge.org/> "RAKE - Ruby Make"
+[echoe]: <http://github.com/fauna/echoe> "If you don't want to hoe, echoe"
+
+Contributing
+------------
+You can contribute bug fixes or new features to task_master by forking the project
+on GitHub (you'll need to register for an account first), and sending me a
+pull request once you've committed your changes.
+
+Links
+-----
+- [GitHub](http://github.com/elliottcable/task_master "task_master on GitHub") is the
+ project's primary repository host, and currently also the project's home
+ page
+- [RubyForge](http://rubyforge.org/projects/task-master "task_master on RubyForge") is
+ out primary RubyGem host, as well as an alternative repository host
+- [integrity](http://integrit.yreality.net/task_master "task_master on yreality's integrity server")
+ is our continuous integration server - if the top build on that page is
+ green, you can assume the latest git HEAD is safe to run/install/utilize.
+- [Gitorious](http://gitorious.org/projects/task_master "task_master on Gitorious") is
+ an alternative repository host
+- [repo.or.cz](http://repo.or.cz/w/task_master.git "task_master on repo.or.cz") is
+ an alternative repository host
+
+License
+-------
+task_master is copyright 2008 by elliott cable.
+
+task_master is released under the [GNU General Public License v3.0][gpl], which
+allows you to freely utilize, modify, and distribute all task_master's source code
+(subject to the terms of the aforementioned license).
+
+[gpl]: <http://www.gnu.org/licenses/gpl.txt> "The GNU General Public License v3.0"
\ No newline at end of file
diff --git a/Rakefile.rb b/Rakefile.rb
new file mode 100644
index 0000000..558d034
--- /dev/null
+++ b/Rakefile.rb
@@ -0,0 +1,130 @@
+($:.unshift File.expand_path(File.join( File.dirname(__FILE__), 'lib' ))).uniq!
+require 'task_master'
+
+# =======================
+# = Gem packaging tasks =
+# =======================
+begin
+ require 'echoe'
+
+ task :package => :'package:install'
+ task :manifest => :'package:manifest'
+ namespace :package do
+ Echoe.new('task_master', TaskMaster::Version) do |g|
+ g.project = 'task-master'
+ g.author = ['elliottcable']
+ g.email = ['[email protected]']
+ g.summary = 'Clean up that Rakefile, you piece of illiterate scum! *whip crack*'
+ g.url = 'http://github.com/elliottcable/task_master'
+ g.development_dependencies = ['elliottcable-echoe >= 3.0.2', 'rspec', 'rcov', 'yard', 'stringray']
+ g.manifest_name = '.manifest'
+ g.retain_gemspec = true
+ g.rakefile_name = 'Rakefile.rb'
+ g.ignore_pattern = /^\.git\/|^meta\/|\.gemspec/
+ end
+
+ desc 'tests packaged files to ensure they are all present'
+ task :verify => :package do
+ # An error message will be displayed if files are missing
+ if system %(ruby -e "require 'rubygems'; require 'pkg/task_master-#{TaskMaster::Version}/lib/task_master'")
+ puts "\nThe library files are present"
+ end
+ end
+ end
+
+rescue LoadError
+ desc 'You need the `elliottcable-echoe` gem to package task_master'
+ task :package
+end
+
+# =======================
+# = Spec/Coverage tasks =
+# =======================
+begin
+ require 'spec'
+ require 'rcov'
+ require 'spec/rake/spectask'
+
+ task :default => :'coverage:run'
+ task :coverage => :'coverage:run'
+ namespace :coverage do
+ Spec::Rake::SpecTask.new(:run) do |t|
+ t.spec_opts = ["--format", "specdoc"]
+ t.spec_opts << "--colour" unless ENV['CI']
+ t.spec_files = Dir['spec/**/*_spec.rb'].sort
+ t.libs = ['lib']
+ t.rcov = true
+ t.rcov_opts = [ '--include-file', '"^lib"', '--exclude-only', '".*"']
+ t.rcov_dir = File.join('meta', 'coverage')
+ end
+
+ begin
+ require 'spec/rake/verify_rcov'
+ # For the moment, this is the only way I know of to fix RCov. I may
+ # release the fix as it's own gem at some point in the near future.
+ require 'stringray/core_ext/spec/rake/verify_rcov'
+ RCov::VerifyTask.new(:verify) do |t|
+ t.threshold = 95.0
+ t.index_html = File.join('meta', 'coverage', 'index.html')
+ t.require_exact_threshold = false
+ end
+ rescue LoadError
+ desc 'You need the `stringray` gem to verify coverage'
+ task :verify
+ end
+
+ task :open do
+ system 'open ' + File.join('meta', 'coverage', 'index.html') if PLATFORM['darwin']
+ end
+ end
+
+rescue LoadError
+ desc 'You need the `rcov` and `rspec` gems to run specs/coverage'
+ task :coverage
+end
+
+# =======================
+# = Documentation tasks =
+# =======================
+begin
+ require 'yard'
+ require 'yard/rake/yardoc_task'
+
+ task :documentation => :'documentation:generate'
+ namespace :documentation do
+ YARD::Rake::YardocTask.new :generate do |t|
+ t.files = ['lib/**/*.rb']
+ t.options = ['--output-dir', File.join('meta', 'documentation'),
+ '--readme', 'README.markdown']
+ end
+
+ YARD::Rake::YardocTask.new :dotyardoc do |t|
+ t.files = ['lib/**/*.rb']
+ t.options = ['--no-output',
+ '--readme', 'README.markdown']
+ end
+
+ task :open do
+ system 'open ' + File.join('meta', 'documentation', 'index.html') if PLATFORM['darwin']
+ end
+ end
+
+rescue LoadError
+ desc 'You need the `yard` gem to generate documentation'
+ task :documentation
+end
+
+# =========
+# = Other =
+# =========
+desc 'Removes all meta producs'
+task :clobber do
+ `rm -rf #{File.expand_path(File.join( File.dirname(__FILE__), 'meta' ))}`
+end
+
+desc 'Check everything over before commiting'
+task :aok => [:'documentation:generate', :'documentation:open',
+ :'package:manifest', :'package:package',
+ :'coverage:run', :'coverage:open', :'coverage:verify']
+
+task :ci => [:'documentation:generate', :'coverage:run', :'coverage:verify']
\ No newline at end of file
diff --git a/lib/task_master.rb b/lib/task_master.rb
new file mode 100644
index 0000000..e2e1817
--- /dev/null
+++ b/lib/task_master.rb
@@ -0,0 +1,3 @@
+module TaskMaster
+ Version = 0
+end
\ No newline at end of file
diff --git a/lib/task_master/tasking.rb b/lib/task_master/tasking.rb
new file mode 100644
index 0000000..9621e30
--- /dev/null
+++ b/lib/task_master/tasking.rb
@@ -0,0 +1,3 @@
+class Tasking
+
+end
\ No newline at end of file
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
new file mode 100644
index 0000000..d4c8b37
--- /dev/null
+++ b/spec/spec_helper.rb
@@ -0,0 +1,6 @@
+($:.unshift File.expand_path(File.join( File.dirname(__FILE__), '..', 'lib' ))).uniq!
+require 'task_master'
+
+# Require spec here, for things like autotest and rdebug that aren't running
+# using the Rakefile.
+require 'spec'
\ No newline at end of file
diff --git a/spec/task_master_spec.rb b/spec/task_master_spec.rb
new file mode 100644
index 0000000..728bd1b
--- /dev/null
+++ b/spec/task_master_spec.rb
@@ -0,0 +1 @@
+require File.dirname(__FILE__) + '/spec_helper'
\ No newline at end of file
diff --git a/task_master.gemspec b/task_master.gemspec
new file mode 100644
index 0000000..39d2b2b
--- /dev/null
+++ b/task_master.gemspec
@@ -0,0 +1,46 @@
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = %q{task_master}
+ s.version = "0"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
+ s.authors = ["elliottcable"]
+ s.date = %q{2008-10-14}
+ s.description = %q{Clean up that Rakefile, you piece of illiterate scum! *whip crack*}
+ s.email = ["[email protected]"]
+ s.extra_rdoc_files = ["lib/task_master/tasking.rb", "lib/task_master.rb", "README.markdown"]
+ s.files = ["lib/task_master/tasking.rb", "lib/task_master.rb", "Rakefile.rb", "README.markdown", "spec/spec_helper.rb", "spec/task_master_spec.rb", ".manifest", "task_master.gemspec"]
+ s.has_rdoc = true
+ s.homepage = %q{http://github.com/elliottcable/task_master}
+ s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Task_master", "--main", "README.markdown"]
+ s.require_paths = ["lib"]
+ s.rubyforge_project = %q{task-master}
+ s.rubygems_version = %q{1.3.0}
+ s.summary = %q{Clean up that Rakefile, you piece of illiterate scum! *whip crack*}
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 2
+
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
+ s.add_development_dependency(%q<elliottcable-echoe>, [">= 0", "= 3.0.2"])
+ s.add_development_dependency(%q<rspec>, [">= 0"])
+ s.add_development_dependency(%q<rcov>, [">= 0"])
+ s.add_development_dependency(%q<yard>, [">= 0"])
+ s.add_development_dependency(%q<stringray>, [">= 0"])
+ else
+ s.add_dependency(%q<elliottcable-echoe>, [">= 0", "= 3.0.2"])
+ s.add_dependency(%q<rspec>, [">= 0"])
+ s.add_dependency(%q<rcov>, [">= 0"])
+ s.add_dependency(%q<yard>, [">= 0"])
+ s.add_dependency(%q<stringray>, [">= 0"])
+ end
+ else
+ s.add_dependency(%q<elliottcable-echoe>, [">= 0", "= 3.0.2"])
+ s.add_dependency(%q<rspec>, [">= 0"])
+ s.add_dependency(%q<rcov>, [">= 0"])
+ s.add_dependency(%q<yard>, [">= 0"])
+ s.add_dependency(%q<stringray>, [">= 0"])
+ end
+end
|
SixArm/sixarm_ruby_action_controller_mock
|
f4f8ebb3892407fb57a1797dba615441282a310e
|
Add CITATION.cff
|
diff --git a/CITATION.cff b/CITATION.cff
new file mode 100644
index 0000000..babfc2d
--- /dev/null
+++ b/CITATION.cff
@@ -0,0 +1,20 @@
+cff-version: 1.2.0
+title: SixArm.com » Ruby » <br> ActionController mock object for testing Rails
+message: >-
+ If you use this work and you want to cite it,
+ then you can use the metadata from this file.
+type: software
+authors:
+ - given-names: Joel Parker
+ family-names: Henderson
+ email: [email protected]
+ affiliation: joelparkerhenderson.com
+ orcid: 'https://orcid.org/0009-0000-4681-282X'
+identifiers:
+ - type: url
+ value: 'https://github.com/SixArm/sixarm_ruby_action_controller_mock/'
+ description: SixArm.com » Ruby » <br> ActionController mock object for testing Rails
+repository-code: 'https://github.com/SixArm/sixarm_ruby_action_controller_mock/'
+abstract: >-
+ SixArm.com » Ruby » <br> ActionController mock object for testing Rails
+license: See license file
|
SixArm/sixarm_ruby_action_controller_mock
|
1bcb059c0a3e12cdda719ab427ffffba7adf67fe
|
Add code of conduct
|
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..d33878e
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,134 @@
+
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, caste, color, religion, or sexual
+identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall
+ community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or advances of
+ any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email address,
+ without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+[INSERT CONTACT METHOD].
+All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of
+actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or permanent
+ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the
+community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.1, available at
+[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by
+[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at
+[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
+[https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
+
|
SixArm/sixarm_ruby_action_controller_mock
|
0e0a57f18f84a17ade6520c9e39d55eb227d0d84
|
Fix gemspec signing_key and cert_chain
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index 42e054d..be76797 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,40 +1,40 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-2.0", "GPL-3.0", "MIT", "MPL-2.0"]
- s.signing_key = "/opt/key/sixarm/sixarm-ruby-gem-signing-20230504-/private.pem"
- s.cert_chain = ["/opt/key/sixarm/sixarm-ruby-gem-signing-20230504-/public.pem"]
+ s.signing_key = "/opt/key/sixarm/sixarm-ruby-gem-signing-20230504-private.pem"
+ s.cert_chain = ["/opt/key/sixarm/sixarm-ruby-gem-signing-20230504-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency("minitest", ">= 5.12", "< 6")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
s.add_development_dependency("rake", ">= 12.3.3", "< 13")
s.add_development_dependency("simplecov", ">= 0.18.0", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
s.required_ruby_version = ">= 2.2"
end
|
SixArm/sixarm_ruby_action_controller_mock
|
eec747ddece33717f340dc088b81ab7a070cb688
|
Add .github/workflows/ruby.yml
|
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml
new file mode 100644
index 0000000..e6333a5
--- /dev/null
+++ b/.github/workflows/ruby.yml
@@ -0,0 +1,28 @@
+name: Ruby
+
+on:
+ push:
+ branches: [ "main" ]
+ pull_request:
+ branches: [ "main" ]
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ ruby-version: ['2.7', '3.0', '3.1', '3.2']
+
+ steps:
+ - uses: actions/checkout@v3
+ - name: Start Ruby
+ uses: ruby/setup-ruby@v1
+ with:
+ ruby-version: ${{ matrix.ruby-version }}
+ bundler-cache: true
+ - name: Run tests
+ run: bundle exec rake
|
SixArm/sixarm_ruby_action_controller_mock
|
9e1732d35976af6435c4a4bcab254ab57b76d242
|
Add platforms
|
diff --git a/Gemfile.lock b/Gemfile.lock
index 08c7d77..cd16da3 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,76 +1,84 @@
PATH
remote: .
specs:
sixarm_ruby_action_controller_mock (1.0.8)
GEM
remote: https://rubygems.org/
specs:
actionpack (4.2.11.3)
actionview (= 4.2.11.3)
activesupport (= 4.2.11.3)
rack (~> 1.6)
rack-test (~> 0.6.2)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
actionview (4.2.11.3)
activesupport (= 4.2.11.3)
builder (~> 3.1)
erubis (~> 2.7.0)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.3)
activesupport (4.2.11.3)
i18n (~> 0.7)
minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1)
builder (3.2.4)
concurrent-ruby (1.2.2)
crass (1.0.6)
docile (1.4.0)
erubis (2.7.0)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
loofah (2.21.3)
crass (~> 1.0.2)
nokogiri (>= 1.12.0)
+ mini_portile2 (2.8.2)
minitest (5.18.0)
+ nokogiri (1.15.1)
+ mini_portile2 (~> 2.8.2)
+ racc (~> 1.4)
nokogiri (1.15.1-arm64-darwin)
racc (~> 1.4)
+ nokogiri (1.15.1-x86_64-linux)
+ racc (~> 1.4)
racc (1.6.2)
rack (1.6.13)
rack-test (0.6.3)
rack (>= 1.0)
rails-deprecated_sanitizer (1.0.4)
activesupport (>= 4.2.0.alpha)
rails-dom-testing (1.0.9)
activesupport (>= 4.2.0, < 5.0)
nokogiri (~> 1.6)
rails-deprecated_sanitizer (>= 1.0.1)
rails-html-sanitizer (1.5.0)
loofah (~> 2.19, >= 2.19.1)
rake (12.3.3)
simplecov (0.22.0)
docile (~> 1.1)
simplecov-html (~> 0.11)
simplecov_json_formatter (~> 0.1)
simplecov-html (0.12.3)
simplecov_json_formatter (0.1.4)
sixarm_ruby_minitest_extensions (1.1.1)
thread_safe (0.3.6)
tzinfo (1.2.11)
thread_safe (~> 0.1)
PLATFORMS
arm64-darwin-22
+ ruby
+ x86_64-linux
DEPENDENCIES
actionpack (> 0, < 5)
minitest (>= 5.12, < 6)
rake (>= 12.3.3, < 13)
simplecov (>= 0.18.0, < 2)
sixarm_ruby_action_controller_mock!
sixarm_ruby_minitest_extensions (>= 1.0.8, < 2)
BUNDLED WITH
2.3.26
|
SixArm/sixarm_ruby_action_controller_mock
|
0decdfe6298cca490079a750bbfd71b9b3e081bc
|
Bump minitest
|
diff --git a/Gemfile.lock b/Gemfile.lock
index b0fac51..08c7d77 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,76 +1,76 @@
PATH
remote: .
specs:
sixarm_ruby_action_controller_mock (1.0.8)
GEM
remote: https://rubygems.org/
specs:
actionpack (4.2.11.3)
actionview (= 4.2.11.3)
activesupport (= 4.2.11.3)
rack (~> 1.6)
rack-test (~> 0.6.2)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
actionview (4.2.11.3)
activesupport (= 4.2.11.3)
builder (~> 3.1)
erubis (~> 2.7.0)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.3)
activesupport (4.2.11.3)
i18n (~> 0.7)
minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1)
builder (3.2.4)
concurrent-ruby (1.2.2)
crass (1.0.6)
docile (1.4.0)
erubis (2.7.0)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
loofah (2.21.3)
crass (~> 1.0.2)
nokogiri (>= 1.12.0)
minitest (5.18.0)
nokogiri (1.15.1-arm64-darwin)
racc (~> 1.4)
racc (1.6.2)
rack (1.6.13)
rack-test (0.6.3)
rack (>= 1.0)
rails-deprecated_sanitizer (1.0.4)
activesupport (>= 4.2.0.alpha)
rails-dom-testing (1.0.9)
activesupport (>= 4.2.0, < 5.0)
nokogiri (~> 1.6)
rails-deprecated_sanitizer (>= 1.0.1)
rails-html-sanitizer (1.5.0)
loofah (~> 2.19, >= 2.19.1)
rake (12.3.3)
simplecov (0.22.0)
docile (~> 1.1)
simplecov-html (~> 0.11)
simplecov_json_formatter (~> 0.1)
simplecov-html (0.12.3)
simplecov_json_formatter (0.1.4)
sixarm_ruby_minitest_extensions (1.1.1)
thread_safe (0.3.6)
tzinfo (1.2.11)
thread_safe (~> 0.1)
PLATFORMS
arm64-darwin-22
DEPENDENCIES
actionpack (> 0, < 5)
- minitest (>= 5.11.1, < 6)
+ minitest (>= 5.12, < 6)
rake (>= 12.3.3, < 13)
- simplecov (>= 0.15.1, < 2)
+ simplecov (>= 0.18.0, < 2)
sixarm_ruby_action_controller_mock!
sixarm_ruby_minitest_extensions (>= 1.0.8, < 2)
BUNDLED WITH
2.3.26
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index bdd510f..058bbea 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,40 +1,40 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-2.0", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
- s.add_development_dependency("minitest", ">= 5.12", "< 2")
+ s.add_development_dependency("minitest", ">= 5.12", "< 6")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
s.add_development_dependency("rake", ">= 12.3.3", "< 13")
s.add_development_dependency("simplecov", ">= 0.18.0", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
s.required_ruby_version = ">= 2.2"
end
|
SixArm/sixarm_ruby_action_controller_mock
|
745552447c47067ea5819a96c9a8c96c16b1bcbf
|
Bump simplecov
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index 9ff42e7..bdd510f 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,40 +1,40 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-2.0", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency("minitest", ">= 5.12", "< 2")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
s.add_development_dependency("rake", ">= 12.3.3", "< 13")
- s.add_development_dependency("simplecov", ">= 0.15.1", "< 2")
+ s.add_development_dependency("simplecov", ">= 0.18.0", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
s.required_ruby_version = ">= 2.2"
end
|
SixArm/sixarm_ruby_action_controller_mock
|
6b6155ab2e1d8fd82c688b07dbe2992b3044f78d
|
Bump minitest
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index a502d18..9ff42e7 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,40 +1,40 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-2.0", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
- s.add_development_dependency("minitest", ">= 5.11.1", "< 6")
+ s.add_development_dependency("minitest", ">= 5.12", "< 2")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
s.add_development_dependency("rake", ">= 12.3.3", "< 13")
s.add_development_dependency("simplecov", ">= 0.15.1", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
s.required_ruby_version = ">= 2.2"
end
|
SixArm/sixarm_ruby_action_controller_mock
|
86477ebe1845c57fd7febbda254e3e818f031982
|
Add GPL-2.0 license
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index c6bfbc7..a502d18 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,40 +1,40 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
- s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-3.0", "MIT", "MPL-2.0"]
+ s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-2.0", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency("minitest", ">= 5.11.1", "< 6")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
s.add_development_dependency("rake", ">= 12.3.3", "< 13")
s.add_development_dependency("simplecov", ">= 0.15.1", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
s.required_ruby_version = ">= 2.2"
end
|
SixArm/sixarm_ruby_action_controller_mock
|
aa2223dce21fb7d3c49553e70d8c17deed906059
|
Bump rake because of security
|
diff --git a/Gemfile.lock b/Gemfile.lock
index 73cc27f..b0fac51 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,76 +1,76 @@
PATH
remote: .
specs:
sixarm_ruby_action_controller_mock (1.0.8)
GEM
remote: https://rubygems.org/
specs:
actionpack (4.2.11.3)
actionview (= 4.2.11.3)
activesupport (= 4.2.11.3)
rack (~> 1.6)
rack-test (~> 0.6.2)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
actionview (4.2.11.3)
activesupport (= 4.2.11.3)
builder (~> 3.1)
erubis (~> 2.7.0)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.3)
activesupport (4.2.11.3)
i18n (~> 0.7)
minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1)
builder (3.2.4)
concurrent-ruby (1.2.2)
crass (1.0.6)
docile (1.4.0)
erubis (2.7.0)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
loofah (2.21.3)
crass (~> 1.0.2)
nokogiri (>= 1.12.0)
minitest (5.18.0)
nokogiri (1.15.1-arm64-darwin)
racc (~> 1.4)
racc (1.6.2)
rack (1.6.13)
rack-test (0.6.3)
rack (>= 1.0)
rails-deprecated_sanitizer (1.0.4)
activesupport (>= 4.2.0.alpha)
rails-dom-testing (1.0.9)
activesupport (>= 4.2.0, < 5.0)
nokogiri (~> 1.6)
rails-deprecated_sanitizer (>= 1.0.1)
rails-html-sanitizer (1.5.0)
loofah (~> 2.19, >= 2.19.1)
rake (12.3.3)
simplecov (0.22.0)
docile (~> 1.1)
simplecov-html (~> 0.11)
simplecov_json_formatter (~> 0.1)
simplecov-html (0.12.3)
simplecov_json_formatter (0.1.4)
sixarm_ruby_minitest_extensions (1.1.1)
thread_safe (0.3.6)
tzinfo (1.2.11)
thread_safe (~> 0.1)
PLATFORMS
arm64-darwin-22
DEPENDENCIES
actionpack (> 0, < 5)
minitest (>= 5.11.1, < 6)
- rake (>= 12.3.0, < 13)
+ rake (>= 12.3.3, < 13)
simplecov (>= 0.15.1, < 2)
sixarm_ruby_action_controller_mock!
sixarm_ruby_minitest_extensions (>= 1.0.8, < 2)
BUNDLED WITH
2.3.26
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index 0c575da..c6bfbc7 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,40 +1,40 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency("minitest", ">= 5.11.1", "< 6")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
- s.add_development_dependency("rake", ">= 12.3.0", "< 13")
+ s.add_development_dependency("rake", ">= 12.3.3", "< 13")
s.add_development_dependency("simplecov", ">= 0.15.1", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
s.required_ruby_version = ">= 2.2"
end
|
SixArm/sixarm_ruby_action_controller_mock
|
1a865a4e651ec5297c74622550d62bf65793d51a
|
Add Gemfile.lock
|
diff --git a/.gitignore b/.gitignore
index 2854219..978e0fe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,11 @@
# SixArm.com â Ruby â GemForge
# Our default .gitignore rules
# Updated 2019-04-26T05:22:40Z
/.bundle
/.yardoc
!/.codeclimate/
!/.codeclimate.yml
!/.travis.yml
/coverage/
/coverage.data
-/Gemfile.lock
/vendor/
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..73cc27f
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,76 @@
+PATH
+ remote: .
+ specs:
+ sixarm_ruby_action_controller_mock (1.0.8)
+
+GEM
+ remote: https://rubygems.org/
+ specs:
+ actionpack (4.2.11.3)
+ actionview (= 4.2.11.3)
+ activesupport (= 4.2.11.3)
+ rack (~> 1.6)
+ rack-test (~> 0.6.2)
+ rails-dom-testing (~> 1.0, >= 1.0.5)
+ rails-html-sanitizer (~> 1.0, >= 1.0.2)
+ actionview (4.2.11.3)
+ activesupport (= 4.2.11.3)
+ builder (~> 3.1)
+ erubis (~> 2.7.0)
+ rails-dom-testing (~> 1.0, >= 1.0.5)
+ rails-html-sanitizer (~> 1.0, >= 1.0.3)
+ activesupport (4.2.11.3)
+ i18n (~> 0.7)
+ minitest (~> 5.1)
+ thread_safe (~> 0.3, >= 0.3.4)
+ tzinfo (~> 1.1)
+ builder (3.2.4)
+ concurrent-ruby (1.2.2)
+ crass (1.0.6)
+ docile (1.4.0)
+ erubis (2.7.0)
+ i18n (0.9.5)
+ concurrent-ruby (~> 1.0)
+ loofah (2.21.3)
+ crass (~> 1.0.2)
+ nokogiri (>= 1.12.0)
+ minitest (5.18.0)
+ nokogiri (1.15.1-arm64-darwin)
+ racc (~> 1.4)
+ racc (1.6.2)
+ rack (1.6.13)
+ rack-test (0.6.3)
+ rack (>= 1.0)
+ rails-deprecated_sanitizer (1.0.4)
+ activesupport (>= 4.2.0.alpha)
+ rails-dom-testing (1.0.9)
+ activesupport (>= 4.2.0, < 5.0)
+ nokogiri (~> 1.6)
+ rails-deprecated_sanitizer (>= 1.0.1)
+ rails-html-sanitizer (1.5.0)
+ loofah (~> 2.19, >= 2.19.1)
+ rake (12.3.3)
+ simplecov (0.22.0)
+ docile (~> 1.1)
+ simplecov-html (~> 0.11)
+ simplecov_json_formatter (~> 0.1)
+ simplecov-html (0.12.3)
+ simplecov_json_formatter (0.1.4)
+ sixarm_ruby_minitest_extensions (1.1.1)
+ thread_safe (0.3.6)
+ tzinfo (1.2.11)
+ thread_safe (~> 0.1)
+
+PLATFORMS
+ arm64-darwin-22
+
+DEPENDENCIES
+ actionpack (> 0, < 5)
+ minitest (>= 5.11.1, < 6)
+ rake (>= 12.3.0, < 13)
+ simplecov (>= 0.15.1, < 2)
+ sixarm_ruby_action_controller_mock!
+ sixarm_ruby_minitest_extensions (>= 1.0.8, < 2)
+
+BUNDLED WITH
+ 2.3.26
|
SixArm/sixarm_ruby_action_controller_mock
|
d1251bbf4ca9d9b1aee723c6e7f97a4b3bd96761
|
Bump .travis.yml Ruby version
|
diff --git a/.travis.yml b/.travis.yml
index 33e4bbe..cd18da7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,13 +1,13 @@
before_install:
- gem update --system
sudo: false
cache: bundler
language: ruby
rvm:
- - 2.6
- - 2.5
- - 2.4
- - 2.3
+ - 3.2
+ - 3.1
+ - 3.0
+ - 2.7
|
SixArm/sixarm_ruby_action_controller_mock
|
35ab0f766e41df651f9b1d15eaf4b73c0226e1a9
|
Drop Coveralls
|
diff --git a/.yardoc/checksums b/.yardoc/checksums
deleted file mode 100644
index 5197853..0000000
--- a/.yardoc/checksums
+++ /dev/null
@@ -1 +0,0 @@
-lib/sixarm_ruby_action_controller_mock.rb 20f25f16a975a9236b0a40ab90ed5476f213043a
diff --git a/.yardoc/object_types b/.yardoc/object_types
deleted file mode 100644
index d373b1c..0000000
Binary files a/.yardoc/object_types and /dev/null differ
diff --git a/.yardoc/objects/root.dat b/.yardoc/objects/root.dat
deleted file mode 100644
index fc8d738..0000000
Binary files a/.yardoc/objects/root.dat and /dev/null differ
diff --git a/.yardoc/proxy_types b/.yardoc/proxy_types
deleted file mode 100644
index beefda1..0000000
Binary files a/.yardoc/proxy_types and /dev/null differ
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index a83391e..0c575da 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,41 +1,40 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency("minitest", ">= 5.11.1", "< 6")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
s.add_development_dependency("rake", ">= 12.3.0", "< 13")
s.add_development_dependency("simplecov", ">= 0.15.1", "< 2")
- s.add_development_dependency("coveralls", ">= 0.8.21", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
s.required_ruby_version = ">= 2.2"
end
|
SixArm/sixarm_ruby_action_controller_mock
|
432a4caa4e6bbd05cb46b4fe3716cef6942eb472
|
Add git ignore rules esp. for .yardoc
|
diff --git a/.gitignore b/.gitignore
index a618c61..2854219 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,12 @@
-.bundle
-.coveralls.yml
-/vendor/
-/Gemfile.lock
+# SixArm.com â Ruby â GemForge
+# Our default .gitignore rules
+# Updated 2019-04-26T05:22:40Z
+/.bundle
+/.yardoc
+!/.codeclimate/
+!/.codeclimate.yml
+!/.travis.yml
/coverage/
/coverage.data
+/Gemfile.lock
+/vendor/
|
SixArm/sixarm_ruby_action_controller_mock
|
67d3e7a255d80b26fd0b49c642ff1abbff46852b
|
Drop deprecated item
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index 3b9fa12..a83391e 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,41 +1,41 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
- s.has_rdoc = true
+
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency("minitest", ">= 5.11.1", "< 6")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
s.add_development_dependency("rake", ">= 12.3.0", "< 13")
s.add_development_dependency("simplecov", ">= 0.15.1", "< 2")
s.add_development_dependency("coveralls", ">= 0.8.21", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
s.required_ruby_version = ">= 2.2"
end
|
SixArm/sixarm_ruby_action_controller_mock
|
ef1de33edecf7a1170b7c32229aa4eaed35b273b
|
Add code owners
|
diff --git a/CODEOWNERS b/CODEOWNERS
new file mode 100644
index 0000000..bacd647
--- /dev/null
+++ b/CODEOWNERS
@@ -0,0 +1 @@
+* [email protected]
|
SixArm/sixarm_ruby_action_controller_mock
|
359e590717d50775609c328ca40d74d897256b1b
|
Add Eclipse Public License
|
diff --git a/LICENSE.md b/LICENSE.md
index 421f165..4c4b817 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,28 +1,29 @@
# License
Use any license below. Reference https://spdx.org/licenses/
* Apache License (Apache-2.0)
* BSD License (BSD-3-Clause)
* Creative Commons (CC-BY-NC-SA-4.0)
+ * Eclipse Public License (EPL-1.0)
* GNU Affero General Public License (AGPL-3.0)
* GNU General Public License (GPL-2.0, GPL-3.0)
* GNU Lesser General Public License (LGPL-3.0)
* MIT License (MIT)
* Perl Artistic License (Artistic-2.0)
* Ruby License (Ruby)
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.
This license is for the included software that is created by SixArm.
Some of the included software may have its own licenses, copyrights,
authors, etc. and these may take precedence over the SixArm license.
Copyright (c) Joel Parker Henderson
|
SixArm/sixarm_ruby_action_controller_mock
|
9e3b9b27f034c566a6b103b86e8de56dbb284cd3
|
Add gemspec required ruby version
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index 6780f2b..3b9fa12 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,39 +1,41 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20180113-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.has_rdoc = true
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency("minitest", ">= 5.11.1", "< 6")
s.add_development_dependency("sixarm_ruby_minitest_extensions", ">= 1.0.8", "< 2")
s.add_development_dependency("rake", ">= 12.3.0", "< 13")
s.add_development_dependency("simplecov", ">= 0.15.1", "< 2")
s.add_development_dependency("coveralls", ">= 0.8.21", "< 2")
s.add_development_dependency('actionpack', '> 0', '< 5')
+ s.required_ruby_version = ">= 2.2"
+
end
|
SixArm/sixarm_ruby_action_controller_mock
|
77b4f7496ae9bd9e886b3fd55270cf8b54d833a5
|
Add Code Climate badges id
|
diff --git a/.codeclimate/badges/id b/.codeclimate/badges/id
index 8b13789..b7880ca 100644
--- a/.codeclimate/badges/id
+++ b/.codeclimate/badges/id
@@ -1 +1 @@
-
+559ff8ae3dc812cb457f
|
SixArm/sixarm_ruby_action_controller_mock
|
6e446458039bf3fbccde57567e3a1f77ae8ff3ff
|
Add Code Climate badges id
|
diff --git a/.codeclimate/badges/id b/.codeclimate/badges/id
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/.codeclimate/badges/id
@@ -0,0 +1 @@
+
|
SixArm/sixarm_ruby_action_controller_mock
|
c13b03ecb8aa162ba414a80024682d16904f6267
|
Retire Ruby 2.1
|
diff --git a/.travis.yml b/.travis.yml
index af14e38..fff392f 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,16 +1,14 @@
before_install:
- gem update --system
sudo: false
cache: bundler
language: ruby
rvm:
- - ruby-head
- 2.5
- 2.4
- 2.3
- 2.2
- - 2.1
|
SixArm/sixarm_ruby_action_controller_mock
|
838ee2db25cf74e7c8adaccf55c3b7f60ffb4e87
|
Add GPL-2.0 license
|
diff --git a/LICENSE.md b/LICENSE.md
index 9e8b421..421f165 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,28 +1,28 @@
# License
Use any license below. Reference https://spdx.org/licenses/
* Apache License (Apache-2.0)
* BSD License (BSD-3-Clause)
* Creative Commons (CC-BY-NC-SA-4.0)
* GNU Affero General Public License (AGPL-3.0)
- * GNU General Public License (GPL-3.0)
+ * GNU General Public License (GPL-2.0, GPL-3.0)
* GNU Lesser General Public License (LGPL-3.0)
* MIT License (MIT)
* Perl Artistic License (Artistic-2.0)
* Ruby License (Ruby)
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.
This license is for the included software that is created by SixArm.
Some of the included software may have its own licenses, copyrights,
authors, etc. and these may take precedence over the SixArm license.
Copyright (c) Joel Parker Henderson
|
SixArm/sixarm_ruby_action_controller_mock
|
e5c673a0b0161092174abe00e42db56aa1a21283
|
Fix arrows
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index 26c4dc1..2c0173f 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,39 +1,39 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
- s.summary = "SixArm.com » Ruby » ActionController mock object that we use to test our various gems for Rails."
+ s.summary = "SixArm.com â Ruby â ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20150314-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20150314-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.has_rdoc = true
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency('minitest', '>= 5.7.0', '< 6')
s.add_development_dependency('sixarm_ruby_minitest_extensions', '= 1.0.5')
s.add_development_dependency('rake', '> 10.4.2', '< 11')
s.add_development_dependency('simplecov', '>= 0.10.0', '< 2')
s.add_development_dependency('coveralls', '>= 0.8.2', '< 2')
s.add_development_dependency('actionpack', '> 0', '< 5')
end
|
SixArm/sixarm_ruby_action_controller_mock
|
264d098045e24597868b52891fc38401481271d0
|
Fix standardization of license abbreviations
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index 3edcbdc..26c4dc1 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,39 +1,39 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com » Ruby » ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
- s.licenses = ["BSD", "GPL", "MIT", "PAL", "Various"]
+ s.licenses = ["Apache-2.0", "Artistic-2.0", "BSD-3-Clause", "GPL-3.0", "MIT", "MPL-2.0"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20150314-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20150314-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.has_rdoc = true
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency('minitest', '>= 5.7.0', '< 6')
s.add_development_dependency('sixarm_ruby_minitest_extensions', '= 1.0.5')
s.add_development_dependency('rake', '> 10.4.2', '< 11')
s.add_development_dependency('simplecov', '>= 0.10.0', '< 2')
s.add_development_dependency('coveralls', '>= 0.8.2', '< 2')
s.add_development_dependency('actionpack', '> 0', '< 5')
end
|
SixArm/sixarm_ruby_action_controller_mock
|
bbc08833a0489556abb9812a881056d18eb60576
|
Add new Ruby versions to Travis CI
|
diff --git a/.travis.yml b/.travis.yml
index 3d52693..e9b3eec 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,9 +1,11 @@
sudo: false
cache: bundler
language: ruby
rvm:
- ruby-head
- rbx-3
+ - 2.4
+ - 2.3
- 2.2
- 2.1
- 2.0
|
SixArm/sixarm_ruby_action_controller_mock
|
24ed4d5a087b6a1ff409cab35d7925020ea0af88
|
Fix tests by adding minitest extensions gem
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index c6887f9..3edcbdc 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,38 +1,39 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com » Ruby » ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["BSD", "GPL", "MIT", "PAL", "Various"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20150314-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20150314-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.has_rdoc = true
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
"Rakefile",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency('minitest', '>= 5.7.0', '< 6')
+ s.add_development_dependency('sixarm_ruby_minitest_extensions', '= 1.0.5')
s.add_development_dependency('rake', '> 10.4.2', '< 11')
s.add_development_dependency('simplecov', '>= 0.10.0', '< 2')
s.add_development_dependency('coveralls', '>= 0.8.2', '< 2')
s.add_development_dependency('actionpack', '> 0', '< 5')
end
|
SixArm/sixarm_ruby_action_controller_mock
|
d0f0e5a6bd3f3732b55da5ea93b294f0b5c23e32
|
Fix travis versions by relaxing them
|
diff --git a/.travis.yml b/.travis.yml
index 06af540..5ab2108 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,9 +1,9 @@
sudo: false
cache: bundler
language: ruby
rvm:
- ruby-head
- rbx-2
- - 2.2.0
- - 2.1.0
- - 2.0.0
+ - 2.2
+ - 2.1
+ - 2.0
|
SixArm/sixarm_ruby_action_controller_mock
|
fe191a8c2df92a1d9722b55622348c073dfcf714
|
Move contributing file to top level
|
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..a9f152a
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,5 @@
+# Contributing
+
+To contribute code, you can create a pull request, or send us email, or chat with us, whichever is easiest for you.
+
+To contribute money, you can use PayPal to send money to [email protected], or email us to ask about other ways.
|
SixArm/sixarm_ruby_action_controller_mock
|
23e0a965283f81a1e666b6e9994252ab0aaa5d7f
|
Fix double-slash
|
diff --git a/.gitignore b/.gitignore
index 0a486d7..a618c61 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,6 @@
.bundle
.coveralls.yml
-//vendor//
+/vendor/
/Gemfile.lock
/coverage/
/coverage.data
|
SixArm/sixarm_ruby_action_controller_mock
|
5a1ed1b694197209b0a00c8a01081fda830210c3
|
Fix Gemfile.lock path
|
diff --git a/.gitignore b/.gitignore
index d727eb9..0a486d7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,6 @@
.bundle
.coveralls.yml
//vendor//
-Gemfile.lock
+/Gemfile.lock
/coverage/
/coverage.data
|
SixArm/sixarm_ruby_action_controller_mock
|
36b724a98258e429fa19db5a70b045d3905bb6b9
|
Fix vendor top level path
|
diff --git a/.gitignore b/.gitignore
index 099d632..d727eb9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,6 @@
.bundle
.coveralls.yml
-vendor
+//vendor//
Gemfile.lock
/coverage/
/coverage.data
|
SixArm/sixarm_ruby_action_controller_mock
|
6c82190c65dead70f444217286761460885c4675
|
Ignore coverage
|
diff --git a/.gitignore b/.gitignore
index 3511ffb..099d632 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
.bundle
.coveralls.yml
vendor
Gemfile.lock
+/coverage/
+/coverage.data
|
SixArm/sixarm_ruby_action_controller_mock
|
45bd39f366cc5386e255753298e38972d1176336
|
Ignore Gemfile.lock
|
diff --git a/.gitignore b/.gitignore
index 84f1806..3511ffb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
.bundle
.coveralls.yml
vendor
+Gemfile.lock
|
SixArm/sixarm_ruby_action_controller_mock
|
8c4ca5a5257f36a779de576bffc6f03f81d2cb34
|
Refactor gems from Gemfile to gemspec
|
diff --git a/Gemfile b/Gemfile
index 1cde336..fa75df1 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,9 +1,3 @@
source 'https://rubygems.org'
-group :test do
- gem 'minitest', '>= 5.7.0', '< 6', require: false
- gem 'rake', '>= 10.4.2', '< 11', require: false
- gem 'simplecov', '>= 0.10.0', '< 1', require: false
- gem 'coveralls', '>= 0.8.2', '< 1', require: false
- gem 'actionpack', '>= 2', '< 5', require: false
-end
+gemspec
|
SixArm/sixarm_ruby_action_controller_mock
|
b062afa98a28f62424bc03afcad82b3c70e99c9b
|
Add contributing file
|
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 9cba265..a9f152a 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -1,28 +1,5 @@
# Contributing
-Thank you for contributing!
+To contribute code, you can create a pull request, or send us email, or chat with us, whichever is easiest for you.
-If you would like to contribute a donation, an easy way is to use PayPal to [email protected].
-
-If you would like to contribute help, the next section is for you.
-
-
-## Contributing to the source
-
-We love pull requests for improvments to the source code and documentation.
-
-There are three easy steps:
-
-1. Fork the repo.
-
- * Before you do any work please run our existing tests to make sure the code runs cleanly.
-
-2. Work as you like.
-
- * Please create tests. This helps us know that all your code runs cleanly.
-
-3. Push to your fork and submit a pull request.
-
- * We'll take a look as soon as we can; this is typically within a business day.
-
-Thank you again!
+To contribute money, you can use PayPal to send money to [email protected], or email us to ask about other ways.
|
SixArm/sixarm_ruby_action_controller_mock
|
f0b36128c37c59f22468b285ea8fa20f43573a25
|
Normalize default tasks
|
diff --git a/Rakefile b/Rakefile
index f36f1ba..babe792 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,23 +1,10 @@
# -*- coding: utf-8 -*-
require "rake"
require "rake/testtask"
Rake::TestTask.new(:test) do |t|
t.libs.push("lib", "test")
t.pattern = "test/**/*.rb"
end
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
-task :default => [:test]
+
task :default => [:test]
|
SixArm/sixarm_ruby_action_controller_mock
|
be56b2e9a73735604aef882977f86073ddc3172c
|
Set linguist documentation in .gitattributes
|
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..bba615e
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+coverage/* linguist-documentation
+doc/* linguist-documentation
|
SixArm/sixarm_ruby_action_controller_mock
|
beaf24125c46a796d01a2f61fd78bce8a10712fd
|
Add coveralls configuration
|
diff --git a/.gitignore b/.gitignore
index 180bf07..84f1806 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
.bundle
+.coveralls.yml
vendor
|
SixArm/sixarm_ruby_action_controller_mock
|
6426a94732366b3e68742ba2ab38cfe0b139b603
|
Excise gemsepc files
|
diff --git a/sixarm_ruby_action_controller_mock.gemspec b/sixarm_ruby_action_controller_mock.gemspec
index 3d9e479..c6887f9 100644
--- a/sixarm_ruby_action_controller_mock.gemspec
+++ b/sixarm_ruby_action_controller_mock.gemspec
@@ -1,45 +1,38 @@
# -*- coding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "sixarm_ruby_action_controller_mock"
s.summary = "SixArm.com » Ruby » ActionController mock object that we use to test our various gems for Rails."
s.description = "This provides basics we need; you probably won't ever need to use this gem."
s.version = "1.0.8"
s.author = "SixArm"
s.email = "[email protected]"
s.homepage = "http://sixarm.com/"
s.licenses = ["BSD", "GPL", "MIT", "PAL", "Various"]
s.signing_key = "/opt/keys/sixarm/sixarm-rsa-4096-x509-20150314-private.pem"
s.cert_chain = ["/opt/keys/sixarm/sixarm-rsa-4096-x509-20150314-public.pem"]
s.platform = Gem::Platform::RUBY
s.require_path = "lib"
s.has_rdoc = true
- s.files = ["README.md",'LICENSE.md','lib/sixarm_ruby_action_controller_mock.rb']
s.test_files = ["test/sixarm_ruby_action_controller_mock_test.rb"]
s.files = [
- ".gemtest",
- "CHANGES.md",
- "CONTRIBUTING.md",
- "LICENSE.md",
"Rakefile",
- "README.md",
- "VERSION",
"lib/sixarm_ruby_action_controller_mock.rb",
]
s.test_files = [
"test/sixarm_ruby_action_controller_mock_test.rb",
]
s.add_development_dependency('minitest', '>= 5.7.0', '< 6')
s.add_development_dependency('rake', '> 10.4.2', '< 11')
s.add_development_dependency('simplecov', '>= 0.10.0', '< 2')
s.add_development_dependency('coveralls', '>= 0.8.2', '< 2')
s.add_development_dependency('actionpack', '> 0', '< 5')
end
|
rkh/presentations
|
69826cb17bc94a3d6fc6109cab745aee2d793e71
|
clean up and update
|
diff --git a/Gemfile b/Gemfile
index a230dda..72f0151 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,22 +1,22 @@
source :rubygems unless ENV['QUICK']
group :slides do
- gem 'showoff'
+ gem 'showoff', :git => 'https://github.com/schacon/showoff'
gem 'rmagick'
gem 'pdfkit'
end
group :demo do
gem 'thin'
- gem 'sinatra', '~> 1.2.6'
+ gem 'sinatra'
gem 'escape_utils'
gem 'capture_stdout'
gem 'slim'
gem 'sass'
gem 'coffee-script'
end
group :development do
gem 'foreman'
gem 'compass'
end
diff --git a/Gemfile.lock b/Gemfile.lock
index 6010169..5b5fd17 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,68 +1,80 @@
+GIT
+ remote: https://github.com/schacon/showoff
+ revision: 335e142e4a2f8c17c3e1d0ec67d708c45b82ba3b
+ specs:
+ showoff (0.7.0)
+ bluecloth
+ gli (>= 1.3.2)
+ json
+ nokogiri
+ parslet
+ sinatra
+
GEM
remote: http://rubygems.org/
specs:
- bluecloth (2.1.0)
+ blankslate (2.1.2.4)
+ bluecloth (2.2.0)
capture_stdout (0.0.1)
- chunky_png (1.2.0)
+ chunky_png (1.2.5)
coffee-script (2.2.0)
coffee-script-source
execjs
- coffee-script-source (1.1.1)
+ coffee-script-source (1.1.3)
compass (0.11.5)
chunky_png (~> 1.2)
fssm (>= 0.2.7)
sass (~> 3.1)
daemons (1.1.4)
- escape_utils (0.2.3)
+ escape_utils (0.2.4)
eventmachine (0.12.10)
- execjs (1.2.0)
+ execjs (1.2.9)
multi_json (~> 1.0)
- foreman (0.19.0)
+ foreman (0.26.1)
term-ansicolor (~> 1.0.5)
thor (>= 0.13.6)
fssm (0.2.7)
- gli (1.3.2)
- json (1.5.3)
+ gli (1.3.5)
+ json (1.6.1)
multi_json (1.0.3)
nokogiri (1.5.0)
+ parslet (1.2.3)
+ blankslate (~> 2.0)
pdfkit (0.5.2)
- rack (1.3.0)
+ rack (1.3.5)
+ rack-protection (1.1.4)
+ rack
rmagick (2.13.1)
- sass (3.1.4)
- showoff (0.4.2)
- bluecloth
- gli (>= 1.2.5)
- json
- nokogiri
- sinatra
- sinatra (1.2.6)
- rack (~> 1.1)
- tilt (< 2.0, >= 1.2.2)
- slim (0.9.4)
- temple (~> 0.3.0)
- tilt (~> 1.2)
- temple (0.3.2)
- term-ansicolor (1.0.5)
- thin (1.2.11)
+ sass (3.1.10)
+ sinatra (1.3.1)
+ rack (>= 1.3.4, ~> 1.3)
+ rack-protection (>= 1.1.2, ~> 1.1)
+ tilt (>= 1.3.3, ~> 1.3)
+ slim (1.0.4)
+ temple (~> 0.3.4)
+ tilt (~> 1.3.2)
+ temple (0.3.4)
+ term-ansicolor (1.0.7)
+ thin (1.3.0)
daemons (>= 1.0.9)
eventmachine (>= 0.12.6)
rack (>= 1.0.0)
thor (0.14.6)
- tilt (1.3.2)
+ tilt (1.3.3)
PLATFORMS
ruby
DEPENDENCIES
capture_stdout
coffee-script
compass
escape_utils
foreman
pdfkit
rmagick
sass
- showoff
- sinatra (~> 1.2.6)
+ showoff!
+ sinatra
slim
thin
diff --git a/intro/00_intro.md b/intro/00_intro.md
index ac0d5c8..4dc06e0 100644
--- a/intro/00_intro.md
+++ b/intro/00_intro.md
@@ -1,23 +1,23 @@
!SLIDE title bullets
-# Smalltalk On Rubinius #
+# No Title #
* Konstantin Haase
!SLIDE center

!SLIDE center

!SLIDE center

!SLIDE center

!SLIDE center

!SLIDE center

|
rkh/presentations
|
55250c21ccae8906cac8c229226a9756f28d68c5
|
import intro slides from reak/realtime talk
|
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..a230dda
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,22 @@
+source :rubygems unless ENV['QUICK']
+
+group :slides do
+ gem 'showoff'
+ gem 'rmagick'
+ gem 'pdfkit'
+end
+
+group :demo do
+ gem 'thin'
+ gem 'sinatra', '~> 1.2.6'
+ gem 'escape_utils'
+ gem 'capture_stdout'
+ gem 'slim'
+ gem 'sass'
+ gem 'coffee-script'
+end
+
+group :development do
+ gem 'foreman'
+ gem 'compass'
+end
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..6010169
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,68 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ bluecloth (2.1.0)
+ capture_stdout (0.0.1)
+ chunky_png (1.2.0)
+ coffee-script (2.2.0)
+ coffee-script-source
+ execjs
+ coffee-script-source (1.1.1)
+ compass (0.11.5)
+ chunky_png (~> 1.2)
+ fssm (>= 0.2.7)
+ sass (~> 3.1)
+ daemons (1.1.4)
+ escape_utils (0.2.3)
+ eventmachine (0.12.10)
+ execjs (1.2.0)
+ multi_json (~> 1.0)
+ foreman (0.19.0)
+ term-ansicolor (~> 1.0.5)
+ thor (>= 0.13.6)
+ fssm (0.2.7)
+ gli (1.3.2)
+ json (1.5.3)
+ multi_json (1.0.3)
+ nokogiri (1.5.0)
+ pdfkit (0.5.2)
+ rack (1.3.0)
+ rmagick (2.13.1)
+ sass (3.1.4)
+ showoff (0.4.2)
+ bluecloth
+ gli (>= 1.2.5)
+ json
+ nokogiri
+ sinatra
+ sinatra (1.2.6)
+ rack (~> 1.1)
+ tilt (< 2.0, >= 1.2.2)
+ slim (0.9.4)
+ temple (~> 0.3.0)
+ tilt (~> 1.2)
+ temple (0.3.2)
+ term-ansicolor (1.0.5)
+ thin (1.2.11)
+ daemons (>= 1.0.9)
+ eventmachine (>= 0.12.6)
+ rack (>= 1.0.0)
+ thor (0.14.6)
+ tilt (1.3.2)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ capture_stdout
+ coffee-script
+ compass
+ escape_utils
+ foreman
+ pdfkit
+ rmagick
+ sass
+ showoff
+ sinatra (~> 1.2.6)
+ slim
+ thin
diff --git a/Procfile b/Procfile
new file mode 100644
index 0000000..8b3b32a
--- /dev/null
+++ b/Procfile
@@ -0,0 +1,2 @@
+web: bundle exec rackup -s thin -p $PORT
+sass: compass watch --sass-dir . --css-dir . --images-dir . --javascripts-dir .
diff --git a/README.md b/README.md
index cd5ee50..80610bd 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,6 @@
Every talk has its own branch. Check out the branch list.
+
+Run it:
+
+ bundle install
+ foreman start
diff --git a/config.ru b/config.ru
new file mode 100644
index 0000000..5ecb93c
--- /dev/null
+++ b/config.ru
@@ -0,0 +1,2 @@
+require 'showoff'
+run ShowOff
diff --git a/intro/00_intro.md b/intro/00_intro.md
index a1fd5f9..ac0d5c8 100644
--- a/intro/00_intro.md
+++ b/intro/00_intro.md
@@ -1,11 +1,23 @@
!SLIDE title bullets
-# will be replaced by title #
+# Smalltalk On Rubinius #
* Konstantin Haase
-!SLIDE bullets
-# Me #
+!SLIDE center
+
+
+!SLIDE center
+
+
+!SLIDE center
+
+
+!SLIDE center
+
+
+!SLIDE center
+
+
+!SLIDE center
+
-* [rkh.im](http://rkh.im/), [github/rkh](http://github.com/rkh), [@konstantinhaase](http://twitter.com/konstantinhaase)
-* Ruby dev at [Finnlabs](http://finn.de)
-* Sinatra, Rubinius, Rack
diff --git a/intro/almost-sinatra.png b/intro/almost-sinatra.png
new file mode 100644
index 0000000..17d2f29
Binary files /dev/null and b/intro/almost-sinatra.png differ
diff --git a/intro/engine_yard_logo.jpg b/intro/engine_yard_logo.jpg
new file mode 100644
index 0000000..d277b77
Binary files /dev/null and b/intro/engine_yard_logo.jpg differ
diff --git a/intro/finnlabs.png b/intro/finnlabs.png
new file mode 100644
index 0000000..66771a1
Binary files /dev/null and b/intro/finnlabs.png differ
diff --git a/intro/github.png b/intro/github.png
new file mode 100644
index 0000000..de70026
Binary files /dev/null and b/intro/github.png differ
diff --git a/intro/me.jpg b/intro/me.jpg
new file mode 100644
index 0000000..be81033
Binary files /dev/null and b/intro/me.jpg differ
diff --git a/intro/rack.png b/intro/rack.png
new file mode 100644
index 0000000..0c802d9
Binary files /dev/null and b/intro/rack.png differ
diff --git a/intro/rkh.png b/intro/rkh.png
new file mode 100644
index 0000000..d6e273f
Binary files /dev/null and b/intro/rkh.png differ
diff --git a/intro/rubinius.png b/intro/rubinius.png
new file mode 100644
index 0000000..5f8f2a6
Binary files /dev/null and b/intro/rubinius.png differ
diff --git a/intro/sinatra1.png b/intro/sinatra1.png
new file mode 100644
index 0000000..4c634e3
Binary files /dev/null and b/intro/sinatra1.png differ
diff --git a/intro/sinatra2.png b/intro/sinatra2.png
new file mode 100644
index 0000000..77dfd30
Binary files /dev/null and b/intro/sinatra2.png differ
diff --git a/talk.css b/talk.css
index 25b5a9e..315b1e8 100644
--- a/talk.css
+++ b/talk.css
@@ -1,85 +1,113 @@
-@charset "UTF-8";
/* line 4, talk.sass */
body {
- background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #aaaaaa), color-stop(80%, #eeeeee), color-stop(100%, #ffffff));
- background-image: -moz-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
- background-image: linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
+ background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #aaaaaa), color-stop(80%, #eeeeee), color-stop(100%, #ffffff));
+ background-image: -webkit-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff);
+ background-image: -moz-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff);
+ background-image: -o-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff);
+ background-image: -ms-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff);
+ background-image: linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff);
background-color: white;
background-repeat: no-repeat;
background-attachment: fixed;
}
/* line 11, talk.sass */
#preso {
- background-color: white !important;
- -moz-box-shadow: #888888 0px 0px 15px 0;
- -webkit-box-shadow: #888888 0px 0px 15px 0;
- -o-box-shadow: #888888 0px 0px 15px 0;
- box-shadow: #888888 0px 0px 15px 0;
+ background-color: white;
+ -moz-box-shadow: 0px 0px 15px #888888;
+ -webkit-box-shadow: 0px 0px 15px #888888;
+ -o-box-shadow: 0px 0px 15px #888888;
+ box-shadow: 0px 0px 15px #888888;
-moz-border-radius-bottomleft: 15px;
-webkit-border-bottom-left-radius: 15px;
-o-border-bottom-left-radius: 15px;
-ms-border-bottom-left-radius: 15px;
-khtml-border-bottom-left-radius: 15px;
border-bottom-left-radius: 15px;
-moz-border-radius-bottomright: 15px;
-webkit-border-bottom-right-radius: 15px;
-o-border-bottom-right-radius: 15px;
-ms-border-bottom-right-radius: 15px;
-khtml-border-bottom-right-radius: 15px;
border-bottom-right-radius: 15px;
}
/* line 16, talk.sass */
#footer {
- background-color: transparent !important;
+ background-color: transparent;
position: relative;
top: -20px;
z-index: 9999 !important;
}
/* line 21, talk.sass */
#footer #slideInfo {
padding: 0 15px;
font-size: 80%;
color: #aaaaaa;
}
/* line 26, talk.sass */
.slide {
- background-color: transparent !important;
+ background-color: transparent;
-moz-border-radius-bottomleft: 15px;
-webkit-border-bottom-left-radius: 15px;
-o-border-bottom-left-radius: 15px;
-ms-border-bottom-left-radius: 15px;
-khtml-border-bottom-left-radius: 15px;
border-bottom-left-radius: 15px;
-moz-border-radius-bottomright: 15px;
-webkit-border-bottom-right-radius: 15px;
-o-border-bottom-right-radius: 15px;
-ms-border-bottom-right-radius: 15px;
-khtml-border-bottom-right-radius: 15px;
border-bottom-right-radius: 15px;
}
/* line 30, talk.sass */
.slide .content h1 {
- font-family: "Chalkduster";
+ font-weight: bold;
}
-/* line 33, talk.sass */
+/* line 34, talk.sass */
.slide .content a:link, .slide .content a:visited {
text-decoration: none;
color: black;
border-bottom: 1px dotted black;
}
-/* line 37, talk.sass */
+/* line 38, talk.sass */
.slide .content a:hover {
color: #880000;
}
-/* line 41, talk.sass */
+/* line 42, talk.sass */
.slide .title h1, .slide .thanks h1 {
margin-top: 150px;
font-size: 9em;
}
-/* line 45, talk.sass */
+/* line 46, talk.sass */
.slide .small {
font-size: 50%;
}
+/* line 50, talk.sass */
+.slide .smallish {
+ font-size: 80%;
+}
+/* line 53, talk.sass */
+.slide .large {
+ font-size: 200%;
+}
+/* line 57, talk.sass */
+.slide .spaced .sh_smalltalk {
+ margin-bottom: 2em;
+}
+/* line 60, talk.sass */
+.slide [alt~=stack] {
+ position: absolute;
+ width: 249px;
+ height: 53px;
+ right: 5px;
+ top: 0;
+}
+/* line 67, talk.sass */
+.slide [alt~=working_code], .slide [alt~=pseudo_code] {
+ position: absolute;
+ right: 0;
+ top: 45px;
+}
diff --git a/talk.sass b/talk.sass
index 764ae41..1d46381 100644
--- a/talk.sass
+++ b/talk.sass
@@ -1,46 +1,70 @@
@import "compass/css3"
@import "compass/utilities"
body
+linear-gradient(color-stops(#aaa 20%, #eee 80%, #fff))
background:
color: #fff
repeat: no-repeat
attachment: fixed
#preso
- background-color: #fff !important
+ background-color: #fff
+box-shadow(#888, 0px, 0px, 15px)
+border-bottom-radius(15px)
#footer
- background-color: transparent !important
+ background-color: transparent
position: relative
top: -20px
z-index: 9999 !important
#slideInfo
padding: 0 15px
font-size: 80%
color: #aaa
.slide
- background-color: transparent !important
+ background-color: transparent
+border-bottom-radius(15px)
.content
h1
- font-family: "Chalkduster"
+ //font-family: "Chalkduster"
+ font-weight: bold
a
&:link, &:visited
text-decoration: none
color: #000
border-bottom: 1px dotted #000
&:hover
color: #800
.title, .thanks
h1
margin-top: 150px
font-size: 9em
.small
font-size: 50%
+
+
+ .smallish
+ font-size: 80%
+
+ .large
+ font-size: 200%
+
+ .spaced
+ .sh_smalltalk
+ margin-bottom: 2em
+
+ [alt~=stack]
+ position: absolute
+ width: 249px
+ height: 53px
+ right: 5px
+ top: 0
+
+ [alt~=working_code], [alt~=pseudo_code]
+ position: absolute
+ right: 0
+ top: 45px
|
rkh/presentations
|
40d6e07f857fb9b49490b2d58db809ab63f3ff6f
|
improve final slide
|
diff --git a/outro/00_thanks.md b/outro/00_thanks.md
index 80a5976..bb1ff75 100644
--- a/outro/00_thanks.md
+++ b/outro/00_thanks.md
@@ -1,2 +1,4 @@
-!SLIDE
-# Thanks! #
\ No newline at end of file
+!SLIDE bullets thanks
+# Thanks! #
+
+* [github.com / rkh / presentations](https://github.com/rkh/presentations)
\ No newline at end of file
diff --git a/talk.css b/talk.css
index a548e50..25b5a9e 100644
--- a/talk.css
+++ b/talk.css
@@ -1,85 +1,85 @@
@charset "UTF-8";
/* line 4, talk.sass */
body {
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #aaaaaa), color-stop(80%, #eeeeee), color-stop(100%, #ffffff));
background-image: -moz-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
background-image: linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
background-color: white;
background-repeat: no-repeat;
background-attachment: fixed;
}
/* line 11, talk.sass */
#preso {
background-color: white !important;
-moz-box-shadow: #888888 0px 0px 15px 0;
-webkit-box-shadow: #888888 0px 0px 15px 0;
-o-box-shadow: #888888 0px 0px 15px 0;
box-shadow: #888888 0px 0px 15px 0;
-moz-border-radius-bottomleft: 15px;
-webkit-border-bottom-left-radius: 15px;
-o-border-bottom-left-radius: 15px;
-ms-border-bottom-left-radius: 15px;
-khtml-border-bottom-left-radius: 15px;
border-bottom-left-radius: 15px;
-moz-border-radius-bottomright: 15px;
-webkit-border-bottom-right-radius: 15px;
-o-border-bottom-right-radius: 15px;
-ms-border-bottom-right-radius: 15px;
-khtml-border-bottom-right-radius: 15px;
border-bottom-right-radius: 15px;
}
/* line 16, talk.sass */
#footer {
background-color: transparent !important;
position: relative;
top: -20px;
z-index: 9999 !important;
}
/* line 21, talk.sass */
#footer #slideInfo {
padding: 0 15px;
font-size: 80%;
color: #aaaaaa;
}
/* line 26, talk.sass */
.slide {
background-color: transparent !important;
-moz-border-radius-bottomleft: 15px;
-webkit-border-bottom-left-radius: 15px;
-o-border-bottom-left-radius: 15px;
-ms-border-bottom-left-radius: 15px;
-khtml-border-bottom-left-radius: 15px;
border-bottom-left-radius: 15px;
-moz-border-radius-bottomright: 15px;
-webkit-border-bottom-right-radius: 15px;
-o-border-bottom-right-radius: 15px;
-ms-border-bottom-right-radius: 15px;
-khtml-border-bottom-right-radius: 15px;
border-bottom-right-radius: 15px;
}
/* line 30, talk.sass */
.slide .content h1 {
font-family: "Chalkduster";
}
/* line 33, talk.sass */
.slide .content a:link, .slide .content a:visited {
text-decoration: none;
color: black;
border-bottom: 1px dotted black;
}
/* line 37, talk.sass */
.slide .content a:hover {
color: #880000;
}
-/* line 40, talk.sass */
-.slide .title h1 {
+/* line 41, talk.sass */
+.slide .title h1, .slide .thanks h1 {
margin-top: 150px;
font-size: 9em;
}
-/* line 44, talk.sass */
+/* line 45, talk.sass */
.slide .small {
font-size: 50%;
}
diff --git a/talk.sass b/talk.sass
index 503915f..764ae41 100644
--- a/talk.sass
+++ b/talk.sass
@@ -1,45 +1,46 @@
@import "compass/css3"
@import "compass/utilities"
body
+linear-gradient(color-stops(#aaa 20%, #eee 80%, #fff))
background:
color: #fff
repeat: no-repeat
attachment: fixed
#preso
background-color: #fff !important
+box-shadow(#888, 0px, 0px, 15px)
+border-bottom-radius(15px)
#footer
background-color: transparent !important
position: relative
top: -20px
z-index: 9999 !important
#slideInfo
padding: 0 15px
font-size: 80%
color: #aaa
.slide
background-color: transparent !important
+border-bottom-radius(15px)
.content
h1
font-family: "Chalkduster"
a
&:link, &:visited
text-decoration: none
color: #000
border-bottom: 1px dotted #000
&:hover
color: #800
- .title h1
- margin-top: 150px
- font-size: 9em
+ .title, .thanks
+ h1
+ margin-top: 150px
+ font-size: 9em
.small
font-size: 50%
|
rkh/presentations
|
e6a84a8bbccf634691f62f4017d6b0119e63338f
|
add small font slides
|
diff --git a/talk.css b/talk.css
index 75250ea..a548e50 100644
--- a/talk.css
+++ b/talk.css
@@ -1,81 +1,85 @@
@charset "UTF-8";
/* line 4, talk.sass */
body {
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #aaaaaa), color-stop(80%, #eeeeee), color-stop(100%, #ffffff));
background-image: -moz-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
background-image: linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
background-color: white;
background-repeat: no-repeat;
background-attachment: fixed;
}
/* line 11, talk.sass */
#preso {
background-color: white !important;
-moz-box-shadow: #888888 0px 0px 15px 0;
-webkit-box-shadow: #888888 0px 0px 15px 0;
-o-box-shadow: #888888 0px 0px 15px 0;
box-shadow: #888888 0px 0px 15px 0;
-moz-border-radius-bottomleft: 15px;
-webkit-border-bottom-left-radius: 15px;
-o-border-bottom-left-radius: 15px;
-ms-border-bottom-left-radius: 15px;
-khtml-border-bottom-left-radius: 15px;
border-bottom-left-radius: 15px;
-moz-border-radius-bottomright: 15px;
-webkit-border-bottom-right-radius: 15px;
-o-border-bottom-right-radius: 15px;
-ms-border-bottom-right-radius: 15px;
-khtml-border-bottom-right-radius: 15px;
border-bottom-right-radius: 15px;
}
/* line 16, talk.sass */
#footer {
background-color: transparent !important;
position: relative;
top: -20px;
z-index: 9999 !important;
}
/* line 21, talk.sass */
#footer #slideInfo {
padding: 0 15px;
font-size: 80%;
color: #aaaaaa;
}
/* line 26, talk.sass */
.slide {
background-color: transparent !important;
-moz-border-radius-bottomleft: 15px;
-webkit-border-bottom-left-radius: 15px;
-o-border-bottom-left-radius: 15px;
-ms-border-bottom-left-radius: 15px;
-khtml-border-bottom-left-radius: 15px;
border-bottom-left-radius: 15px;
-moz-border-radius-bottomright: 15px;
-webkit-border-bottom-right-radius: 15px;
-o-border-bottom-right-radius: 15px;
-ms-border-bottom-right-radius: 15px;
-khtml-border-bottom-right-radius: 15px;
border-bottom-right-radius: 15px;
}
/* line 30, talk.sass */
.slide .content h1 {
font-family: "Chalkduster";
}
/* line 33, talk.sass */
.slide .content a:link, .slide .content a:visited {
text-decoration: none;
color: black;
border-bottom: 1px dotted black;
}
/* line 37, talk.sass */
.slide .content a:hover {
color: #880000;
}
/* line 40, talk.sass */
.slide .title h1 {
margin-top: 150px;
font-size: 9em;
}
+/* line 44, talk.sass */
+.slide .small {
+ font-size: 50%;
+}
diff --git a/talk.sass b/talk.sass
index 4d4d9df..503915f 100644
--- a/talk.sass
+++ b/talk.sass
@@ -1,42 +1,45 @@
@import "compass/css3"
@import "compass/utilities"
body
+linear-gradient(color-stops(#aaa 20%, #eee 80%, #fff))
background:
color: #fff
repeat: no-repeat
attachment: fixed
#preso
background-color: #fff !important
+box-shadow(#888, 0px, 0px, 15px)
+border-bottom-radius(15px)
#footer
background-color: transparent !important
position: relative
top: -20px
z-index: 9999 !important
#slideInfo
padding: 0 15px
font-size: 80%
color: #aaa
.slide
background-color: transparent !important
+border-bottom-radius(15px)
.content
h1
font-family: "Chalkduster"
a
&:link, &:visited
text-decoration: none
color: #000
border-bottom: 1px dotted #000
&:hover
color: #800
.title h1
margin-top: 150px
font-size: 9em
+
+ .small
+ font-size: 50%
|
rkh/presentations
|
a218d7fd0200b8c0c1df3d82e75a6b8772605f72
|
fix border radius issue in webkit
|
diff --git a/talk.css b/talk.css
index df92809..75250ea 100644
--- a/talk.css
+++ b/talk.css
@@ -1,65 +1,81 @@
@charset "UTF-8";
/* line 4, talk.sass */
body {
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #aaaaaa), color-stop(80%, #eeeeee), color-stop(100%, #ffffff));
background-image: -moz-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
background-image: linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
background-color: white;
background-repeat: no-repeat;
background-attachment: fixed;
}
/* line 11, talk.sass */
#preso {
- background-color: transparent !important;
+ background-color: white !important;
-moz-box-shadow: #888888 0px 0px 15px 0;
-webkit-box-shadow: #888888 0px 0px 15px 0;
-o-box-shadow: #888888 0px 0px 15px 0;
box-shadow: #888888 0px 0px 15px 0;
-moz-border-radius-bottomleft: 15px;
-webkit-border-bottom-left-radius: 15px;
-o-border-bottom-left-radius: 15px;
-ms-border-bottom-left-radius: 15px;
-khtml-border-bottom-left-radius: 15px;
border-bottom-left-radius: 15px;
-moz-border-radius-bottomright: 15px;
-webkit-border-bottom-right-radius: 15px;
-o-border-bottom-right-radius: 15px;
-ms-border-bottom-right-radius: 15px;
-khtml-border-bottom-right-radius: 15px;
border-bottom-right-radius: 15px;
}
/* line 16, talk.sass */
#footer {
background-color: transparent !important;
position: relative;
top: -20px;
z-index: 9999 !important;
}
/* line 21, talk.sass */
#footer #slideInfo {
padding: 0 15px;
font-size: 80%;
color: #aaaaaa;
}
-/* line 28, talk.sass */
+/* line 26, talk.sass */
+.slide {
+ background-color: transparent !important;
+ -moz-border-radius-bottomleft: 15px;
+ -webkit-border-bottom-left-radius: 15px;
+ -o-border-bottom-left-radius: 15px;
+ -ms-border-bottom-left-radius: 15px;
+ -khtml-border-bottom-left-radius: 15px;
+ border-bottom-left-radius: 15px;
+ -moz-border-radius-bottomright: 15px;
+ -webkit-border-bottom-right-radius: 15px;
+ -o-border-bottom-right-radius: 15px;
+ -ms-border-bottom-right-radius: 15px;
+ -khtml-border-bottom-right-radius: 15px;
+ border-bottom-right-radius: 15px;
+}
+/* line 30, talk.sass */
.slide .content h1 {
font-family: "Chalkduster";
}
-/* line 31, talk.sass */
+/* line 33, talk.sass */
.slide .content a:link, .slide .content a:visited {
text-decoration: none;
color: black;
border-bottom: 1px dotted black;
}
-/* line 35, talk.sass */
+/* line 37, talk.sass */
.slide .content a:hover {
color: #880000;
}
-/* line 38, talk.sass */
+/* line 40, talk.sass */
.slide .title h1 {
margin-top: 150px;
font-size: 9em;
}
diff --git a/talk.sass b/talk.sass
index 05aedaf..4d4d9df 100644
--- a/talk.sass
+++ b/talk.sass
@@ -1,40 +1,42 @@
@import "compass/css3"
@import "compass/utilities"
body
+linear-gradient(color-stops(#aaa 20%, #eee 80%, #fff))
background:
color: #fff
repeat: no-repeat
attachment: fixed
#preso
- background-color: transparent !important
+ background-color: #fff !important
+box-shadow(#888, 0px, 0px, 15px)
+border-bottom-radius(15px)
#footer
background-color: transparent !important
position: relative
top: -20px
z-index: 9999 !important
#slideInfo
padding: 0 15px
font-size: 80%
color: #aaa
.slide
+ background-color: transparent !important
+ +border-bottom-radius(15px)
.content
h1
font-family: "Chalkduster"
a
&:link, &:visited
text-decoration: none
color: #000
border-bottom: 1px dotted #000
&:hover
color: #800
-
+
.title h1
margin-top: 150px
font-size: 9em
|
rkh/presentations
|
dc90e3b4cdf18a40c16374521fd495a82df7e742
|
skeleton for future presentations
|
diff --git a/intro/00_intro.md b/intro/00_intro.md
new file mode 100644
index 0000000..a1fd5f9
--- /dev/null
+++ b/intro/00_intro.md
@@ -0,0 +1,11 @@
+!SLIDE title bullets
+# will be replaced by title #
+
+* Konstantin Haase
+
+!SLIDE bullets
+# Me #
+
+* [rkh.im](http://rkh.im/), [github/rkh](http://github.com/rkh), [@konstantinhaase](http://twitter.com/konstantinhaase)
+* Ruby dev at [Finnlabs](http://finn.de)
+* Sinatra, Rubinius, Rack
diff --git a/outro/00_thanks.md b/outro/00_thanks.md
new file mode 100644
index 0000000..80a5976
--- /dev/null
+++ b/outro/00_thanks.md
@@ -0,0 +1,2 @@
+!SLIDE
+# Thanks! #
\ No newline at end of file
diff --git a/showoff.json b/showoff.json
index 51d4d12..52d8d82 100644
--- a/showoff.json
+++ b/showoff.json
@@ -1 +1,8 @@
-{ "name": "No Title", "sections": [ {"section":"slides"} ]}
+{
+ "name": "No Title",
+ "sections": [
+ { "section": "intro" },
+ { "section": "slides" },
+ { "section": "outro" }
+ ]
+}
diff --git a/slides/.gitignore b/slides/.gitignore
new file mode 100644
index 0000000..e69de29
diff --git a/slides/00_intro.md b/slides/00_intro.md
deleted file mode 100644
index 69f9c62..0000000
--- a/slides/00_intro.md
+++ /dev/null
@@ -1,2 +0,0 @@
-!SLIDE title
-# will be replaced by title #
\ No newline at end of file
diff --git a/talk.coffee b/talk.coffee
index 33d15b4..5a8f9f8 100644
--- a/talk.coffee
+++ b/talk.coffee
@@ -1,3 +1,4 @@
# replace generic title in title slide with actual title of the talk
-$('.title').live "showoff:show", (e) -> $(e.target).find("h1").text document.title
+$('.title').live "showoff:show", (e) ->
+ $(e.target).find("h1").text document.title
diff --git a/talk.css b/talk.css
index e69de29..df92809 100644
--- a/talk.css
+++ b/talk.css
@@ -0,0 +1,65 @@
+@charset "UTF-8";
+/* line 4, talk.sass */
+body {
+ background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #aaaaaa), color-stop(80%, #eeeeee), color-stop(100%, #ffffff));
+ background-image: -moz-linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
+ background-image: linear-gradient(top, #aaaaaa 20%, #eeeeee 80%, #ffffff 100%);
+ background-color: white;
+ background-repeat: no-repeat;
+ background-attachment: fixed;
+}
+
+/* line 11, talk.sass */
+#preso {
+ background-color: transparent !important;
+ -moz-box-shadow: #888888 0px 0px 15px 0;
+ -webkit-box-shadow: #888888 0px 0px 15px 0;
+ -o-box-shadow: #888888 0px 0px 15px 0;
+ box-shadow: #888888 0px 0px 15px 0;
+ -moz-border-radius-bottomleft: 15px;
+ -webkit-border-bottom-left-radius: 15px;
+ -o-border-bottom-left-radius: 15px;
+ -ms-border-bottom-left-radius: 15px;
+ -khtml-border-bottom-left-radius: 15px;
+ border-bottom-left-radius: 15px;
+ -moz-border-radius-bottomright: 15px;
+ -webkit-border-bottom-right-radius: 15px;
+ -o-border-bottom-right-radius: 15px;
+ -ms-border-bottom-right-radius: 15px;
+ -khtml-border-bottom-right-radius: 15px;
+ border-bottom-right-radius: 15px;
+}
+
+/* line 16, talk.sass */
+#footer {
+ background-color: transparent !important;
+ position: relative;
+ top: -20px;
+ z-index: 9999 !important;
+}
+/* line 21, talk.sass */
+#footer #slideInfo {
+ padding: 0 15px;
+ font-size: 80%;
+ color: #aaaaaa;
+}
+
+/* line 28, talk.sass */
+.slide .content h1 {
+ font-family: "Chalkduster";
+}
+/* line 31, talk.sass */
+.slide .content a:link, .slide .content a:visited {
+ text-decoration: none;
+ color: black;
+ border-bottom: 1px dotted black;
+}
+/* line 35, talk.sass */
+.slide .content a:hover {
+ color: #880000;
+}
+/* line 38, talk.sass */
+.slide .title h1 {
+ margin-top: 150px;
+ font-size: 9em;
+}
diff --git a/talk.sass b/talk.sass
index fddbfe3..05aedaf 100644
--- a/talk.sass
+++ b/talk.sass
@@ -1 +1,40 @@
+@import "compass/css3"
+@import "compass/utilities"
+
+body
+ +linear-gradient(color-stops(#aaa 20%, #eee 80%, #fff))
+ background:
+ color: #fff
+ repeat: no-repeat
+ attachment: fixed
+
+#preso
+ background-color: transparent !important
+ +box-shadow(#888, 0px, 0px, 15px)
+ +border-bottom-radius(15px)
+
+#footer
+ background-color: transparent !important
+ position: relative
+ top: -20px
+ z-index: 9999 !important
+ #slideInfo
+ padding: 0 15px
+ font-size: 80%
+ color: #aaa
+
.slide
+ .content
+ h1
+ font-family: "Chalkduster"
+ a
+ &:link, &:visited
+ text-decoration: none
+ color: #000
+ border-bottom: 1px dotted #000
+ &:hover
+ color: #800
+
+ .title h1
+ margin-top: 150px
+ font-size: 9em
|
rkh/presentations
|
47d09889ce4ec6a56e79d3ce903d04258ace7f99
|
also track generated css
|
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index e84e55e..0000000
--- a/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-talk.css
diff --git a/talk.css b/talk.css
new file mode 100644
index 0000000..e69de29
|
rkh/presentations
|
f446ae68cf81be83c43b7e3b10ffcbdf317df6e5
|
become generic
|
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..cd5ee50
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
+Every talk has its own branch. Check out the branch list.
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..5c813a3
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,4 @@
+task :default do
+ fork { exec 'watchr talk.watchr' }
+ exec 'showoff serve'
+end
diff --git a/showoff.json b/showoff.json
index 36744f6..51d4d12 100644
--- a/showoff.json
+++ b/showoff.json
@@ -1 +1 @@
-{ "name": "Live Code Reloading", "sections": [ {"section":"slides"} ]}
+{ "name": "No Title", "sections": [ {"section":"slides"} ]}
diff --git a/slides/00_intro.md b/slides/00_intro.md
new file mode 100644
index 0000000..69f9c62
--- /dev/null
+++ b/slides/00_intro.md
@@ -0,0 +1,2 @@
+!SLIDE title
+# will be replaced by title #
\ No newline at end of file
diff --git a/slides/00_introduction.md b/slides/00_introduction.md
deleted file mode 100644
index b004385..0000000
--- a/slides/00_introduction.md
+++ /dev/null
@@ -1,19 +0,0 @@
-!SLIDE
-# Live Code Reloading #
-
-!SLIDE bullets incremental
-# Me #
-
-* [rkh.im](http://rkh.im/), [github/rkh](http://github.com/rkh), [@konstantinhaase](http://twitter.com/konstantinhaase)
-* Ruby dev at [Finnlabs](http://finn.de)
-* Rubinius, Sinatra, Rack, ... Rails?
-
-!SLIDE
-
-
-!SLIDE bullets incremental
-# ActiveSupport::Dependencies #
-
-* `Expected some_module.rb to define SomeModule!`
-* `A copy of SomeModule has been removed from the module tree but is still active!`
-* `SomeModule is not missing constant SomeConstant!`
\ No newline at end of file
diff --git a/slides/01_autoloading.md b/slides/01_autoloading.md
deleted file mode 100644
index 04ddc26..0000000
--- a/slides/01_autoloading.md
+++ /dev/null
@@ -1,30 +0,0 @@
-!SLIDE
-# Autoloading Constants #
-
-!SLIDE
- @@@ruby
- require 'my_autoloader'
-
- # require 'foo'
- foo = Foo.new
-
- # require 'foo_bar/blah'
- bar = FooBar::Blah.new
-
-!SLIDE
- @@@ ruby
- class Module
- alias const_missing_without_autoloading \
- const_missing
-
- def const_missing(const)
- path = "#{name.gsub('::', '/')}/#{const}"
- path.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
- require path.downcase
- const_defined?(const) ?
- const_get(const) : super
- rescue LoadError => error
- warn(error.message)
- super
- end
- end
\ No newline at end of file
diff --git a/slides/02_reloading_intro.md b/slides/02_reloading_intro.md
deleted file mode 100644
index efaad03..0000000
--- a/slides/02_reloading_intro.md
+++ /dev/null
@@ -1,20 +0,0 @@
-!SLIDE bullets incremental
-# Reloading constants #
-* When?
-* What?
-* How?
-
-!SLIDE bullets incremental
-# When? #
-* After every request.
-* If a file changed.
-* After a request, if a file changed.
-
-!SLIDE bullets incremental
-# What? #
-* The files that changed.
-* Every file.
-* Some files.
-
-!SLIDE
-# How? #
diff --git a/slides/03_restarting.md b/slides/03_restarting.md
deleted file mode 100644
index 9139474..0000000
--- a/slides/03_restarting.md
+++ /dev/null
@@ -1,15 +0,0 @@
-!SLIDE bullets incremental
-# Restart your application! #
-* Shotgun
-* rerun
-* "Magical Reloading Sparkles"
-
-!SLIDE bullets incremental
-# Advantages #
-* Correct
-* COW friendly
-
-!SLIDE bullets incremental
-# Disadvantages #
-* Slow
-* No Windows/JRuby support
\ No newline at end of file
diff --git a/slides/04_open_classes.md b/slides/04_open_classes.md
deleted file mode 100644
index d7403a3..0000000
--- a/slides/04_open_classes.md
+++ /dev/null
@@ -1,101 +0,0 @@
-!SLIDE bullets incremental
-# Rely On Open Classes #
-* Rack::Reloader
-* Sinatra::Reloader
-
-!SLIDE
- @@@ ruby
- # Foo = Class.new { ... }
- class Foo
- def self.bar(x) x + 1 end
- bar(2) # => 3
- end
-
- # Foo.class_eval { ... }
- class Foo
- def self.bar(x) x + 2 end
- bar(2) # => 4
- end
-
-!SLIDE
- @@@ ruby
- # config.ru
- use(Rack::Config) { load './foo.rb' }
- run Foo
-
-!SLIDE
- @@@ ruby
- # config.ru
- mtime, file = Time.at(0), './foo.rb'
-
- use Rack::Config do
- next if File.mtime(file) == mtime
- mtime = File.mtime(file)
- load file
- end
-
- run Foo
-
-!SLIDE
- @@@ ruby
- # config.ru
- require 'foo'
- use Rack::Reloader
- run Foo
-
-!SLIDE bullets incremental
-# Advantages #
-* Fast
-* Able to reload single files
-
-!SLIDE
-# Disadvantages #
-
-!SLIDE
- @@@ ruby
- class Array
- alias original_to_s to_s
- def to_s
- original_to_s.upcase
- end
- end
-
- # reload...
-
- class Array
- alias original_to_s to_s
- def to_s
- original_to_s.downcase
- end
- end
-
- [:foo].to_s
-
-!SLIDE bullets
-* `SystemStackError: stack level too deep`
-
-!SLIDE
- @@@ ruby
- class Foo
- def self.bar() end
- end
-
- # reload...
-
- class Foo
- def self.foo() end
- end
-
- Foo.respond_to? :bar # => true
-
-!SLIDE
- @@@ ruby
- class Foo < ActiveResource::Base
- end
-
- # reload...
-
- class Foo < ActiveRecord::Base
- # TypeError: superclass mismatch
- # for class Foo
- end
diff --git a/slides/05_remove_const.md b/slides/05_remove_const.md
deleted file mode 100644
index 06f960d..0000000
--- a/slides/05_remove_const.md
+++ /dev/null
@@ -1,46 +0,0 @@
-!SLIDE bullets incremental
-# Removing constants #
-* ActiveSupport::Dependencies
-* Merb::BootLoader::LoadClasses
-* Padrino::Reloader
-
-!SLIDE
- @@@ ruby
- # config.ru
- use(Rack::Config) do
- if Object.const_defined?(:Foo)
- Object.send(:remove_const, :Foo)
- end
-
- load './foo.rb'
- end
-
- # `run Foo` would not pick up the new Foo
- run proc { |env| Foo.call(env) }
-
-!SLIDE
- @@@ ruby
- class Foo; end
- foo = Foo.new
-
- Object.send(:remove_const, :Foo)
- class Foo; end
- foo.is_a? Foo # => false
-
-!SLIDE bullets incremental
-# ActiveSupport::Dependencies #
-* Autoloaded, unloadable and un-unloadable constant pools
-* `autoload_paths`, `autoload_once_paths`, `mechanism`
-* `history`, `loaded`, `autoloaded_constants`, `explicitly_unloadable_constants`, `references`, `constant_watch_stack`
-
-!SLIDE bullets incremental
-# ActiveSupport::Dependencies, reloaded #
-* Constant Wrapper
-* Strategies
-* Check for file changes (optional)
-
-!SLIDE bullets incremental
-# Strategies #
-* Global Reloader (default)
-* Monkey Patching Reloader
-* Sloppy Reloader
diff --git a/slides/06_end.md b/slides/06_end.md
deleted file mode 100644
index 46ff0f9..0000000
--- a/slides/06_end.md
+++ /dev/null
@@ -1,5 +0,0 @@
-!SLIDE bullets
-# Thanks! #
-* Code: [github/rkh/rails](http://github.com/rkh/rails)
-* Benchmarks: [github/rkh/reloader-shootout](http://github.com/rkh/rails)
-* Blog post: [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
\ No newline at end of file
diff --git a/slides/rsoc.png b/slides/rsoc.png
deleted file mode 100644
index 6effa21..0000000
Binary files a/slides/rsoc.png and /dev/null differ
diff --git a/talk.coffee b/talk.coffee
new file mode 100644
index 0000000..33d15b4
--- /dev/null
+++ b/talk.coffee
@@ -0,0 +1,3 @@
+# replace generic title in title slide with actual title of the talk
+$('.title').live "showoff:show", (e) -> $(e.target).find("h1").text document.title
+
diff --git a/talk.js b/talk.js
new file mode 100644
index 0000000..3f80dd5
--- /dev/null
+++ b/talk.js
@@ -0,0 +1,5 @@
+(function() {
+ $('.title').live("showoff:show", function(e) {
+ return $(e.target).find("h1").text(document.title);
+ });
+})();
diff --git a/talk.sass b/talk.sass
index f40c390..fddbfe3 100644
--- a/talk.sass
+++ b/talk.sass
@@ -1,34 +1 @@
-@import "compass/css3"
-@import "compass/utilities"
-
-.content
- a
- &:link, &:visited
- text-decoration: none
- color: #000
- border-bottom: 1px dotted #000
-
-body
- +linear-gradient(color-stops(#eff5ff 20%, #f3ffff 80%, #fff))
- background:
- color: #fff
- repeat: no-repeat
- attachment: fixed
- #preso
- background-color: transparent !important
- margin-top: 50px !important
- width: 1050px !important
- .slide
- width: 1050px !important
- +border-radius(50px)
- img
- margin-left: 13px
- #footer
- background-color: transparent !important
- #slideInfo
- position: absolute
- top: 5px
- right: 20px
- color: #abd
- text-align: right
- z-index: 9999 !important
+.slide
|
rkh/presentations
|
9efb6331bc2abcd98bcc288ce39b59902dc7017a
|
move to top level
|
diff --git a/.gitignore b/.gitignore
index 694c642..e84e55e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1 @@
-rsoc2010-rugb/talk.css
+talk.css
diff --git a/rubyconf2010/showoff.json b/rubyconf2010/showoff.json
deleted file mode 100644
index 36744f6..0000000
--- a/rubyconf2010/showoff.json
+++ /dev/null
@@ -1 +0,0 @@
-{ "name": "Live Code Reloading", "sections": [ {"section":"slides"} ]}
diff --git a/rubyconf2010/slides/01_reloading.md b/rubyconf2010/slides/01_reloading.md
deleted file mode 100644
index bda4b61..0000000
--- a/rubyconf2010/slides/01_reloading.md
+++ /dev/null
@@ -1,73 +0,0 @@
-!SLIDE bullets
-
-# Live Code Reloading #
-
-* (aka reworking ActiveSupport::Dependencies)
-
-!SLIDE
-# What changed? #
-
-!SLIDE
-
-# Internal Architecture #
-
- @@@ ruby
- module ActiveSupport::Dependencies
- Constant["Foo"].active?
- Constant["Bar"].activate
- end
-
-!SLIDE bullets incremental
-
-# Battle Testing #
-
-* Old constant references become delegates
-* Better constant definition tracking
-* Instance invalidation
-* `$LOADED_FEATURES` aware
-* dependency tracking (`require_dependency`)
-
-!SLIDE bullets incremental
-
-# Come again? #
-
-* No more "Foo is not missing Bar"
-* (Nearly) no more "Already activated constant Blah"
-* Less unintentional behavior
-* `require` doesn't screw things up
-* No more "Where did my patch go?"
-
-!SLIDE bullets
-# Only reload on file changes #
-
-* (optional)
-
-!SLIDE
-# Pluggable Reloading Strategies #
-
- @@@ ruby
- module SinatraReloading
- def invalidate_remains; end
-
- def file
- constant.app_file
- end
-
- def prepare
- activate
- constant.reset!
- end
- end
-
-!SLIDE bullets incremental
-
-* World reloading (default)
-* Sloppy reloading (don't use)
-* <s style="color: #888">Monkey</s> Freedom Patching strategy
-
-!SLIDE bullets
-# Thanks! #
-
-* Code: [github/rkh/rails](http://github.com/rkh/rails)
-* Benchmarks: [github/rkh/reloader-shootout](http://github.com/rkh/rails)
-* Blog post: [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
\ No newline at end of file
diff --git a/rubyconf2010/talk.css b/rubyconf2010/talk.css
deleted file mode 100644
index 196002a..0000000
--- a/rubyconf2010/talk.css
+++ /dev/null
@@ -1,49 +0,0 @@
-/* line 6, talk.sass */
-.content a:link, .content a:visited {
- text-decoration: none;
- color: black;
- border-bottom: 1px dotted black;
-}
-
-/* line 11, talk.sass */
-body {
- background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #eff5ff), color-stop(80%, #f3ffff), color-stop(100%, #ffffff));
- background-image: -moz-linear-gradient(top, #eff5ff 20%, #f3ffff 80%, #ffffff 100%);
- background-image: linear-gradient(top, #eff5ff 20%, #f3ffff 80%, #ffffff 100%);
- background-color: white;
- background-repeat: no-repeat;
- background-attachment: fixed;
-}
-/* line 17, talk.sass */
-body #preso {
- background-color: transparent !important;
- margin-top: 50px !important;
- width: 1050px !important;
-}
-/* line 21, talk.sass */
-body #preso .slide {
- width: 1050px !important;
- -moz-border-radius: 50px;
- -webkit-border-radius: 50px;
- -o-border-radius: 50px;
- -ms-border-radius: 50px;
- -khtml-border-radius: 50px;
- border-radius: 50px;
-}
-/* line 24, talk.sass */
-body #preso .slide img {
- margin-left: 13px;
-}
-/* line 26, talk.sass */
-body #footer {
- background-color: transparent !important;
-}
-/* line 28, talk.sass */
-body #footer #slideInfo {
- position: absolute;
- top: 5px;
- right: 20px;
- color: #aabbdd;
- text-align: right;
- z-index: 9999 !important;
-}
diff --git a/rsoc2010-rugb/showoff.json b/showoff.json
similarity index 100%
rename from rsoc2010-rugb/showoff.json
rename to showoff.json
diff --git a/rsoc2010-rugb/slides/00_introduction.md b/slides/00_introduction.md
similarity index 100%
rename from rsoc2010-rugb/slides/00_introduction.md
rename to slides/00_introduction.md
diff --git a/rsoc2010-rugb/slides/01_autoloading.md b/slides/01_autoloading.md
similarity index 100%
rename from rsoc2010-rugb/slides/01_autoloading.md
rename to slides/01_autoloading.md
diff --git a/rsoc2010-rugb/slides/02_reloading_intro.md b/slides/02_reloading_intro.md
similarity index 100%
rename from rsoc2010-rugb/slides/02_reloading_intro.md
rename to slides/02_reloading_intro.md
diff --git a/rsoc2010-rugb/slides/03_restarting.md b/slides/03_restarting.md
similarity index 100%
rename from rsoc2010-rugb/slides/03_restarting.md
rename to slides/03_restarting.md
diff --git a/rsoc2010-rugb/slides/04_open_classes.md b/slides/04_open_classes.md
similarity index 100%
rename from rsoc2010-rugb/slides/04_open_classes.md
rename to slides/04_open_classes.md
diff --git a/rsoc2010-rugb/slides/05_remove_const.md b/slides/05_remove_const.md
similarity index 100%
rename from rsoc2010-rugb/slides/05_remove_const.md
rename to slides/05_remove_const.md
diff --git a/rsoc2010-rugb/slides/06_end.md b/slides/06_end.md
similarity index 100%
rename from rsoc2010-rugb/slides/06_end.md
rename to slides/06_end.md
diff --git a/rsoc2010-rugb/slides/rsoc.png b/slides/rsoc.png
similarity index 100%
rename from rsoc2010-rugb/slides/rsoc.png
rename to slides/rsoc.png
diff --git a/rsoc2010-rugb/talk.sass b/talk.sass
similarity index 100%
rename from rsoc2010-rugb/talk.sass
rename to talk.sass
diff --git a/rsoc2010-rugb/talk.watchr b/talk.watchr
similarity index 100%
rename from rsoc2010-rugb/talk.watchr
rename to talk.watchr
|
rkh/presentations
|
2fd52d3f0508c69abec15f626ab682168ece5616
|
reduce slides
|
diff --git a/rubyconf2010/slides/00_introduction.md b/rubyconf2010/slides/00_introduction.md
deleted file mode 100644
index b97a74c..0000000
--- a/rubyconf2010/slides/00_introduction.md
+++ /dev/null
@@ -1,10 +0,0 @@
-!SLIDE
-# Live Code Reloading #
-
-!SLIDE bullets
-# Me #
-
-* [rkh.im](http://rkh.im/), [github/rkh](http://github.com/rkh), [@konstantinhaase](http://twitter.com/konstantinhaase)
-* Sinatra, Rubinius, Rack
-* Student at Hasso Plattner Institute, Potsdam (Germany)
-* Ruby dev at [Finnlabs](http://finn.de), Berlin
\ No newline at end of file
diff --git a/rubyconf2010/slides/01_reloading.md b/rubyconf2010/slides/01_reloading.md
index ca63f5e..bda4b61 100644
--- a/rubyconf2010/slides/01_reloading.md
+++ b/rubyconf2010/slides/01_reloading.md
@@ -1,82 +1,73 @@
!SLIDE bullets
# Live Code Reloading #
* (aka reworking ActiveSupport::Dependencies)
-!SLIDE bullets incremental
-
-# Reloading Crash Course #
-
-* self-patching constants
-* actually restart your app
-* remove constant, reload file
-* [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
-
!SLIDE
# What changed? #
!SLIDE
# Internal Architecture #
@@@ ruby
module ActiveSupport::Dependencies
Constant["Foo"].active?
Constant["Bar"].activate
end
!SLIDE bullets incremental
# Battle Testing #
* Old constant references become delegates
* Better constant definition tracking
* Instance invalidation
* `$LOADED_FEATURES` aware
* dependency tracking (`require_dependency`)
!SLIDE bullets incremental
# Come again? #
* No more "Foo is not missing Bar"
* (Nearly) no more "Already activated constant Blah"
* Less unintentional behavior
* `require` doesn't screw things up
* No more "Where did my patch go?"
-!SLIDE bullets incremental
+!SLIDE bullets
# Only reload on file changes #
* (optional)
!SLIDE
# Pluggable Reloading Strategies #
@@@ ruby
module SinatraReloading
def invalidate_remains; end
def file
constant.app_file
end
def prepare
activate
constant.reset!
end
end
!SLIDE bullets incremental
* World reloading (default)
* Sloppy reloading (don't use)
* <s style="color: #888">Monkey</s> Freedom Patching strategy
!SLIDE bullets
# Thanks! #
* Code: [github/rkh/rails](http://github.com/rkh/rails)
* Benchmarks: [github/rkh/reloader-shootout](http://github.com/rkh/rails)
* Blog post: [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
\ No newline at end of file
|
rkh/presentations
|
747fb377639588a024744ad127e80ef78557c4b6
|
less slides
|
diff --git a/rubyconf2010/slides/01_reloading.md b/rubyconf2010/slides/01_reloading.md
index d6082ac..ca63f5e 100644
--- a/rubyconf2010/slides/01_reloading.md
+++ b/rubyconf2010/slides/01_reloading.md
@@ -1,104 +1,82 @@
+!SLIDE bullets
+
+# Live Code Reloading #
+
+* (aka reworking ActiveSupport::Dependencies)
+
!SLIDE bullets incremental
# Reloading Crash Course #
* self-patching constants
* actually restart your app
* remove constant, reload file
* [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
!SLIDE
# What changed? #
!SLIDE
# Internal Architecture #
-!SLIDE
@@@ ruby
module ActiveSupport::Dependencies
Constant["Foo"].active?
Constant["Bar"].activate
end
-!SLIDE
+!SLIDE bullets incremental
# Battle Testing #
-!SLIDE bullets incremental
-
* Old constant references become delegates
* Better constant definition tracking
* Instance invalidation
* `$LOADED_FEATURES` aware
+* dependency tracking (`require_dependency`)
-!SLIDE
+!SLIDE bullets incremental
# Come again? #
-!SLIDE bullets incremental
-
* No more "Foo is not missing Bar"
* (Nearly) no more "Already activated constant Blah"
* Less unintentional behavior
* `require` doesn't screw things up
+* No more "Where did my patch go?"
!SLIDE bullets incremental
-
-# Dependency tracking #
-
-* aka "Where did my patch go?"
-
-!SLIDE
- @@@ ruby
- # my_user_patch.rb
- require_dependency "user"
-
- module MyUserPatch
- User.send :include, self
- def say(something) end
- end
-
-!SLIDE
# Only reload on file changes #
+* (optional)
+
!SLIDE
# Pluggable Reloading Strategies #
-!SLIDE
@@@ ruby
module SinatraReloading
def invalidate_remains; end
def file
constant.app_file
end
def prepare
activate
constant.reset!
end
end
!SLIDE bullets incremental
* World reloading (default)
* Sloppy reloading (don't use)
* <s style="color: #888">Monkey</s> Freedom Patching strategy
-!SLIDE
- @@@ ruby
- AS::Dependencies.default_strategy = :sloppy
-
- MyClass.unloadable \
- :strategy => :monkey_patching
-
- AS::Dependencies::Constant["JustInCase"].
- strategy = :world
-
!SLIDE bullets
# Thanks! #
* Code: [github/rkh/rails](http://github.com/rkh/rails)
* Benchmarks: [github/rkh/reloader-shootout](http://github.com/rkh/rails)
* Blog post: [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
\ No newline at end of file
|
rkh/presentations
|
710183a555493371c5e21be20c446167be968dc8
|
added rubyconf presenation
|
diff --git a/rubyconf2010/showoff.json b/rubyconf2010/showoff.json
new file mode 100644
index 0000000..36744f6
--- /dev/null
+++ b/rubyconf2010/showoff.json
@@ -0,0 +1 @@
+{ "name": "Live Code Reloading", "sections": [ {"section":"slides"} ]}
diff --git a/rubyconf2010/slides/00_introduction.md b/rubyconf2010/slides/00_introduction.md
new file mode 100644
index 0000000..b97a74c
--- /dev/null
+++ b/rubyconf2010/slides/00_introduction.md
@@ -0,0 +1,10 @@
+!SLIDE
+# Live Code Reloading #
+
+!SLIDE bullets
+# Me #
+
+* [rkh.im](http://rkh.im/), [github/rkh](http://github.com/rkh), [@konstantinhaase](http://twitter.com/konstantinhaase)
+* Sinatra, Rubinius, Rack
+* Student at Hasso Plattner Institute, Potsdam (Germany)
+* Ruby dev at [Finnlabs](http://finn.de), Berlin
\ No newline at end of file
diff --git a/rubyconf2010/slides/01_reloading.md b/rubyconf2010/slides/01_reloading.md
new file mode 100644
index 0000000..d6082ac
--- /dev/null
+++ b/rubyconf2010/slides/01_reloading.md
@@ -0,0 +1,104 @@
+!SLIDE bullets incremental
+
+# Reloading Crash Course #
+
+* self-patching constants
+* actually restart your app
+* remove constant, reload file
+* [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
+
+!SLIDE
+# What changed? #
+
+!SLIDE
+
+# Internal Architecture #
+
+!SLIDE
+ @@@ ruby
+ module ActiveSupport::Dependencies
+ Constant["Foo"].active?
+ Constant["Bar"].activate
+ end
+
+!SLIDE
+
+# Battle Testing #
+
+!SLIDE bullets incremental
+
+* Old constant references become delegates
+* Better constant definition tracking
+* Instance invalidation
+* `$LOADED_FEATURES` aware
+
+!SLIDE
+
+# Come again? #
+
+!SLIDE bullets incremental
+
+* No more "Foo is not missing Bar"
+* (Nearly) no more "Already activated constant Blah"
+* Less unintentional behavior
+* `require` doesn't screw things up
+
+!SLIDE bullets incremental
+
+# Dependency tracking #
+
+* aka "Where did my patch go?"
+
+!SLIDE
+ @@@ ruby
+ # my_user_patch.rb
+ require_dependency "user"
+
+ module MyUserPatch
+ User.send :include, self
+ def say(something) end
+ end
+
+!SLIDE
+# Only reload on file changes #
+
+!SLIDE
+# Pluggable Reloading Strategies #
+
+!SLIDE
+ @@@ ruby
+ module SinatraReloading
+ def invalidate_remains; end
+
+ def file
+ constant.app_file
+ end
+
+ def prepare
+ activate
+ constant.reset!
+ end
+ end
+
+!SLIDE bullets incremental
+
+* World reloading (default)
+* Sloppy reloading (don't use)
+* <s style="color: #888">Monkey</s> Freedom Patching strategy
+
+!SLIDE
+ @@@ ruby
+ AS::Dependencies.default_strategy = :sloppy
+
+ MyClass.unloadable \
+ :strategy => :monkey_patching
+
+ AS::Dependencies::Constant["JustInCase"].
+ strategy = :world
+
+!SLIDE bullets
+# Thanks! #
+
+* Code: [github/rkh/rails](http://github.com/rkh/rails)
+* Benchmarks: [github/rkh/reloader-shootout](http://github.com/rkh/rails)
+* Blog post: [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
\ No newline at end of file
diff --git a/rubyconf2010/talk.css b/rubyconf2010/talk.css
new file mode 100644
index 0000000..196002a
--- /dev/null
+++ b/rubyconf2010/talk.css
@@ -0,0 +1,49 @@
+/* line 6, talk.sass */
+.content a:link, .content a:visited {
+ text-decoration: none;
+ color: black;
+ border-bottom: 1px dotted black;
+}
+
+/* line 11, talk.sass */
+body {
+ background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #eff5ff), color-stop(80%, #f3ffff), color-stop(100%, #ffffff));
+ background-image: -moz-linear-gradient(top, #eff5ff 20%, #f3ffff 80%, #ffffff 100%);
+ background-image: linear-gradient(top, #eff5ff 20%, #f3ffff 80%, #ffffff 100%);
+ background-color: white;
+ background-repeat: no-repeat;
+ background-attachment: fixed;
+}
+/* line 17, talk.sass */
+body #preso {
+ background-color: transparent !important;
+ margin-top: 50px !important;
+ width: 1050px !important;
+}
+/* line 21, talk.sass */
+body #preso .slide {
+ width: 1050px !important;
+ -moz-border-radius: 50px;
+ -webkit-border-radius: 50px;
+ -o-border-radius: 50px;
+ -ms-border-radius: 50px;
+ -khtml-border-radius: 50px;
+ border-radius: 50px;
+}
+/* line 24, talk.sass */
+body #preso .slide img {
+ margin-left: 13px;
+}
+/* line 26, talk.sass */
+body #footer {
+ background-color: transparent !important;
+}
+/* line 28, talk.sass */
+body #footer #slideInfo {
+ position: absolute;
+ top: 5px;
+ right: 20px;
+ color: #aabbdd;
+ text-align: right;
+ z-index: 9999 !important;
+}
|
rkh/presentations
|
bd02d40e925355ce955ecdd0cfdcc736a1eee032
|
some styling
|
diff --git a/rsoc2010-rugb/talk.sass b/rsoc2010-rugb/talk.sass
index c829210..f40c390 100644
--- a/rsoc2010-rugb/talk.sass
+++ b/rsoc2010-rugb/talk.sass
@@ -1,6 +1,34 @@
+@import "compass/css3"
+@import "compass/utilities"
+
.content
a
&:link, &:visited
text-decoration: none
color: #000
border-bottom: 1px dotted #000
+
+body
+ +linear-gradient(color-stops(#eff5ff 20%, #f3ffff 80%, #fff))
+ background:
+ color: #fff
+ repeat: no-repeat
+ attachment: fixed
+ #preso
+ background-color: transparent !important
+ margin-top: 50px !important
+ width: 1050px !important
+ .slide
+ width: 1050px !important
+ +border-radius(50px)
+ img
+ margin-left: 13px
+ #footer
+ background-color: transparent !important
+ #slideInfo
+ position: absolute
+ top: 5px
+ right: 20px
+ color: #abd
+ text-align: right
+ z-index: 9999 !important
|
rkh/presentations
|
6d345321d1f38882f9831eb61cb5110152d6d37e
|
RUG-B talk about RSoC
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..694c642
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+rsoc2010-rugb/talk.css
diff --git a/rsoc2010-rugb/showoff.json b/rsoc2010-rugb/showoff.json
new file mode 100644
index 0000000..36744f6
--- /dev/null
+++ b/rsoc2010-rugb/showoff.json
@@ -0,0 +1 @@
+{ "name": "Live Code Reloading", "sections": [ {"section":"slides"} ]}
diff --git a/rsoc2010-rugb/slides/00_introduction.md b/rsoc2010-rugb/slides/00_introduction.md
new file mode 100644
index 0000000..b004385
--- /dev/null
+++ b/rsoc2010-rugb/slides/00_introduction.md
@@ -0,0 +1,19 @@
+!SLIDE
+# Live Code Reloading #
+
+!SLIDE bullets incremental
+# Me #
+
+* [rkh.im](http://rkh.im/), [github/rkh](http://github.com/rkh), [@konstantinhaase](http://twitter.com/konstantinhaase)
+* Ruby dev at [Finnlabs](http://finn.de)
+* Rubinius, Sinatra, Rack, ... Rails?
+
+!SLIDE
+
+
+!SLIDE bullets incremental
+# ActiveSupport::Dependencies #
+
+* `Expected some_module.rb to define SomeModule!`
+* `A copy of SomeModule has been removed from the module tree but is still active!`
+* `SomeModule is not missing constant SomeConstant!`
\ No newline at end of file
diff --git a/rsoc2010-rugb/slides/01_autoloading.md b/rsoc2010-rugb/slides/01_autoloading.md
new file mode 100644
index 0000000..f4ef336
--- /dev/null
+++ b/rsoc2010-rugb/slides/01_autoloading.md
@@ -0,0 +1,30 @@
+!SLIDE
+# Autoloading Constants #
+
+!SLIDE
+ @@@ruby
+ require 'my_autoloader'
+
+ # require 'foo'
+ foo = Foo.new
+
+ # require 'foo_bar/blah'
+ bar = FooBar::Blah.nen
+
+!SLIDE
+ @@@ ruby
+ class Module
+ alias const_missing_without_autoloading \
+ const_missing
+
+ def const_missing(const)
+ path = "#{name.gsub('::', '/')}/#{const}"
+ path.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
+ require path.downcase
+ const_defined?(const) ?
+ const_get(const) : super
+ rescue LoadError => error
+ warn(error.message)
+ super
+ end
+ end
\ No newline at end of file
diff --git a/rsoc2010-rugb/slides/02_reloading_intro.md b/rsoc2010-rugb/slides/02_reloading_intro.md
new file mode 100644
index 0000000..efaad03
--- /dev/null
+++ b/rsoc2010-rugb/slides/02_reloading_intro.md
@@ -0,0 +1,20 @@
+!SLIDE bullets incremental
+# Reloading constants #
+* When?
+* What?
+* How?
+
+!SLIDE bullets incremental
+# When? #
+* After every request.
+* If a file changed.
+* After a request, if a file changed.
+
+!SLIDE bullets incremental
+# What? #
+* The files that changed.
+* Every file.
+* Some files.
+
+!SLIDE
+# How? #
diff --git a/rsoc2010-rugb/slides/03_restarting.md b/rsoc2010-rugb/slides/03_restarting.md
new file mode 100644
index 0000000..9139474
--- /dev/null
+++ b/rsoc2010-rugb/slides/03_restarting.md
@@ -0,0 +1,15 @@
+!SLIDE bullets incremental
+# Restart your application! #
+* Shotgun
+* rerun
+* "Magical Reloading Sparkles"
+
+!SLIDE bullets incremental
+# Advantages #
+* Correct
+* COW friendly
+
+!SLIDE bullets incremental
+# Disadvantages #
+* Slow
+* No Windows/JRuby support
\ No newline at end of file
diff --git a/rsoc2010-rugb/slides/04_open_classes.md b/rsoc2010-rugb/slides/04_open_classes.md
new file mode 100644
index 0000000..d7403a3
--- /dev/null
+++ b/rsoc2010-rugb/slides/04_open_classes.md
@@ -0,0 +1,101 @@
+!SLIDE bullets incremental
+# Rely On Open Classes #
+* Rack::Reloader
+* Sinatra::Reloader
+
+!SLIDE
+ @@@ ruby
+ # Foo = Class.new { ... }
+ class Foo
+ def self.bar(x) x + 1 end
+ bar(2) # => 3
+ end
+
+ # Foo.class_eval { ... }
+ class Foo
+ def self.bar(x) x + 2 end
+ bar(2) # => 4
+ end
+
+!SLIDE
+ @@@ ruby
+ # config.ru
+ use(Rack::Config) { load './foo.rb' }
+ run Foo
+
+!SLIDE
+ @@@ ruby
+ # config.ru
+ mtime, file = Time.at(0), './foo.rb'
+
+ use Rack::Config do
+ next if File.mtime(file) == mtime
+ mtime = File.mtime(file)
+ load file
+ end
+
+ run Foo
+
+!SLIDE
+ @@@ ruby
+ # config.ru
+ require 'foo'
+ use Rack::Reloader
+ run Foo
+
+!SLIDE bullets incremental
+# Advantages #
+* Fast
+* Able to reload single files
+
+!SLIDE
+# Disadvantages #
+
+!SLIDE
+ @@@ ruby
+ class Array
+ alias original_to_s to_s
+ def to_s
+ original_to_s.upcase
+ end
+ end
+
+ # reload...
+
+ class Array
+ alias original_to_s to_s
+ def to_s
+ original_to_s.downcase
+ end
+ end
+
+ [:foo].to_s
+
+!SLIDE bullets
+* `SystemStackError: stack level too deep`
+
+!SLIDE
+ @@@ ruby
+ class Foo
+ def self.bar() end
+ end
+
+ # reload...
+
+ class Foo
+ def self.foo() end
+ end
+
+ Foo.respond_to? :bar # => true
+
+!SLIDE
+ @@@ ruby
+ class Foo < ActiveResource::Base
+ end
+
+ # reload...
+
+ class Foo < ActiveRecord::Base
+ # TypeError: superclass mismatch
+ # for class Foo
+ end
diff --git a/rsoc2010-rugb/slides/05_remove_const.md b/rsoc2010-rugb/slides/05_remove_const.md
new file mode 100644
index 0000000..06f960d
--- /dev/null
+++ b/rsoc2010-rugb/slides/05_remove_const.md
@@ -0,0 +1,46 @@
+!SLIDE bullets incremental
+# Removing constants #
+* ActiveSupport::Dependencies
+* Merb::BootLoader::LoadClasses
+* Padrino::Reloader
+
+!SLIDE
+ @@@ ruby
+ # config.ru
+ use(Rack::Config) do
+ if Object.const_defined?(:Foo)
+ Object.send(:remove_const, :Foo)
+ end
+
+ load './foo.rb'
+ end
+
+ # `run Foo` would not pick up the new Foo
+ run proc { |env| Foo.call(env) }
+
+!SLIDE
+ @@@ ruby
+ class Foo; end
+ foo = Foo.new
+
+ Object.send(:remove_const, :Foo)
+ class Foo; end
+ foo.is_a? Foo # => false
+
+!SLIDE bullets incremental
+# ActiveSupport::Dependencies #
+* Autoloaded, unloadable and un-unloadable constant pools
+* `autoload_paths`, `autoload_once_paths`, `mechanism`
+* `history`, `loaded`, `autoloaded_constants`, `explicitly_unloadable_constants`, `references`, `constant_watch_stack`
+
+!SLIDE bullets incremental
+# ActiveSupport::Dependencies, reloaded #
+* Constant Wrapper
+* Strategies
+* Check for file changes (optional)
+
+!SLIDE bullets incremental
+# Strategies #
+* Global Reloader (default)
+* Monkey Patching Reloader
+* Sloppy Reloader
diff --git a/rsoc2010-rugb/slides/06_end.md b/rsoc2010-rugb/slides/06_end.md
new file mode 100644
index 0000000..46ff0f9
--- /dev/null
+++ b/rsoc2010-rugb/slides/06_end.md
@@ -0,0 +1,5 @@
+!SLIDE bullets
+# Thanks! #
+* Code: [github/rkh/rails](http://github.com/rkh/rails)
+* Benchmarks: [github/rkh/reloader-shootout](http://github.com/rkh/rails)
+* Blog post: [rkh.im/2010/08/code-reloading](http://rkh.im/2010/08/code-reloading)
\ No newline at end of file
diff --git a/rsoc2010-rugb/slides/rsoc.png b/rsoc2010-rugb/slides/rsoc.png
new file mode 100644
index 0000000..6effa21
Binary files /dev/null and b/rsoc2010-rugb/slides/rsoc.png differ
diff --git a/rsoc2010-rugb/talk.sass b/rsoc2010-rugb/talk.sass
new file mode 100644
index 0000000..c829210
--- /dev/null
+++ b/rsoc2010-rugb/talk.sass
@@ -0,0 +1,6 @@
+.content
+ a
+ &:link, &:visited
+ text-decoration: none
+ color: #000
+ border-bottom: 1px dotted #000
diff --git a/rsoc2010-rugb/talk.watchr b/rsoc2010-rugb/talk.watchr
new file mode 100644
index 0000000..8c29f23
--- /dev/null
+++ b/rsoc2010-rugb/talk.watchr
@@ -0,0 +1,19 @@
+def w(name, str = nil, &block)
+ block ||= proc { |m| sys(str % m[0])}
+ watch('^' << name.gsub('.', '\.').gsub('*', '.*')) do |m|
+ puts "-"*80, "#{Time.now.strftime("%H:%M:%S")} - file changed: \033[1;34m#{m[0]}\033[0m"
+ block[m]
+ end
+end
+
+def sys(cmd)
+ puts "\033[0;33m>>> \033[1;33m#{cmd}\033[0m"
+ if system cmd
+ puts "\033[1;32mSUCCESS\033[0m"
+ else
+ puts "\033[1;31mFAIL\033[0m"
+ end
+end
+
+w '*.coffee', 'coffee -c %s'
+w '*.(sass|scss)', 'compass compile --sass-dir . --css-dir . --images-dir . --javascripts-dir .'
|
ericholscher/devmason-utils
|
e500d67adaa01ec0082259d0a56168517bb83999
|
Small fix and print the response from the server.
|
diff --git a/devmason_utils/django_utils.py b/devmason_utils/django_utils.py
index a7d3358..8ff182d 100644
--- a/devmason_utils/django_utils.py
+++ b/devmason_utils/django_utils.py
@@ -1,88 +1,88 @@
from django.conf import settings
import datetime
import socket
import unittest
from devmason_utils.utils import (create_package, send_results, get_arch,
get_app_name_from_test, get_auth_string)
PB_SERVER = getattr(settings, 'PB_SERVER', 'http://devmason.com/pony_server')
PB_USER = getattr(settings, 'PB_USER', '')
PB_PASS = getattr(settings, 'PB_PASS', '')
if PB_USER and PB_PASS:
PB_AUTH = get_auth_string(PB_USER, PB_PASS)
else:
print "No auth provided."
- PB_AUTH = None
+ PB_AUTH = ''
STARTED = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
def _insert_failure(failed_apps, app, failure):
if failed_apps.has_key(app):
failed_apps[app].append(failure)
else:
failed_apps[app] = [failure]
def _increment_app(all_apps, app):
if all_apps.has_key(app):
all_apps[app] += 1
else:
all_apps[app] = 1
def get_test_cases(suite):
test_cases = []
if isinstance(suite, unittest.TestSuite):
for test_case_or_suite in suite._tests:
if isinstance(test_case_or_suite, unittest.TestSuite):
test_cases.extend(get_test_cases(test_case_or_suite))
else:
test_cases.append(test_case_or_suite)
return test_cases
def report_results_for_suite(suite, result):
failed_apps = {}
all_apps = {}
for test in get_test_cases(suite):
test_app = get_app_name_from_test(test)
_increment_app(all_apps, test_app)
for failure in result.failures + result.errors:
test = failure[0]
output = failure[1]
app = get_app_name_from_test(test)
_insert_failure(failed_apps, app, failure)
arch = get_arch()
hostname = socket.gethostname()
for app in all_apps:
success = app not in failed_apps.keys()
if app in failed_apps:
errout = '\n'.join([failure[1] for failure in failed_apps[app]])
else:
errout = "%s Passed" % all_apps[app]
build_dict = {'success': success,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
'tags': ['django_test_runner'],
'client': {
'arch': arch,
'host': hostname,
'user': PB_USER,
},
'results': [
{'success': success,
'name': 'Test Application',
'errout': errout,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
}
]
}
try:
create_package(app, server=PB_SERVER, auth=PB_AUTH)
send_results(app, build_dict, server=PB_SERVER, auth=PB_AUTH)
except:
#Don't blow up tests if we can't report results.
pass
diff --git a/devmason_utils/utils.py b/devmason_utils/utils.py
index d29e1a8..824f4c2 100644
--- a/devmason_utils/utils.py
+++ b/devmason_utils/utils.py
@@ -1,73 +1,76 @@
try:
import simplejson as json
except:
from django.utils import simplejson as json
import httplib2
import distutils.util
import unicodedata
import re
PB_SERVER = 'http://devmason.com/pony_server'
def get_auth_string(user, passwd):
return "Basic %s" % ("%s:%s" % (user, passwd)).encode("base64").strip()
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '_', value).strip().lower())
return re.sub('[-\s]+', '-', value)
def get_app_name_from_test(test):
try:
#doctest
app = test._dt_test.name.split('.tests')[0]
except AttributeError:
#unit test in tests
app = test.__module__.split('.tests')[0]
if not app:
#Unit test in models.
app = test.__module__.split('.models')[0]
if not app:
app = test.__module__.split('.')[0]
return app
def get_arch():
return distutils.util.get_platform()
def create_package(project, name=None, server=PB_SERVER, auth=None):
if not name:
name = project
print "Sending info for %s" % name
create_url = "%s/%s" % (server, slugify(unicode(project)))
json_payload = '{"name": "%s"}' % name
h = httplib2.Http()
resp, content = h.request(create_url, "PUT", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
return resp
def send_results(project, result_dict, server=PB_SERVER, auth=None):
post_url = "%s/%s/builds" % (server, slugify(unicode(project)))
json_payload = json.dumps(result_dict)
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
+ print "Results from server:"
+ print resp
+ print content
def send_build_request(project, identifier='HEAD', server=PB_SERVER):
post_url = "%s/builds/request" % server
post_data = json.dumps({
'project': project,
'identifier': identifier,
})
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=post_data,
headers={'content-type':'application/json'}
)
|
ericholscher/devmason-utils
|
bf4394de17a90b3cd3187bcf45ac3b4c1b0af0c6
|
Small cleanup.
|
diff --git a/devmason_utils/django_utils.py b/devmason_utils/django_utils.py
index 949c7e3..a7d3358 100644
--- a/devmason_utils/django_utils.py
+++ b/devmason_utils/django_utils.py
@@ -1,86 +1,88 @@
from django.conf import settings
import datetime
import socket
import unittest
-from devmason_utils.utils import create_package, send_results, get_arch, get_app_name_from_test
+from devmason_utils.utils import (create_package, send_results, get_arch,
+ get_app_name_from_test, get_auth_string)
PB_SERVER = getattr(settings, 'PB_SERVER', 'http://devmason.com/pony_server')
PB_USER = getattr(settings, 'PB_USER', '')
PB_PASS = getattr(settings, 'PB_PASS', '')
+
if PB_USER and PB_PASS:
- PB_AUTH = "Basic %s" % ("%s:%s" % (PB_USER, PB_PASS)).encode("base64").strip()
+ PB_AUTH = get_auth_string(PB_USER, PB_PASS)
else:
print "No auth provided."
PB_AUTH = None
STARTED = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
def _insert_failure(failed_apps, app, failure):
if failed_apps.has_key(app):
failed_apps[app].append(failure)
else:
failed_apps[app] = [failure]
def _increment_app(all_apps, app):
if all_apps.has_key(app):
all_apps[app] += 1
else:
all_apps[app] = 1
def get_test_cases(suite):
test_cases = []
if isinstance(suite, unittest.TestSuite):
for test_case_or_suite in suite._tests:
if isinstance(test_case_or_suite, unittest.TestSuite):
test_cases.extend(get_test_cases(test_case_or_suite))
else:
test_cases.append(test_case_or_suite)
return test_cases
def report_results_for_suite(suite, result):
failed_apps = {}
all_apps = {}
for test in get_test_cases(suite):
test_app = get_app_name_from_test(test)
_increment_app(all_apps, test_app)
for failure in result.failures + result.errors:
test = failure[0]
output = failure[1]
app = get_app_name_from_test(test)
_insert_failure(failed_apps, app, failure)
arch = get_arch()
hostname = socket.gethostname()
for app in all_apps:
success = app not in failed_apps.keys()
if app in failed_apps:
errout = '\n'.join([failure[1] for failure in failed_apps[app]])
else:
errout = "%s Passed" % all_apps[app]
build_dict = {'success': success,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
'tags': ['django_test_runner'],
'client': {
'arch': arch,
'host': hostname,
'user': PB_USER,
},
'results': [
{'success': success,
'name': 'Test Application',
'errout': errout,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
}
]
}
try:
create_package(app, server=PB_SERVER, auth=PB_AUTH)
send_results(app, build_dict, server=PB_SERVER, auth=PB_AUTH)
except:
#Don't blow up tests if we can't report results.
pass
diff --git a/devmason_utils/models.py b/devmason_utils/models.py
index e69de29..58e048e 100644
--- a/devmason_utils/models.py
+++ b/devmason_utils/models.py
@@ -0,0 +1,31 @@
+#Go do yourself a favor and watch The Dead Poets Society.
+#
+#O Captain my Captain! our fearful trip is done,
+#The ship has weathered every rack, the prize we sought is won,
+#The port is near, the bells I hear, the people all exulting,
+#While follow eyes the steady keel, the vessel grim and daring;
+#But O heart! heart! heart!
+#O the bleeding drops of red,
+#Where on the deck my Captain lies,
+#Fallen cold and dead.
+#
+#O Captain! my Captain! rise up and hear the bells;
+#Rise up--for you the flag is flung for you the bugle trills,
+#For you bouquets and ribboned wreaths for you the shores a-crowding,
+#For you they call, the swaying mass, their eager faces turning;
+#Here Captain! dear father!
+#This arm beneath your head!
+#It is some dream that on the deck,
+#You've fallen cold and dead.
+#
+#My Captain does not answer, his lips are pale and still;
+#My father does not feel my arm, he has no pulse nor will;
+#The ship is anchored safe and sound, its voyage closed and done;
+#From fearful trip the victor ship comes in with object won;
+#Exult O shores, and ring O bells!
+#But I, with mournful tread,
+#Walk the deck my Captain lies,
+#Fallen cold and dead.
+#
+#
+#Walt Whitman
\ No newline at end of file
diff --git a/devmason_utils/tests.py b/devmason_utils/tests.py
index 780af65..829501e 100644
--- a/devmason_utils/tests.py
+++ b/devmason_utils/tests.py
@@ -1,11 +1,11 @@
import pprint
import difflib
from django.test import TestCase, Client
from devmason_utils.utils import create_package, get_auth_string
class CreatePackageTests(TestCase):
def test_create_package(self):
auth = get_auth_string('test', 'test')
- resp = create_package('My Project2', server='http://localhost:8000/devmason', auth=auth)
+ resp = create_package('My Project', server='http://localhost:8000/devmason', auth=auth)
|
ericholscher/devmason-utils
|
862366a27b818ce7452030ebd49d822bc75185c1
|
Added super basic tests, requires a local server to be running.
|
diff --git a/devmason_utils/models.py b/devmason_utils/models.py
new file mode 100644
index 0000000..e69de29
diff --git a/devmason_utils/tests.py b/devmason_utils/tests.py
new file mode 100644
index 0000000..780af65
--- /dev/null
+++ b/devmason_utils/tests.py
@@ -0,0 +1,11 @@
+import pprint
+import difflib
+from django.test import TestCase, Client
+
+from devmason_utils.utils import create_package, get_auth_string
+
+class CreatePackageTests(TestCase):
+
+ def test_create_package(self):
+ auth = get_auth_string('test', 'test')
+ resp = create_package('My Project2', server='http://localhost:8000/devmason', auth=auth)
|
ericholscher/devmason-utils
|
798af38bbd36880fb276f15751d3ad8a8b4b9004
|
Small name cleanup.
|
diff --git a/devmason_utils/django_utils.py b/devmason_utils/django_utils.py
index 813fd95..949c7e3 100644
--- a/devmason_utils/django_utils.py
+++ b/devmason_utils/django_utils.py
@@ -1,86 +1,86 @@
from django.conf import settings
import datetime
import socket
import unittest
-from pony_utils.utils import create_package, send_results, get_arch, get_app_name_from_test
+from devmason_utils.utils import create_package, send_results, get_arch, get_app_name_from_test
PB_SERVER = getattr(settings, 'PB_SERVER', 'http://devmason.com/pony_server')
PB_USER = getattr(settings, 'PB_USER', '')
PB_PASS = getattr(settings, 'PB_PASS', '')
if PB_USER and PB_PASS:
PB_AUTH = "Basic %s" % ("%s:%s" % (PB_USER, PB_PASS)).encode("base64").strip()
else:
print "No auth provided."
PB_AUTH = None
STARTED = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
def _insert_failure(failed_apps, app, failure):
if failed_apps.has_key(app):
failed_apps[app].append(failure)
else:
failed_apps[app] = [failure]
def _increment_app(all_apps, app):
if all_apps.has_key(app):
all_apps[app] += 1
else:
all_apps[app] = 1
def get_test_cases(suite):
test_cases = []
if isinstance(suite, unittest.TestSuite):
for test_case_or_suite in suite._tests:
if isinstance(test_case_or_suite, unittest.TestSuite):
test_cases.extend(get_test_cases(test_case_or_suite))
else:
test_cases.append(test_case_or_suite)
return test_cases
def report_results_for_suite(suite, result):
failed_apps = {}
all_apps = {}
for test in get_test_cases(suite):
test_app = get_app_name_from_test(test)
_increment_app(all_apps, test_app)
for failure in result.failures + result.errors:
test = failure[0]
output = failure[1]
app = get_app_name_from_test(test)
_insert_failure(failed_apps, app, failure)
arch = get_arch()
hostname = socket.gethostname()
for app in all_apps:
success = app not in failed_apps.keys()
if app in failed_apps:
errout = '\n'.join([failure[1] for failure in failed_apps[app]])
else:
errout = "%s Passed" % all_apps[app]
build_dict = {'success': success,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
'tags': ['django_test_runner'],
'client': {
'arch': arch,
'host': hostname,
'user': PB_USER,
},
'results': [
{'success': success,
'name': 'Test Application',
'errout': errout,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
}
]
}
try:
create_package(app, server=PB_SERVER, auth=PB_AUTH)
send_results(app, build_dict, server=PB_SERVER, auth=PB_AUTH)
except:
#Don't blow up tests if we can't report results.
pass
diff --git a/devmason_utils/test_runner.py b/devmason_utils/test_runner.py
index 62d5c38..5f7fcc9 100644
--- a/devmason_utils/test_runner.py
+++ b/devmason_utils/test_runner.py
@@ -1,62 +1,62 @@
import unittest
from django.conf import settings
from django.db.models import get_app, get_apps
from django.test import _doctest as doctest
from django.test.utils import setup_test_environment, teardown_test_environment
from django.test.testcases import OutputChecker, DocTestRunner, TestCase
from django.test.simple import *
-from pony_utils.django.utils import report_results_for_suite
+from devmason_utils.django_utils import report_results_for_suite
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
"""
Run the unit tests for all the test labels in the provided list.
Labels must be of the form:
- app.TestClass.test_method
Run a single specific test method
- app.TestClass
Run all the test methods in a given class
- app
Search for doctests and unittests in the named application.
When looking for tests, the test runner will look in the models and
tests modules for the application.
A list of 'extra' tests may also be provided; these tests
will be added to the test suite.
Returns the number of tests that failed.
"""
setup_test_environment()
settings.DEBUG = False
suite = unittest.TestSuite()
if test_labels:
for label in test_labels:
if '.' in label:
suite.addTest(build_test(label))
else:
app = get_app(label)
suite.addTest(build_suite(app))
else:
for app in get_apps():
#run_tests(build_suite(app))
suite.addTest(build_suite(app))
for test in extra_tests:
suite.addTest(test)
suite = reorder_suite(suite, (TestCase,))
old_name = settings.DATABASE_NAME
from django.db import connection
connection.creation.create_test_db(verbosity, autoclobber=not interactive)
result = unittest.TextTestRunner(verbosity=verbosity).run(suite)
connection.creation.destroy_test_db(old_name, verbosity)
teardown_test_environment()
report_results_for_suite(suite, result)
return len(result.failures) + len(result.errors)
diff --git a/devmason_utils/utils.py b/devmason_utils/utils.py
index 43c7fb2..d29e1a8 100644
--- a/devmason_utils/utils.py
+++ b/devmason_utils/utils.py
@@ -1,69 +1,73 @@
try:
import simplejson as json
except:
from django.utils import simplejson as json
import httplib2
import distutils.util
import unicodedata
import re
PB_SERVER = 'http://devmason.com/pony_server'
+def get_auth_string(user, passwd):
+ return "Basic %s" % ("%s:%s" % (user, passwd)).encode("base64").strip()
+
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '_', value).strip().lower())
return re.sub('[-\s]+', '-', value)
def get_app_name_from_test(test):
try:
#doctest
app = test._dt_test.name.split('.tests')[0]
except AttributeError:
#unit test in tests
app = test.__module__.split('.tests')[0]
if not app:
#Unit test in models.
app = test.__module__.split('.models')[0]
if not app:
app = test.__module__.split('.')[0]
return app
def get_arch():
return distutils.util.get_platform()
def create_package(project, name=None, server=PB_SERVER, auth=None):
if not name:
name = project
print "Sending info for %s" % name
create_url = "%s/%s" % (server, slugify(unicode(project)))
json_payload = '{"name": "%s"}' % name
h = httplib2.Http()
resp, content = h.request(create_url, "PUT", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
+ return resp
def send_results(project, result_dict, server=PB_SERVER, auth=None):
post_url = "%s/%s/builds" % (server, slugify(unicode(project)))
json_payload = json.dumps(result_dict)
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
def send_build_request(project, identifier='HEAD', server=PB_SERVER):
post_url = "%s/builds/request" % server
post_data = json.dumps({
'project': project,
'identifier': identifier,
})
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=post_data,
headers={'content-type':'application/json'}
)
|
ericholscher/devmason-utils
|
363c1a71aa4131739f7f7bdd3ff63e4a53a18bb1
|
Added initial sphinx docs layout.
|
diff --git a/docs/Makefile b/docs/Makefile
new file mode 100644
index 0000000..7b41bab
--- /dev/null
+++ b/docs/Makefile
@@ -0,0 +1,89 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER =
+BUILDDIR = _build
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
+
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+ -rm -rf $(BUILDDIR)/*
+
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/DevmasonUtils.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/DevmasonUtils.qhc"
+
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+ @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
+ "run these through (pdf)latex."
+
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+ @echo
+ @echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in $(BUILDDIR)/doctest/output.txt."
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000..3e9d7ff
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,194 @@
+# -*- coding: utf-8 -*-
+#
+# Devmason Utils documentation build configuration file, created by
+# sphinx-quickstart on Wed Mar 10 20:24:40 2010.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.append(os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = []
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'Devmason Utils'
+copyright = u'2010, Eric Holscher'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '0.1'
+# The full version, including alpha/beta/rc tags.
+release = '0.1'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of documents that shouldn't be included in the build.
+#unused_docs = []
+
+# List of directories, relative to source directory, that shouldn't be searched
+# for source files.
+exclude_trees = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. Major themes that come with
+# Sphinx are currently 'default' and 'sphinxdoc'.
+html_theme = 'default'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_use_modindex = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = ''
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'DevmasonUtilsdoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+#latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+ ('index', 'DevmasonUtils.tex', u'Devmason Utils Documentation',
+ u'Eric Holscher', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_use_modindex = True
diff --git a/docs/index.rst b/docs/index.rst
new file mode 100644
index 0000000..2292602
--- /dev/null
+++ b/docs/index.rst
@@ -0,0 +1,20 @@
+.. Devmason Utils documentation master file, created by
+ sphinx-quickstart on Wed Mar 10 20:24:40 2010.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to Devmason Utils's documentation!
+==========================================
+
+Contents:
+
+.. toctree::
+ :maxdepth: 2
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
diff --git a/docs/make.bat b/docs/make.bat
new file mode 100644
index 0000000..f413ecd
--- /dev/null
+++ b/docs/make.bat
@@ -0,0 +1,113 @@
+@ECHO OFF
+
+REM Command file for Sphinx documentation
+
+set SPHINXBUILD=sphinx-build
+set BUILDDIR=_build
+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
+if NOT "%PAPER%" == "" (
+ set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
+)
+
+if "%1" == "" goto help
+
+if "%1" == "help" (
+ :help
+ echo.Please use `make ^<target^>` where ^<target^> is one of
+ echo. html to make standalone HTML files
+ echo. dirhtml to make HTML files named index.html in directories
+ echo. pickle to make pickle files
+ echo. json to make JSON files
+ echo. htmlhelp to make HTML files and a HTML help project
+ echo. qthelp to make HTML files and a qthelp project
+ echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
+ echo. changes to make an overview over all changed/added/deprecated items
+ echo. linkcheck to check all external links for integrity
+ echo. doctest to run all doctests embedded in the documentation if enabled
+ goto end
+)
+
+if "%1" == "clean" (
+ for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
+ del /q /s %BUILDDIR%\*
+ goto end
+)
+
+if "%1" == "html" (
+ %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/html.
+ goto end
+)
+
+if "%1" == "dirhtml" (
+ %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
+ goto end
+)
+
+if "%1" == "pickle" (
+ %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
+ echo.
+ echo.Build finished; now you can process the pickle files.
+ goto end
+)
+
+if "%1" == "json" (
+ %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
+ echo.
+ echo.Build finished; now you can process the JSON files.
+ goto end
+)
+
+if "%1" == "htmlhelp" (
+ %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
+ echo.
+ echo.Build finished; now you can run HTML Help Workshop with the ^
+.hhp project file in %BUILDDIR%/htmlhelp.
+ goto end
+)
+
+if "%1" == "qthelp" (
+ %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
+ echo.
+ echo.Build finished; now you can run "qcollectiongenerator" with the ^
+.qhcp project file in %BUILDDIR%/qthelp, like this:
+ echo.^> qcollectiongenerator %BUILDDIR%\qthelp\DevmasonUtils.qhcp
+ echo.To view the help file:
+ echo.^> assistant -collectionFile %BUILDDIR%\qthelp\DevmasonUtils.ghc
+ goto end
+)
+
+if "%1" == "latex" (
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+ echo.
+ echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
+ goto end
+)
+
+if "%1" == "changes" (
+ %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
+ echo.
+ echo.The overview file is in %BUILDDIR%/changes.
+ goto end
+)
+
+if "%1" == "linkcheck" (
+ %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
+ echo.
+ echo.Link check complete; look for any errors in the above output ^
+or in %BUILDDIR%/linkcheck/output.txt.
+ goto end
+)
+
+if "%1" == "doctest" (
+ %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
+ echo.
+ echo.Testing of doctests in the sources finished, look at the ^
+results in %BUILDDIR%/doctest/output.txt.
+ goto end
+)
+
+:end
|
ericholscher/devmason-utils
|
46ddcd1b033f98dc02a1018df5b239561add8809
|
Added license, setup.py, authors, general house cleaning.
|
diff --git a/AUTHORS b/AUTHORS
new file mode 100644
index 0000000..34f31dd
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1 @@
+Eric Holscher
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..44e6fcc
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,23 @@
+Copyright (c) 2008 Eric Holscher <[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.
+
diff --git a/README b/README
index d3ac787..1c9b55a 100644
--- a/README
+++ b/README
@@ -1 +1 @@
-This is where we put all the utils for playing with ponies, in the clouds.
+This is a project for interacting with http://devmason.com. It provides an example Python implementation of the API.
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..3e0d045
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,11 @@
+from setuptools import setup
+
+setup(name='devmason_utils',
+ version='0.1',
+ description='A Python client implementation of a the devmason server.',
+ author = 'Eric Holscher',
+ url = 'http://github.com/ericholscher/devmason-utils',
+ license = 'BSD',
+ packages = ['devmason_utils'],
+ install_requires=['httplib2'],
+)
|
ericholscher/devmason-utils
|
bb26eee736d61d967a3107419d8143b4756d4e14
|
Do a bare except, which makes me cry, so hudson builds work.
|
diff --git a/pony_utils/django/utils.py b/pony_utils/django/utils.py
index 20c0c21..813fd95 100644
--- a/pony_utils/django/utils.py
+++ b/pony_utils/django/utils.py
@@ -1,82 +1,86 @@
from django.conf import settings
import datetime
import socket
import unittest
from pony_utils.utils import create_package, send_results, get_arch, get_app_name_from_test
PB_SERVER = getattr(settings, 'PB_SERVER', 'http://devmason.com/pony_server')
PB_USER = getattr(settings, 'PB_USER', '')
PB_PASS = getattr(settings, 'PB_PASS', '')
if PB_USER and PB_PASS:
PB_AUTH = "Basic %s" % ("%s:%s" % (PB_USER, PB_PASS)).encode("base64").strip()
else:
print "No auth provided."
PB_AUTH = None
STARTED = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
def _insert_failure(failed_apps, app, failure):
if failed_apps.has_key(app):
failed_apps[app].append(failure)
else:
failed_apps[app] = [failure]
def _increment_app(all_apps, app):
if all_apps.has_key(app):
all_apps[app] += 1
else:
all_apps[app] = 1
def get_test_cases(suite):
test_cases = []
if isinstance(suite, unittest.TestSuite):
for test_case_or_suite in suite._tests:
if isinstance(test_case_or_suite, unittest.TestSuite):
test_cases.extend(get_test_cases(test_case_or_suite))
else:
test_cases.append(test_case_or_suite)
return test_cases
def report_results_for_suite(suite, result):
failed_apps = {}
all_apps = {}
for test in get_test_cases(suite):
test_app = get_app_name_from_test(test)
_increment_app(all_apps, test_app)
for failure in result.failures + result.errors:
test = failure[0]
output = failure[1]
app = get_app_name_from_test(test)
_insert_failure(failed_apps, app, failure)
arch = get_arch()
hostname = socket.gethostname()
for app in all_apps:
success = app not in failed_apps.keys()
if app in failed_apps:
errout = '\n'.join([failure[1] for failure in failed_apps[app]])
else:
errout = "%s Passed" % all_apps[app]
build_dict = {'success': success,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
'tags': ['django_test_runner'],
'client': {
'arch': arch,
'host': hostname,
'user': PB_USER,
},
'results': [
{'success': success,
'name': 'Test Application',
'errout': errout,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
}
]
}
- create_package(app, server=PB_SERVER, auth=PB_AUTH)
- send_results(app, build_dict, server=PB_SERVER, auth=PB_AUTH)
+ try:
+ create_package(app, server=PB_SERVER, auth=PB_AUTH)
+ send_results(app, build_dict, server=PB_SERVER, auth=PB_AUTH)
+ except:
+ #Don't blow up tests if we can't report results.
+ pass
|
ericholscher/devmason-utils
|
a36818eea3a0887f152b65d8671d70cd629b2700
|
Fallback to django's.
|
diff --git a/pony_utils/utils.py b/pony_utils/utils.py
index 0b4421a..43c7fb2 100644
--- a/pony_utils/utils.py
+++ b/pony_utils/utils.py
@@ -1,66 +1,69 @@
-from django.utils import simplejson as json
+try:
+ import simplejson as json
+except:
+ from django.utils import simplejson as json
import httplib2
import distutils.util
import unicodedata
import re
PB_SERVER = 'http://devmason.com/pony_server'
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '_', value).strip().lower())
return re.sub('[-\s]+', '-', value)
def get_app_name_from_test(test):
try:
#doctest
app = test._dt_test.name.split('.tests')[0]
except AttributeError:
#unit test in tests
app = test.__module__.split('.tests')[0]
if not app:
#Unit test in models.
app = test.__module__.split('.models')[0]
if not app:
app = test.__module__.split('.')[0]
return app
def get_arch():
return distutils.util.get_platform()
def create_package(project, name=None, server=PB_SERVER, auth=None):
if not name:
name = project
print "Sending info for %s" % name
create_url = "%s/%s" % (server, slugify(unicode(project)))
json_payload = '{"name": "%s"}' % name
h = httplib2.Http()
resp, content = h.request(create_url, "PUT", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
def send_results(project, result_dict, server=PB_SERVER, auth=None):
post_url = "%s/%s/builds" % (server, slugify(unicode(project)))
json_payload = json.dumps(result_dict)
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
def send_build_request(project, identifier='HEAD', server=PB_SERVER):
post_url = "%s/builds/request" % server
post_data = json.dumps({
'project': project,
'identifier': identifier,
})
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=post_data,
headers={'content-type':'application/json'}
)
|
ericholscher/devmason-utils
|
a6e091cb5fec1dca0f6297dcc7ecfd69b71eedb4
|
Fix json import.
|
diff --git a/pony_utils/utils.py b/pony_utils/utils.py
index a43c21a..0b4421a 100644
--- a/pony_utils/utils.py
+++ b/pony_utils/utils.py
@@ -1,69 +1,66 @@
-try:
- import json
-except:
- import simplejson
+from django.utils import simplejson as json
import httplib2
import distutils.util
import unicodedata
import re
PB_SERVER = 'http://devmason.com/pony_server'
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '_', value).strip().lower())
return re.sub('[-\s]+', '-', value)
def get_app_name_from_test(test):
try:
#doctest
app = test._dt_test.name.split('.tests')[0]
except AttributeError:
#unit test in tests
app = test.__module__.split('.tests')[0]
if not app:
#Unit test in models.
app = test.__module__.split('.models')[0]
if not app:
app = test.__module__.split('.')[0]
return app
def get_arch():
return distutils.util.get_platform()
def create_package(project, name=None, server=PB_SERVER, auth=None):
if not name:
name = project
print "Sending info for %s" % name
create_url = "%s/%s" % (server, slugify(unicode(project)))
json_payload = '{"name": "%s"}' % name
h = httplib2.Http()
resp, content = h.request(create_url, "PUT", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
def send_results(project, result_dict, server=PB_SERVER, auth=None):
post_url = "%s/%s/builds" % (server, slugify(unicode(project)))
json_payload = json.dumps(result_dict)
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
def send_build_request(project, identifier='HEAD', server=PB_SERVER):
post_url = "%s/builds/request" % server
post_data = json.dumps({
'project': project,
'identifier': identifier,
})
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=post_data,
headers={'content-type':'application/json'}
)
|
ericholscher/devmason-utils
|
10140715b43573b76c3833eb872ecf481d8e42bc
|
Handle Test Suites for the test runner.
|
diff --git a/pony_utils/django/utils.py b/pony_utils/django/utils.py
index 81f80e8..20c0c21 100644
--- a/pony_utils/django/utils.py
+++ b/pony_utils/django/utils.py
@@ -1,71 +1,82 @@
from django.conf import settings
import datetime
import socket
+import unittest
from pony_utils.utils import create_package, send_results, get_arch, get_app_name_from_test
PB_SERVER = getattr(settings, 'PB_SERVER', 'http://devmason.com/pony_server')
PB_USER = getattr(settings, 'PB_USER', '')
PB_PASS = getattr(settings, 'PB_PASS', '')
if PB_USER and PB_PASS:
PB_AUTH = "Basic %s" % ("%s:%s" % (PB_USER, PB_PASS)).encode("base64").strip()
else:
print "No auth provided."
PB_AUTH = None
STARTED = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
def _insert_failure(failed_apps, app, failure):
if failed_apps.has_key(app):
failed_apps[app].append(failure)
else:
failed_apps[app] = [failure]
def _increment_app(all_apps, app):
if all_apps.has_key(app):
all_apps[app] += 1
else:
all_apps[app] = 1
+def get_test_cases(suite):
+ test_cases = []
+ if isinstance(suite, unittest.TestSuite):
+ for test_case_or_suite in suite._tests:
+ if isinstance(test_case_or_suite, unittest.TestSuite):
+ test_cases.extend(get_test_cases(test_case_or_suite))
+ else:
+ test_cases.append(test_case_or_suite)
+ return test_cases
+
def report_results_for_suite(suite, result):
failed_apps = {}
all_apps = {}
- for test in suite._tests:
+ for test in get_test_cases(suite):
test_app = get_app_name_from_test(test)
_increment_app(all_apps, test_app)
for failure in result.failures + result.errors:
test = failure[0]
output = failure[1]
app = get_app_name_from_test(test)
_insert_failure(failed_apps, app, failure)
arch = get_arch()
hostname = socket.gethostname()
for app in all_apps:
success = app not in failed_apps.keys()
if app in failed_apps:
errout = '\n'.join([failure[1] for failure in failed_apps[app]])
else:
errout = "%s Passed" % all_apps[app]
build_dict = {'success': success,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
'tags': ['django_test_runner'],
'client': {
'arch': arch,
'host': hostname,
'user': PB_USER,
},
'results': [
{'success': success,
'name': 'Test Application',
'errout': errout,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
}
]
}
- create_package(PB_SERVER, app, auth=PB_AUTH)
- send_results(PB_SERVER, app, build_dict, auth=PB_AUTH)
\ No newline at end of file
+ create_package(app, server=PB_SERVER, auth=PB_AUTH)
+ send_results(app, build_dict, server=PB_SERVER, auth=PB_AUTH)
|
ericholscher/devmason-utils
|
30484b1622f4aef6b29cfceb7390d0400f877b8d
|
Parse App names a little cleaner.
|
diff --git a/pony_utils/utils.py b/pony_utils/utils.py
index dc26044..a43c21a 100644
--- a/pony_utils/utils.py
+++ b/pony_utils/utils.py
@@ -1,69 +1,69 @@
try:
import json
except:
import simplejson
import httplib2
import distutils.util
import unicodedata
import re
PB_SERVER = 'http://devmason.com/pony_server'
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '_', value).strip().lower())
return re.sub('[-\s]+', '-', value)
def get_app_name_from_test(test):
try:
#doctest
- app = test._dt_test.name.split('.tests.')[0]
+ app = test._dt_test.name.split('.tests')[0]
except AttributeError:
#unit test in tests
- app = test.__module__.split('.tests.')[0]
+ app = test.__module__.split('.tests')[0]
if not app:
#Unit test in models.
- app = test.__module__.split('.models.')[0]
+ app = test.__module__.split('.models')[0]
if not app:
app = test.__module__.split('.')[0]
return app
def get_arch():
return distutils.util.get_platform()
def create_package(project, name=None, server=PB_SERVER, auth=None):
if not name:
name = project
print "Sending info for %s" % name
create_url = "%s/%s" % (server, slugify(unicode(project)))
json_payload = '{"name": "%s"}' % name
h = httplib2.Http()
resp, content = h.request(create_url, "PUT", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
-def send_results(project, result_dict,server=PB_SERVER, auth=None):
+def send_results(project, result_dict, server=PB_SERVER, auth=None):
post_url = "%s/%s/builds" % (server, slugify(unicode(project)))
json_payload = json.dumps(result_dict)
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
def send_build_request(project, identifier='HEAD', server=PB_SERVER):
post_url = "%s/builds/request" % server
post_data = json.dumps({
'project': project,
'identifier': identifier,
})
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=post_data,
headers={'content-type':'application/json'}
)
|
ericholscher/devmason-utils
|
20bd44e856302432c7c68742efcb5786a254c739
|
Fix silly typo
|
diff --git a/pony_utils/utils.py b/pony_utils/utils.py
index f849e29..dc26044 100644
--- a/pony_utils/utils.py
+++ b/pony_utils/utils.py
@@ -1,69 +1,69 @@
try:
import json
except:
import simplejson
import httplib2
import distutils.util
import unicodedata
import re
PB_SERVER = 'http://devmason.com/pony_server'
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '_', value).strip().lower())
return re.sub('[-\s]+', '-', value)
def get_app_name_from_test(test):
try:
#doctest
app = test._dt_test.name.split('.tests.')[0]
except AttributeError:
#unit test in tests
app = test.__module__.split('.tests.')[0]
if not app:
#Unit test in models.
app = test.__module__.split('.models.')[0]
if not app:
app = test.__module__.split('.')[0]
return app
def get_arch():
return distutils.util.get_platform()
def create_package(project, name=None, server=PB_SERVER, auth=None):
if not name:
name = project
print "Sending info for %s" % name
create_url = "%s/%s" % (server, slugify(unicode(project)))
json_payload = '{"name": "%s"}' % name
h = httplib2.Http()
resp, content = h.request(create_url, "PUT", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
def send_results(project, result_dict,server=PB_SERVER, auth=None):
post_url = "%s/%s/builds" % (server, slugify(unicode(project)))
json_payload = json.dumps(result_dict)
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
-def send_build_request(project, identifier=HEAD, server=PB_SERVER):
+def send_build_request(project, identifier='HEAD', server=PB_SERVER):
post_url = "%s/builds/request" % server
post_data = json.dumps({
'project': project,
'identifier': identifier,
})
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=post_data,
headers={'content-type':'application/json'}
)
|
ericholscher/devmason-utils
|
d81a3f98ebe323ed378a9a4280824da24d4c6b32
|
Added a default of devmason :)
|
diff --git a/pony_utils/django/utils.py b/pony_utils/django/utils.py
index 7ebb207..81f80e8 100644
--- a/pony_utils/django/utils.py
+++ b/pony_utils/django/utils.py
@@ -1,72 +1,71 @@
from django.conf import settings
import datetime
import socket
from pony_utils.utils import create_package, send_results, get_arch, get_app_name_from_test
-#http://pony_server.com
-PB_SERVER = getattr(settings, 'PB_SERVER', '')
+PB_SERVER = getattr(settings, 'PB_SERVER', 'http://devmason.com/pony_server')
PB_USER = getattr(settings, 'PB_USER', '')
PB_PASS = getattr(settings, 'PB_PASS', '')
if PB_USER and PB_PASS:
PB_AUTH = "Basic %s" % ("%s:%s" % (PB_USER, PB_PASS)).encode("base64").strip()
else:
print "No auth provided."
PB_AUTH = None
-STARTED = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
+STARTED = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
def _insert_failure(failed_apps, app, failure):
if failed_apps.has_key(app):
failed_apps[app].append(failure)
else:
failed_apps[app] = [failure]
def _increment_app(all_apps, app):
if all_apps.has_key(app):
all_apps[app] += 1
else:
all_apps[app] = 1
def report_results_for_suite(suite, result):
failed_apps = {}
all_apps = {}
for test in suite._tests:
test_app = get_app_name_from_test(test)
_increment_app(all_apps, test_app)
for failure in result.failures + result.errors:
test = failure[0]
output = failure[1]
app = get_app_name_from_test(test)
_insert_failure(failed_apps, app, failure)
arch = get_arch()
hostname = socket.gethostname()
for app in all_apps:
success = app not in failed_apps.keys()
if app in failed_apps:
errout = '\n'.join([failure[1] for failure in failed_apps[app]])
else:
errout = "%s Passed" % all_apps[app]
build_dict = {'success': success,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
'tags': ['django_test_runner'],
'client': {
'arch': arch,
'host': hostname,
'user': PB_USER,
},
'results': [
{'success': success,
'name': 'Test Application',
'errout': errout,
'started': STARTED,
'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
}
]
}
create_package(PB_SERVER, app, auth=PB_AUTH)
send_results(PB_SERVER, app, build_dict, auth=PB_AUTH)
\ No newline at end of file
diff --git a/pony_utils/utils.py b/pony_utils/utils.py
index 84d3730..f849e29 100644
--- a/pony_utils/utils.py
+++ b/pony_utils/utils.py
@@ -1,67 +1,69 @@
try:
import json
except:
import simplejson
import httplib2
import distutils.util
import unicodedata
import re
+PB_SERVER = 'http://devmason.com/pony_server'
+
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '_', value).strip().lower())
return re.sub('[-\s]+', '-', value)
def get_app_name_from_test(test):
try:
#doctest
app = test._dt_test.name.split('.tests.')[0]
except AttributeError:
#unit test in tests
app = test.__module__.split('.tests.')[0]
if not app:
#Unit test in models.
app = test.__module__.split('.models.')[0]
if not app:
app = test.__module__.split('.')[0]
return app
def get_arch():
return distutils.util.get_platform()
-def create_package(server, project, name=None, auth=None):
+def create_package(project, name=None, server=PB_SERVER, auth=None):
if not name:
name = project
print "Sending info for %s" % name
create_url = "%s/%s" % (server, slugify(unicode(project)))
json_payload = '{"name": "%s"}' % name
h = httplib2.Http()
resp, content = h.request(create_url, "PUT", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
-def send_results(server, project, result_dict, auth=None):
+def send_results(project, result_dict,server=PB_SERVER, auth=None):
post_url = "%s/%s/builds" % (server, slugify(unicode(project)))
json_payload = json.dumps(result_dict)
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=json_payload,
headers={'content-type':'application/json',
'AUTHORIZATION': auth}
)
-def send_build_request(server, project, identifier):
+def send_build_request(project, identifier=HEAD, server=PB_SERVER):
post_url = "%s/builds/request" % server
post_data = json.dumps({
'project': project,
'identifier': identifier,
})
h = httplib2.Http()
resp, content = h.request(post_url, "POST", body=post_data,
headers={'content-type':'application/json'}
)
|
ericholscher/devmason-utils
|
ecc17018cb5353b51802ca3c2d620433faf7e10d
|
Add the start of the codes!
|
diff --git a/pony_utils/__init__.py b/pony_utils/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/pony_utils/django/__init__.py b/pony_utils/django/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/pony_utils/django/test_runner.py b/pony_utils/django/test_runner.py
new file mode 100644
index 0000000..62d5c38
--- /dev/null
+++ b/pony_utils/django/test_runner.py
@@ -0,0 +1,62 @@
+import unittest
+from django.conf import settings
+from django.db.models import get_app, get_apps
+from django.test import _doctest as doctest
+from django.test.utils import setup_test_environment, teardown_test_environment
+from django.test.testcases import OutputChecker, DocTestRunner, TestCase
+from django.test.simple import *
+
+from pony_utils.django.utils import report_results_for_suite
+
+def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
+ """
+ Run the unit tests for all the test labels in the provided list.
+ Labels must be of the form:
+ - app.TestClass.test_method
+ Run a single specific test method
+ - app.TestClass
+ Run all the test methods in a given class
+ - app
+ Search for doctests and unittests in the named application.
+
+ When looking for tests, the test runner will look in the models and
+ tests modules for the application.
+
+ A list of 'extra' tests may also be provided; these tests
+ will be added to the test suite.
+
+ Returns the number of tests that failed.
+ """
+ setup_test_environment()
+
+ settings.DEBUG = False
+ suite = unittest.TestSuite()
+
+ if test_labels:
+ for label in test_labels:
+ if '.' in label:
+ suite.addTest(build_test(label))
+ else:
+ app = get_app(label)
+ suite.addTest(build_suite(app))
+ else:
+ for app in get_apps():
+ #run_tests(build_suite(app))
+ suite.addTest(build_suite(app))
+
+ for test in extra_tests:
+ suite.addTest(test)
+
+ suite = reorder_suite(suite, (TestCase,))
+
+ old_name = settings.DATABASE_NAME
+ from django.db import connection
+ connection.creation.create_test_db(verbosity, autoclobber=not interactive)
+ result = unittest.TextTestRunner(verbosity=verbosity).run(suite)
+ connection.creation.destroy_test_db(old_name, verbosity)
+
+ teardown_test_environment()
+
+ report_results_for_suite(suite, result)
+
+ return len(result.failures) + len(result.errors)
diff --git a/pony_utils/django/utils.py b/pony_utils/django/utils.py
new file mode 100644
index 0000000..7ebb207
--- /dev/null
+++ b/pony_utils/django/utils.py
@@ -0,0 +1,72 @@
+from django.conf import settings
+import datetime
+import socket
+
+from pony_utils.utils import create_package, send_results, get_arch, get_app_name_from_test
+
+#http://pony_server.com
+PB_SERVER = getattr(settings, 'PB_SERVER', '')
+PB_USER = getattr(settings, 'PB_USER', '')
+PB_PASS = getattr(settings, 'PB_PASS', '')
+if PB_USER and PB_PASS:
+ PB_AUTH = "Basic %s" % ("%s:%s" % (PB_USER, PB_PASS)).encode("base64").strip()
+else:
+ print "No auth provided."
+ PB_AUTH = None
+STARTED = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
+
+
+def _insert_failure(failed_apps, app, failure):
+ if failed_apps.has_key(app):
+ failed_apps[app].append(failure)
+ else:
+ failed_apps[app] = [failure]
+
+def _increment_app(all_apps, app):
+ if all_apps.has_key(app):
+ all_apps[app] += 1
+ else:
+ all_apps[app] = 1
+
+def report_results_for_suite(suite, result):
+ failed_apps = {}
+ all_apps = {}
+ for test in suite._tests:
+ test_app = get_app_name_from_test(test)
+ _increment_app(all_apps, test_app)
+ for failure in result.failures + result.errors:
+ test = failure[0]
+ output = failure[1]
+ app = get_app_name_from_test(test)
+ _insert_failure(failed_apps, app, failure)
+
+ arch = get_arch()
+ hostname = socket.gethostname()
+
+ for app in all_apps:
+ success = app not in failed_apps.keys()
+ if app in failed_apps:
+ errout = '\n'.join([failure[1] for failure in failed_apps[app]])
+ else:
+ errout = "%s Passed" % all_apps[app]
+ build_dict = {'success': success,
+ 'started': STARTED,
+ 'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
+ 'tags': ['django_test_runner'],
+ 'client': {
+ 'arch': arch,
+ 'host': hostname,
+ 'user': PB_USER,
+ },
+ 'results': [
+ {'success': success,
+ 'name': 'Test Application',
+ 'errout': errout,
+ 'started': STARTED,
+ 'finished': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
+ }
+ ]
+ }
+
+ create_package(PB_SERVER, app, auth=PB_AUTH)
+ send_results(PB_SERVER, app, build_dict, auth=PB_AUTH)
\ No newline at end of file
diff --git a/pony_utils/utils.py b/pony_utils/utils.py
new file mode 100644
index 0000000..84d3730
--- /dev/null
+++ b/pony_utils/utils.py
@@ -0,0 +1,67 @@
+try:
+ import json
+except:
+ import simplejson
+import httplib2
+import distutils.util
+import unicodedata
+import re
+
+def slugify(value):
+ """
+ Normalizes string, converts to lowercase, removes non-alpha characters,
+ and converts spaces to hyphens.
+ """
+ value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
+ value = unicode(re.sub('[^\w\s-]', '_', value).strip().lower())
+ return re.sub('[-\s]+', '-', value)
+
+def get_app_name_from_test(test):
+ try:
+ #doctest
+ app = test._dt_test.name.split('.tests.')[0]
+ except AttributeError:
+ #unit test in tests
+ app = test.__module__.split('.tests.')[0]
+ if not app:
+ #Unit test in models.
+ app = test.__module__.split('.models.')[0]
+ if not app:
+ app = test.__module__.split('.')[0]
+ return app
+
+
+def get_arch():
+ return distutils.util.get_platform()
+
+def create_package(server, project, name=None, auth=None):
+ if not name:
+ name = project
+ print "Sending info for %s" % name
+ create_url = "%s/%s" % (server, slugify(unicode(project)))
+ json_payload = '{"name": "%s"}' % name
+ h = httplib2.Http()
+ resp, content = h.request(create_url, "PUT", body=json_payload,
+ headers={'content-type':'application/json',
+ 'AUTHORIZATION': auth}
+ )
+
+def send_results(server, project, result_dict, auth=None):
+ post_url = "%s/%s/builds" % (server, slugify(unicode(project)))
+ json_payload = json.dumps(result_dict)
+ h = httplib2.Http()
+ resp, content = h.request(post_url, "POST", body=json_payload,
+ headers={'content-type':'application/json',
+ 'AUTHORIZATION': auth}
+ )
+
+def send_build_request(server, project, identifier):
+ post_url = "%s/builds/request" % server
+ post_data = json.dumps({
+ 'project': project,
+ 'identifier': identifier,
+ })
+ h = httplib2.Http()
+ resp, content = h.request(post_url, "POST", body=post_data,
+ headers={'content-type':'application/json'}
+ )
|
ericholscher/devmason-utils
|
417e98171da51783e035f41d0580db6a110586e0
|
Add readme
|
diff --git a/README b/README
new file mode 100644
index 0000000..d3ac787
--- /dev/null
+++ b/README
@@ -0,0 +1 @@
+This is where we put all the utils for playing with ponies, in the clouds.
|
ericholscher/devmason-utils
|
ef08de7a33032cf5f49e5fcd2f4efc14ae4c4f1f
|
Add gitignore
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..bd3b7af
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+*.pyc
+build/
+dist/
+*.egg-info
\ No newline at end of file
|
saces/SchwachkopfEinsteck
|
f39b03f4ad6e62dc388b5d2383c6bb4715b58dd6
|
API fixes
|
diff --git a/src/plugins/schwachkopfeinsteck/ReposInserter1.java b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
index b86e23d..90a5d1a 100644
--- a/src/plugins/schwachkopfeinsteck/ReposInserter1.java
+++ b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
@@ -1,197 +1,197 @@
package plugins.schwachkopfeinsteck;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectDatabase;
import org.eclipse.jgit.lib.ObjectDirectory;
import org.eclipse.jgit.lib.PackFile;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.RefAdvertiser;
import freenet.client.InsertContext;
import freenet.client.async.BaseManifestPutter;
+import freenet.client.async.ClientContext;
import freenet.client.async.ClientPutCallback;
-import freenet.client.async.ManifestElement;
+import freenet.client.async.TooManyFilesInsertException;
import freenet.keys.FreenetURI;
-import freenet.node.RequestClient;
-import freenet.support.api.Bucket;
+import freenet.support.api.ManifestElement;
+import freenet.support.api.RandomAccessBucket;
import freenet.support.io.ArrayBucket;
import freenet.support.io.BucketTools;
import freenet.support.io.Closer;
import freenet.support.io.TempBucketFactory;
public class ReposInserter1 extends BaseManifestPutter {
public ReposInserter1(ClientPutCallback cb,
HashMap<String, FreenetURI> packList, File reposDir, Repository db, short prioClass,
FreenetURI target, String defaultName, InsertContext ctx,
- boolean getCHKOnly2, RequestClient clientContext,
- boolean earlyEncode, TempBucketFactory tempBucketFactory) {
- super(cb, paramTrick(packList, reposDir, db, tempBucketFactory), prioClass, target, defaultName, ctx, getCHKOnly2,
- clientContext, earlyEncode);
+ ClientContext clientContext,
+ TempBucketFactory tempBucketFactory, boolean randomiseCryptoKeys, byte[] forceCryptoKey) throws TooManyFilesInsertException {
+ super(cb, paramTrick(packList, reposDir, db, tempBucketFactory), prioClass, target, defaultName, ctx, randomiseCryptoKeys, forceCryptoKey, clientContext);
}
private static HashMap<String, Object> paramTrick(HashMap<String, FreenetURI> packList, File reposDir, Repository db, TempBucketFactory tbf) {
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("rDir", reposDir);
result.put("tbf", tbf);
result.put("db", db);
result.put("packList", packList);
return result;
}
@Override
protected void makePutHandlers(HashMap<String, Object> manifestElements,
String defaultName) {
File reposDir = (File) manifestElements.get("rDir");
TempBucketFactory tbf = (TempBucketFactory) manifestElements.get("tbf");
Repository db = (Repository) manifestElements.get("db");
HashMap<String, FreenetURI> packList = (HashMap<String, FreenetURI>) manifestElements.get("packList");
// make the default page
String defaultText = "This is a git repository.";
- Bucket b = new ArrayBucket(defaultText.getBytes());
+ RandomAccessBucket b = new ArrayBucket(defaultText.getBytes());
ManifestElement defaultItem = new ManifestElement("defaultText", b, "text/plain", b.size());
freenet.client.async.BaseManifestPutter.ContainerBuilder container = getRootContainer();
container.addItem("defaultText", defaultItem, true);
// generate info files for dumb servers (fproxy)
container.pushCurrentDir();
container.pushCurrentDir();
try {
// info/refs
- Bucket refs = generateInfoRefs(db, tbf);
+ RandomAccessBucket refs = generateInfoRefs(db, tbf);
ManifestElement refsItem = new ManifestElement("refs", refs, "text/plain", refs.size());
container.makeSubDirCD("info");
container.addItem("refs", refsItem, false);
container.popCurrentDir();
// objects/info/packs
- Bucket packs = generateObjectsInfoPacks(db, tbf);
+ RandomAccessBucket packs = generateObjectsInfoPacks(db, tbf);
ManifestElement packsItem = new ManifestElement("packs", packs, "text/plain", packs.size());
container.makeSubDirCD("objects");
container.makeSubDirCD("info");
container.addItem("packs", packsItem, false);
container.popCurrentDir();
parseDir(reposDir, container, tbf, false, packList);
} catch (IOException e) {
e.printStackTrace();
throw new Error(e);
}
}
- private Bucket generateInfoRefs(Repository db, TempBucketFactory tbf) throws IOException {
- Bucket result = tbf.makeBucket(-1);
+ private RandomAccessBucket generateInfoRefs(Repository db, TempBucketFactory tbf) throws IOException {
+ RandomAccessBucket result = tbf.makeBucket(-1);
final RevWalk walk = new RevWalk(db);
final RevFlag ADVERTISED = walk.newFlag("ADVERTISED");
final OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(result.getOutputStream()), Constants.CHARSET);
final RefAdvertiser adv = new RefAdvertiser() {
@Override
protected void writeOne(final CharSequence line) throws IOException {
// Whoever decided that info/refs should use a different
// delimiter than the native git:// protocol shouldn't
// be allowed to design this sort of stuff. :-(
out.append(line.toString().replace(' ', '\t'));
}
@Override
protected void end() {
// No end marker required for info/refs format.
}
};
adv.init(walk, ADVERTISED);
adv.setDerefTags(true);
Map<String, Ref> refs = db.getAllRefs();
refs.remove(Constants.HEAD);
adv.send(refs);
out.close();
result.setReadOnly();
return result;
}
- private Bucket generateObjectsInfoPacks(Repository db, TempBucketFactory tbf) throws IOException {
- Bucket result = tbf.makeBucket(-1);
+ private RandomAccessBucket generateObjectsInfoPacks(Repository db, TempBucketFactory tbf) throws IOException {
+ RandomAccessBucket result = tbf.makeBucket(-1);
final OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(result.getOutputStream()), Constants.CHARSET);
final ObjectDatabase ob = db.getObjectDatabase();
if (ob instanceof ObjectDirectory) {
for (PackFile pack : ((ObjectDirectory) ob).getPacks()) {
out.append("P ");
out.append(pack.getPackFile().getName());
out.append('\n');
}
}
out.append('\n');
out.close();
result.setReadOnly();
return result;
}
private void parseDir(File dir, ContainerBuilder container, TempBucketFactory tbf, boolean checkPack, HashMap<String, FreenetURI> packList) throws IOException {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
container.pushCurrentDir();
container.makeSubDirCD(file.getName());
if (checkPack && file.getName().equals("pack")) {
parsePackList(file, packList, container, tbf);
} else {
parseDir(file, container, tbf, (file.getName().equals("objects")), packList);
}
container.popCurrentDir();
} else {
addFile(file, container, tbf);
}
}
}
private void parsePackList(File dir, HashMap<String, FreenetURI> packList, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
File[] files = dir.listFiles();
for (File file : files) {
String name = file.getName();
if (packList.containsKey(name)) {
FreenetURI target = packList.get(name);
ManifestElement me = new ManifestElement(file.getName(), target, "text/plain");
container.addItem(file.getName(), me, false);
} else {
addFile(file, container, tbf);
}
}
}
private void addFile(File file, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
- Bucket b = makeBucket(file, tbf);
+ RandomAccessBucket b = makeBucket(file, tbf);
ManifestElement me = new ManifestElement(file.getName(), b, "text/plain", b.size());
container.addItem(file.getName(), me, false);
}
- private Bucket makeBucket(File file, TempBucketFactory tbf) throws IOException {
- Bucket b = tbf.makeBucket(file.length());
+ private RandomAccessBucket makeBucket(File file, TempBucketFactory tbf) throws IOException {
+ RandomAccessBucket b = tbf.makeBucket(file.length());
InputStream is = new FileInputStream(file);
try {
BucketTools.copyFrom(b, is, Long.MAX_VALUE);
} catch (IOException e) {
Closer.close(b);
throw e;
} finally {
Closer.close(is);
}
b.setReadOnly();
return b;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/RepositoryManager.java b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
index 5f29656..b3d8826 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoryManager.java
+++ b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
@@ -1,314 +1,338 @@
package plugins.schwachkopfeinsteck;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.WeakHashMap;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.jgit.lib.Repository;
-import com.db4o.ObjectContainer;
-
import freenet.client.FetchContext;
import freenet.client.FetchException;
import freenet.client.FetchWaiter;
import freenet.client.InsertContext;
import freenet.client.InsertException;
import freenet.client.Metadata;
import freenet.client.async.ClientContext;
import freenet.client.async.ClientGetter;
import freenet.client.async.ClientRequester;
-import freenet.client.async.DatabaseDisabledException;
+import freenet.client.async.PersistenceDisabledException;
import freenet.client.async.SnoopMetadata;
+import freenet.client.async.TooManyFilesInsertException;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
import freenet.node.RequestStarter;
import freenet.support.Fields;
import freenet.support.Logger;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
public class RepositoryManager {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
public static class RepositoryWrapper {
public final String name;
public final Repository db;
public final ReentrantReadWriteLock rwLock;
RepositoryWrapper(String name2, Repository db2, ReentrantReadWriteLock rwLock2) {
name = name2;
db = db2;
rwLock = rwLock2;
}
}
private final PluginContext pluginContext;
private final File cacheDir;
private final WeakHashMap<String, ReentrantReadWriteLock> locks = new WeakHashMap<String, ReentrantReadWriteLock>();
private final WeakHashMap<String, Repository> dbCache = new WeakHashMap<String, Repository>();
private final HashMap<String, ClientRequester> jobs = new HashMap<String, ClientRequester>();
RepositoryManager(File cachedir, PluginContext plugincontext) {
cacheDir = cachedir;
pluginContext = plugincontext;
}
private ReentrantReadWriteLock getRRWLock(String name) {
ReentrantReadWriteLock result;
synchronized(locks) {
result = locks.get(name);
if (result == null) {
result = new ReentrantReadWriteLock(true);
locks.put(name, result);
}
}
return result;
}
private Repository internalGetRepository(String name) throws IOException {
Repository result;
synchronized(dbCache) {
result = dbCache.get(name);
if (result == null) {
File reposDir = new File(cacheDir, name);
if (!reposDir.exists()) {
return null;
}
result = new Repository(reposDir);
dbCache.put(name, result);
}
}
return result;
}
public RepositoryWrapper getRepository(String name) throws IOException {
Repository db = internalGetRepository(name);
if (db == null) {
return null;
}
ReentrantReadWriteLock lock = getRRWLock(name);
return new RepositoryWrapper(name, db, lock);
}
public static File ensureCacheDirExists(String dir) throws IOException {
File newDir = new File(dir);
if (newDir.exists()) {
if (!newDir.isDirectory()) {
throw new IOException("Not a directory: "+newDir.getAbsolutePath());
}
return newDir;
}
if (newDir.mkdirs()) {
return newDir;
}
throw new IOException("Unable to create cache directory: "+newDir.getAbsolutePath());
}
/**
* get the internal repository name from freenet uri.
* must be the request uri.
*/
public static String getRepositoryName(FreenetURI uri) {
String docName = uri.getDocName();
uri = uri.setKeyType("SSK");
String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
return new String(reposName + '@' + docName);
}
public String getCacheDir() {
return cacheDir.getPath();
}
public void deleteRepository(String reposName) {
ReentrantReadWriteLock lock = getRRWLock(reposName);
synchronized (lock) {
File repos = new File(cacheDir, reposName);
FileUtil.removeAll(repos);
}
}
public void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(cacheDir, repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
ReentrantReadWriteLock lock = getRRWLock(repos.getName());
synchronized (lock) {
File descfile = new File(repos, "description");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
}
private void updateEditionHint(File repos, long edition) throws IOException {
ReentrantReadWriteLock lock = getRRWLock(repos.getName());
synchronized (lock) {
File descfile = new File(repos, "EditionHint");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(Long.toString(edition).getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
}
private long getEditionHint(File repos) {
ReentrantReadWriteLock lock = getRRWLock(repos.getName());
- String hint;
+ StringBuilder hint;
synchronized (lock) {
File hintfile = new File(repos, "EditionHint");
if (!hintfile.exists()) {
return -1;
}
try {
hint = FileUtil.readUTF(hintfile);
} catch (IOException e) {
Logger.error(this, "Failed to read EditionHint for: "+repos.getName()+". Forcing full upload.");
return -1;
}
}
- return Fields.parseLong(hint, -1);
+ return Fields.parseLong(hint.toString(), -1);
}
private void tryCreateRepository(String reposName) throws IOException {
tryCreateRepository(reposName, null);
}
public void tryCreateRepository(String reposName, String description) throws IOException {
File reposDir = new File(cacheDir, reposName);
Repository repos;
repos = new Repository(reposDir);
repos.create(true);
if (description != null) {
updateDescription(reposDir, description);
}
}
@Deprecated
public File getCacheDirFile() {
return cacheDir;
}
public void kill() {
// TODO stopp lockking, kill all jobs.
// empty caches.
}
public FreenetURI insert(RepositoryWrapper rw, FreenetURI fetchURI, FreenetURI insertURI) throws InsertException {
File reposDir = new File(cacheDir, rw.name);
//get the edition hint
long hint = getEditionHint(reposDir);
HashMap<String, FreenetURI> packList = null;
if (hint > -1) {
// it seems the repository was inserted before, try to fetch the manifest to reuse the pack files
FreenetURI u = fetchURI.setSuggestedEdition(hint).sskForUSK();
packList = getPackList(u);
}
RequestClient rc = new RequestClient() {
+ @Override
public boolean persistent() {
return false;
}
- public void removeFrom(ObjectContainer container) {
+ @Override
+ public boolean realTimeFlag() {
+ return false;
}
};
+ ClientContext x = pluginContext.clientCore.clientContext;
InsertContext iCtx = pluginContext.hlsc.getInsertContext(true);
iCtx.compressorDescriptor = "LZMA";
- VerboseWaiter pw = new VerboseWaiter();
- ReposInserter1 dmp = new ReposInserter1(pw, packList, reposDir, rw.db, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
+ VerboseWaiter pw = new VerboseWaiter(rc);
+ ReposInserter1 dmp = null;
+ try {
+ dmp = new ReposInserter1(pw, packList, reposDir, rw.db, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, pluginContext.clientCore.clientContext, pluginContext.clientCore.tempBucketFactory, false, (byte[])null);
+ } catch (TooManyFilesInsertException e2) {
+ // TODO Auto-generated catch block
+ e2.printStackTrace();
+ }
+
iCtx.eventProducer.addEventListener(pw);
+
try {
pluginContext.clientCore.clientContext.start(dmp);
- } catch (DatabaseDisabledException e) {
- // Impossible
+ } catch (PersistenceDisabledException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
}
+
FreenetURI result;
try {
result = pw.waitForCompletion();
} finally {
iCtx.eventProducer.removeEventListener(pw);
}
try {
updateEditionHint(reposDir, result.getEdition());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static class Snooper implements SnoopMetadata {
private Metadata metaData;
Snooper() {
}
- public boolean snoopMetadata(Metadata meta, ObjectContainer container, ClientContext context) {
+ public boolean snoopMetadata(Metadata meta, ClientContext context) {
if (meta.isSimpleManifest()) {
metaData = meta;
return true;
}
return false;
}
}
// get the fragment 'pack files list' from metadata, expect a ssk
private HashMap<String, FreenetURI> getPackList(FreenetURI uri) {
+ RequestClient rc = new RequestClient() {
+ @Override
+ public boolean persistent() {
+ return false;
+ }
+ @Override
+ public boolean realTimeFlag() {
+ return false;
+ }
+
+ };
// get the list for reusing pack files
Snooper snooper = new Snooper();
FetchContext context = pluginContext.hlsc.getFetchContext();
- FetchWaiter fw = new FetchWaiter();
- ClientGetter get = new ClientGetter(fw, uri.setMetaString(new String[]{"fake"}), context, RequestStarter.INTERACTIVE_PRIORITY_CLASS, (RequestClient)pluginContext.hlsc, null, null);
+ FetchWaiter fw = new FetchWaiter(rc);
+ ClientGetter get = new ClientGetter(fw, uri.setMetaString(new String[]{"fake"}), context, RequestStarter.INTERACTIVE_PRIORITY_CLASS, null);
get.setMetaSnoop(snooper);
try {
- get.start(null, pluginContext.clientCore.clientContext);
+ get.start(pluginContext.clientCore.clientContext);
fw.waitForCompletion();
} catch (FetchException e) {
Logger.error(this, "Fetch failure.", e);
}
if (snooper.metaData == null) {
// nope. force a full insert
return null;
}
HashMap<String, Metadata> list;
try {
// FIXME deal with MultiLevelMetadata, the pack dir can get huge
list = snooper.metaData.getDocument("objects").getDocument("pack").getDocuments();
} catch (Throwable t) {
Logger.error(this, "Error transforming metadata, really a git repository? Or a Bug/MissingFeature.", t);
return null;
}
HashMap<String, FreenetURI> result = new HashMap<String, FreenetURI>();
for (Entry<String, Metadata> e:list.entrySet()) {
String n = e.getKey();
Metadata m = e.getValue();
if (m.isSingleFileRedirect()) {
// already a redirect, reuse it
FreenetURI u = m.getSingleTarget();
result.put(n, u);
} else {
FreenetURI u = uri.setMetaString(new String[]{"objects", "pack", n});
result.put(n, u);
}
}
return result;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/VerboseWaiter.java b/src/plugins/schwachkopfeinsteck/VerboseWaiter.java
index f7d8339..e84dafc 100644
--- a/src/plugins/schwachkopfeinsteck/VerboseWaiter.java
+++ b/src/plugins/schwachkopfeinsteck/VerboseWaiter.java
@@ -1,39 +1,46 @@
package plugins.schwachkopfeinsteck;
import com.db4o.ObjectContainer;
import freenet.client.PutWaiter;
import freenet.client.async.BaseClientPutter;
import freenet.client.async.ClientContext;
import freenet.client.events.ClientEvent;
import freenet.client.events.ClientEventListener;
import freenet.keys.FreenetURI;
+import freenet.node.RequestClient;
import freenet.support.Logger;
public class VerboseWaiter extends PutWaiter implements ClientEventListener {
- public VerboseWaiter() {
- super();
+ public VerboseWaiter(RequestClient client) {
+ super(client);
}
@Override
- public void onFetchable(BaseClientPutter state, ObjectContainer container) {
+ public void onFetchable(BaseClientPutter state) {
Logger.error(this, "Put fetchable");
- super.onFetchable(state, container);
+ super.onFetchable(state);
}
@Override
- public synchronized void onGeneratedURI(FreenetURI uri, BaseClientPutter state, ObjectContainer container) {
+ public synchronized void onGeneratedURI(FreenetURI uri, BaseClientPutter state) {
Logger.error(this, "Got UriGenerated: "+uri.toString(false, false));
- super.onGeneratedURI(uri, state, container);
+ super.onGeneratedURI(uri, state);
}
public void onRemoveEventProducer(ObjectContainer container) {
Logger.error(this, "TODO", new Exception("TODO"));
}
public void receive(ClientEvent ce, ObjectContainer maybeContainer, ClientContext context) {
Logger.error(this, "Progress: "+ce.getDescription());
}
+
+ @Override
+ public void receive(ClientEvent ce, ClientContext context) {
+ // TODO Auto-generated method stub
+ Logger.error(this, "TODO ClientEvent", new Exception("TODO"));
+ }
}
diff --git a/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
index 2694587..d201cb5 100644
--- a/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
@@ -1,397 +1,397 @@
package plugins.schwachkopfeinsteck.toadlets;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import plugins.schwachkopfeinsteck.GitPlugin;
import plugins.schwachkopfeinsteck.RepositoryManager;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.keys.FreenetURI;
import freenet.node.useralerts.SimpleUserAlert;
import freenet.node.useralerts.UserAlert;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
private static final String CMD_BROWSE = "browse";
private static final String CMD_CREATE = "create";
private static final String CMD_DELETE = "delete";
private static final String CMD_FORK = "fork";
private static final String CMD_SAVEDESCRIPTION = "save";
private static final String PARAM_DELETECONFIRM = "deleteconfirm";
private static final String PARAM_DESCRIPTION = "description";
private static final String PARAM_INSERTURI = "inserturi";
private static final String PARAM_NAME = "name";
private static final String PARAM_REPOSNAME = "reposuri";
private static final String PARAM_REQUESTURI = "requesturi";
private static final String PARAM_SOURCE = "source";
private static final String PARAM_URI = "uri";
private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
private final RepositoryManager repositoryManager;
// '/', ';', '?' are forbidden to not confuse the URL parser,
// all others are forbidden to prevent file system clashes
private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon, RepositoryManager repositorymanager) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
repositoryManager = repositorymanager;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
List<String> errors = new LinkedList<String>();
makeMainPage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makeMainPage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
try {
repositoryManager.updateDescription(repos, desc);
} catch (IOException e) {
e.printStackTrace();
errors.add("Error while updating description : "+e.getLocalizedMessage());
}
} else if (request.isPartSet(CMD_DELETE)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
if (request.isPartSet(PARAM_DELETECONFIRM)) {
repositoryManager.deleteRepository(repos);
} else {
makeDeleteConfirmPage(ctx, repos);
return;
}
} else if (request.isPartSet(CMD_CREATE)) {
String name = request.getPartAsString(PARAM_NAME, 1024);
String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
errors.add("Are you jokingly? Every field is empty.");
} else {
if ((rUri.length() == 0) && (iUri.length() == 0)) {
FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
iUri = kp[0].setDocName(null).toString(false, false);
rUri = kp[1].setDocName(null).toString(false, false);
errors.add("URI was empty, I generated one for you.");
}
name = sanitizeDocName(name, errors);
// TODO some more uri wodoo
// a bare fetch uri means import, a bare insert uri get its fetch uri added
// try to get name from uri if name is not given
// auto convert ssk
// etc pp
if (errors.size() == 0) {
tryCreateRepository(name, rUri, iUri, errors);
}
if (errors.size() > 0) {
makeCreatePage(ctx, name, rUri, iUri, errors);
return;
}
makeCreatedReposPage(ctx, name, rUri, iUri, errors);
return;
}
} else {
errors.add("Did not understand. Maybe not implemented jet? :P");
}
makeMainPage(ctx, errors);
}
private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, null, null, null);
makeForkBox(contentNode, null, null, null);
makeRepositoryBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeDeleteConfirmBox(contentNode, reposName);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeCreatedReposBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
boxForm.addChild("b", reposName);
boxForm.addChild("br");
boxForm.addChild("a", "href", path(), "Hell, NO!");
boxForm.addChild("#", "\u00a0");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
}
private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
box.addChild("#", "Created a new repository. Congratz!");
box.addChild("br");
box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+rUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
box.addChild("br");
box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+iUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
}
private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Request URI:\u00a0 ");
if (rUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (iUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
}
private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
if (source != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (uri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
}
private void makeRepositoryBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
File cacheDir = repositoryManager.getCacheDirFile();
File[] dirs = cacheDir.listFiles();
if (dirs.length == 0) {
box.addChild("#", "No repositories set up.");
return;
}
HTMLNode table = box.addChild("table", "width", "100%");
HTMLNode tableHead = table.addChild("thead");
HTMLNode tableRow = tableHead.addChild("tr");
HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
nextTableCell.addChild("#", "Name");
nextTableCell = tableRow.addChild("th");
nextTableCell.addChild("#", "Description");
for (File dir: dirs) {
HTMLNode htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeNameCell(dir));
htmlTableRow.addChild(makeDescriptionCell(dir));
htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeDeleteCell(dir));
htmlTableRow.addChild(makeEmptyCell());
htmlTableRow.addChild(makeForkCell(dir));
}
}
private HTMLNode makeEmptyCell() {
HTMLNode cell = new HTMLNode("td");
cell.addChild("#", "\u00a0");
return cell;
}
private HTMLNode makeNameCell(File repos) {
HTMLNode cell = new HTMLNode("td", "colspan", "3");
String dirName = repos.getName();
cell.addChild("b", dirName);
return cell;
}
private HTMLNode makeDescriptionCell(File repos) {
HTMLNode cell = new HTMLNode("td", "rowspan", "2");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
String desc = getReposDescription(repos);
if (desc != null) {
area.addChild("#", desc);
} else {
area.addChild("#", "\u00a0");
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
return cell;
}
private HTMLNode makeDeleteCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
return cell;
}
private HTMLNode makeForkCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
return cell;
}
private String getReposDescription(File dir) {
File descfile = new File(dir, "description");
if (!descfile.exists()) return "<Describe me!>";
- String desc;
+ StringBuilder desc;
try {
desc = FileUtil.readUTF(descfile);
} catch (IOException e) {
Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
return "Error: "+e.getLocalizedMessage();
}
- return desc;
+ return desc.toString();
}
private String getReposURI(File repos) {
return repos.getName();
}
private String getReposURI(String repos) {
return repos;
}
private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
String dirName = rUri + '@' + name;
try {
repositoryManager.tryCreateRepository(dirName, "add a description here");
} catch (IOException e) {
Logger.error(this, "Error while create repository: "+dirName, e);
errors.add(e.getLocalizedMessage());
return;
}
String alert = "Due lack of a better idea the URIs are noted here:\n"+
"Created Repository :"+dirName+"\n"+
"Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
"Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
pluginContext.clientCore.alerts.register(new SimpleUserAlert(true, "Repository created", alert, "Repository created", UserAlert.MINOR));
}
private String sanitizeDocName(String docName, List<String> errors) {
int len = docName.length();
for (int i=0 ; i<len ; i++) {
char c = docName.charAt(i);
if (forbiddenChars.contains(c)) {
errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
}
}
return docName;
}
}
|
saces/SchwachkopfEinsteck
|
7eb89b42860dd38d510dad2024706f25593e0249
|
remove unused/redundant parameter
|
diff --git a/src/plugins/schwachkopfeinsteck/RepositoryManager.java b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
index f5cd416..5f29656 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoryManager.java
+++ b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
@@ -1,314 +1,314 @@
package plugins.schwachkopfeinsteck;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.WeakHashMap;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.jgit.lib.Repository;
import com.db4o.ObjectContainer;
import freenet.client.FetchContext;
import freenet.client.FetchException;
import freenet.client.FetchWaiter;
import freenet.client.InsertContext;
import freenet.client.InsertException;
import freenet.client.Metadata;
import freenet.client.async.ClientContext;
import freenet.client.async.ClientGetter;
import freenet.client.async.ClientRequester;
import freenet.client.async.DatabaseDisabledException;
import freenet.client.async.SnoopMetadata;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
import freenet.node.RequestStarter;
import freenet.support.Fields;
import freenet.support.Logger;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
public class RepositoryManager {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
public static class RepositoryWrapper {
public final String name;
public final Repository db;
public final ReentrantReadWriteLock rwLock;
RepositoryWrapper(String name2, Repository db2, ReentrantReadWriteLock rwLock2) {
name = name2;
db = db2;
rwLock = rwLock2;
}
}
private final PluginContext pluginContext;
private final File cacheDir;
private final WeakHashMap<String, ReentrantReadWriteLock> locks = new WeakHashMap<String, ReentrantReadWriteLock>();
private final WeakHashMap<String, Repository> dbCache = new WeakHashMap<String, Repository>();
private final HashMap<String, ClientRequester> jobs = new HashMap<String, ClientRequester>();
RepositoryManager(File cachedir, PluginContext plugincontext) {
cacheDir = cachedir;
pluginContext = plugincontext;
}
private ReentrantReadWriteLock getRRWLock(String name) {
ReentrantReadWriteLock result;
synchronized(locks) {
result = locks.get(name);
if (result == null) {
result = new ReentrantReadWriteLock(true);
locks.put(name, result);
}
}
return result;
}
private Repository internalGetRepository(String name) throws IOException {
Repository result;
synchronized(dbCache) {
result = dbCache.get(name);
if (result == null) {
File reposDir = new File(cacheDir, name);
if (!reposDir.exists()) {
return null;
}
result = new Repository(reposDir);
dbCache.put(name, result);
}
}
return result;
}
public RepositoryWrapper getRepository(String name) throws IOException {
Repository db = internalGetRepository(name);
if (db == null) {
return null;
}
ReentrantReadWriteLock lock = getRRWLock(name);
return new RepositoryWrapper(name, db, lock);
}
public static File ensureCacheDirExists(String dir) throws IOException {
File newDir = new File(dir);
if (newDir.exists()) {
if (!newDir.isDirectory()) {
throw new IOException("Not a directory: "+newDir.getAbsolutePath());
}
return newDir;
}
if (newDir.mkdirs()) {
return newDir;
}
throw new IOException("Unable to create cache directory: "+newDir.getAbsolutePath());
}
/**
* get the internal repository name from freenet uri.
* must be the request uri.
*/
public static String getRepositoryName(FreenetURI uri) {
String docName = uri.getDocName();
uri = uri.setKeyType("SSK");
String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
return new String(reposName + '@' + docName);
}
public String getCacheDir() {
return cacheDir.getPath();
}
public void deleteRepository(String reposName) {
ReentrantReadWriteLock lock = getRRWLock(reposName);
synchronized (lock) {
File repos = new File(cacheDir, reposName);
FileUtil.removeAll(repos);
}
}
public void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(cacheDir, repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
ReentrantReadWriteLock lock = getRRWLock(repos.getName());
synchronized (lock) {
File descfile = new File(repos, "description");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
}
private void updateEditionHint(File repos, long edition) throws IOException {
ReentrantReadWriteLock lock = getRRWLock(repos.getName());
synchronized (lock) {
File descfile = new File(repos, "EditionHint");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(Long.toString(edition).getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
}
private long getEditionHint(File repos) {
ReentrantReadWriteLock lock = getRRWLock(repos.getName());
String hint;
synchronized (lock) {
File hintfile = new File(repos, "EditionHint");
if (!hintfile.exists()) {
return -1;
}
try {
hint = FileUtil.readUTF(hintfile);
} catch (IOException e) {
Logger.error(this, "Failed to read EditionHint for: "+repos.getName()+". Forcing full upload.");
return -1;
}
}
return Fields.parseLong(hint, -1);
}
private void tryCreateRepository(String reposName) throws IOException {
tryCreateRepository(reposName, null);
}
public void tryCreateRepository(String reposName, String description) throws IOException {
File reposDir = new File(cacheDir, reposName);
Repository repos;
repos = new Repository(reposDir);
repos.create(true);
if (description != null) {
updateDescription(reposDir, description);
}
}
@Deprecated
public File getCacheDirFile() {
return cacheDir;
}
public void kill() {
// TODO stopp lockking, kill all jobs.
// empty caches.
}
- public FreenetURI insert(RepositoryWrapper rw, FreenetURI fetchURI, FreenetURI insertURI, PluginContext pluginContext) throws InsertException {
+ public FreenetURI insert(RepositoryWrapper rw, FreenetURI fetchURI, FreenetURI insertURI) throws InsertException {
File reposDir = new File(cacheDir, rw.name);
//get the edition hint
long hint = getEditionHint(reposDir);
HashMap<String, FreenetURI> packList = null;
if (hint > -1) {
// it seems the repository was inserted before, try to fetch the manifest to reuse the pack files
FreenetURI u = fetchURI.setSuggestedEdition(hint).sskForUSK();
packList = getPackList(u);
}
RequestClient rc = new RequestClient() {
public boolean persistent() {
return false;
}
public void removeFrom(ObjectContainer container) {
}
};
InsertContext iCtx = pluginContext.hlsc.getInsertContext(true);
iCtx.compressorDescriptor = "LZMA";
VerboseWaiter pw = new VerboseWaiter();
ReposInserter1 dmp = new ReposInserter1(pw, packList, reposDir, rw.db, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
iCtx.eventProducer.addEventListener(pw);
try {
pluginContext.clientCore.clientContext.start(dmp);
} catch (DatabaseDisabledException e) {
// Impossible
}
FreenetURI result;
try {
result = pw.waitForCompletion();
} finally {
iCtx.eventProducer.removeEventListener(pw);
}
try {
updateEditionHint(reposDir, result.getEdition());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static class Snooper implements SnoopMetadata {
private Metadata metaData;
Snooper() {
}
public boolean snoopMetadata(Metadata meta, ObjectContainer container, ClientContext context) {
if (meta.isSimpleManifest()) {
metaData = meta;
return true;
}
return false;
}
}
// get the fragment 'pack files list' from metadata, expect a ssk
private HashMap<String, FreenetURI> getPackList(FreenetURI uri) {
// get the list for reusing pack files
Snooper snooper = new Snooper();
FetchContext context = pluginContext.hlsc.getFetchContext();
FetchWaiter fw = new FetchWaiter();
ClientGetter get = new ClientGetter(fw, uri.setMetaString(new String[]{"fake"}), context, RequestStarter.INTERACTIVE_PRIORITY_CLASS, (RequestClient)pluginContext.hlsc, null, null);
get.setMetaSnoop(snooper);
try {
get.start(null, pluginContext.clientCore.clientContext);
fw.waitForCompletion();
} catch (FetchException e) {
Logger.error(this, "Fetch failure.", e);
}
if (snooper.metaData == null) {
// nope. force a full insert
return null;
}
HashMap<String, Metadata> list;
try {
// FIXME deal with MultiLevelMetadata, the pack dir can get huge
list = snooper.metaData.getDocument("objects").getDocument("pack").getDocuments();
} catch (Throwable t) {
Logger.error(this, "Error transforming metadata, really a git repository? Or a Bug/MissingFeature.", t);
return null;
}
HashMap<String, FreenetURI> result = new HashMap<String, FreenetURI>();
for (Entry<String, Metadata> e:list.entrySet()) {
String n = e.getKey();
Metadata m = e.getValue();
if (m.isSingleFileRedirect()) {
// already a redirect, reuse it
FreenetURI u = m.getSingleTarget();
result.put(n, u);
} else {
FreenetURI u = uri.setMetaString(new String[]{"objects", "pack", n});
result.put(n, u);
}
}
return result;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
index d13bc70..4669423 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
@@ -1,34 +1,32 @@
package plugins.schwachkopfeinsteck.daemon;
import plugins.schwachkopfeinsteck.RepositoryManager;
import freenet.support.incubation.server.AbstractServer;
import freenet.support.incubation.server.AbstractService;
import freenet.support.plugins.helpers1.PluginContext;
public class AnonymousGitDaemon extends AbstractServer {
private boolean isReadOnly = true;
- private final PluginContext pluginContext;
private final RepositoryManager repositoryManager;
public AnonymousGitDaemon(String servername, RepositoryManager repositorymanager, PluginContext plugincontext) {
super(servername, plugincontext.node.executor);
- pluginContext = plugincontext;
repositoryManager = repositorymanager;
}
@Override
protected AbstractService getService() {
- return new AnonymousGitService(isReadOnly(), eXecutor, pluginContext, repositoryManager);
+ return new AnonymousGitService(isReadOnly(), eXecutor, repositoryManager);
}
public void setReadOnly(boolean readOnly) {
isReadOnly = readOnly;
}
public boolean isReadOnly() {
return isReadOnly;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index a4c57a1..33d1346 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,276 +1,274 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.PacketLineOut;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.UploadPack;
import plugins.schwachkopfeinsteck.RepositoryManager;
import plugins.schwachkopfeinsteck.RepositoryManager.RepositoryWrapper;
import freenet.client.InsertException;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableUSK;
import freenet.support.Executor;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
import freenet.support.plugins.helpers1.PluginContext;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private final boolean isReadOnly;
private final Executor eXecutor;
- private final PluginContext pluginContext;
private final RepositoryManager repositoryManager;
private static final long LOCK_TIMEOUT = 5;
private static final TimeUnit LOCK_TIMEUNIT = TimeUnit.SECONDS;
- public AnonymousGitService(boolean readOnly, Executor executor, PluginContext plugincontext, RepositoryManager repositorymanager) {
+ public AnonymousGitService(boolean readOnly, Executor executor, RepositoryManager repositorymanager) {
isReadOnly = readOnly;
eXecutor = executor;
- pluginContext = plugincontext;
repositoryManager = repositorymanager;
}
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
//System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
// adjust uri string
if (reposName.startsWith("/")) {
reposName = reposName.substring(1);
}
if (!reposName.endsWith("/")) {
reposName = reposName + '/';
}
// reposName is the uri
FreenetURI iUri = null;
FreenetURI rUri;
try {
rUri = new FreenetURI(reposName);
} catch (MalformedURLException e1) {
fatal(rawOut, "Not a valid Freenet URI: "+e1.getLocalizedMessage());
return;
}
if (!rUri.isUSK()) {
fatal(rawOut, "Repository uri must be an USK.");
return;
}
// if it is an insert uri, get the request uri from it.
if(rUri.getExtra()[1] == 1) {
iUri = rUri;
InsertableUSK iUsk = InsertableUSK.createInsertable(rUri, false);
rUri = iUsk.getURI();
}
// reposName is the internal repository name
reposName = RepositoryManager.getRepositoryName(rUri);
RepositoryWrapper rw = repositoryManager.getRepository(reposName);
if (rw == null) {
fatal(rawOut, "No such repository.");
return;
}
try {
innerHandle(command, rw, rawIn, rawOut, rUri, iUri);
} catch (InterruptedException e) {
Logger.error(this, "Interrupted.", e);
fatal(rawOut, "Interrupted.");
}
}
private class LockWorkerThread extends Thread {
private volatile boolean recivedDone = false;
private final RepositoryWrapper rW;
private final InputStream rawIn;
private final OutputStream rawOut;
private String error = null;
private final FreenetURI fetchUri;
private final FreenetURI insertUri;
LockWorkerThread(RepositoryWrapper rw, InputStream rawin, OutputStream rawout, FreenetURI fetchuri, FreenetURI inserturi) {
rW = rw;
rawIn = rawin;
rawOut = rawout;
fetchUri = fetchuri;
insertUri = inserturi;
}
@Override
public void run() {
try {
innerRun();
} catch (InterruptedException e) {
Logger.error(this, "Interrupted.", e);
} catch (IOException e) {
Logger.error(this, "IO Error.", e);
}
}
private void innerRun() throws InterruptedException, IOException {
Lock lock = rW.rwLock.writeLock();
if (lock.tryLock() || lock.tryLock(LOCK_TIMEOUT, LOCK_TIMEUNIT)) {
boolean sucess = false;
boolean triggerUpload;
try {
triggerUpload = handleGitReceivePack(rW.db, rawIn, rawOut);
sucess = true;
} finally {
if (!sucess) {
lock.unlock();
}
recivedDone();
}
if (!triggerUpload) {
if (logMINOR) Logger.minor(this, "Nothing updated. Do not upload.");
lock.unlock();
return;
}
// downgrade from write to read lock
Lock newLock = rW.rwLock.readLock();
newLock.lock();
lock.unlock();
lock = newLock;
try {
- repositoryManager.insert(rW, fetchUri, insertUri, pluginContext);
+ repositoryManager.insert(rW, fetchUri, insertUri);
} catch (InsertException e) {
error = "Insert Failure: "+InsertException.getMessage(e.getMode());
Logger.error(this, error, e);
} finally {
lock.unlock();
}
} else {
error = "Was not able to obtain a write lock within 5 seconds.\nTry again later.";
recivedDone();
}
}
private synchronized void recivedDone() {
recivedDone = true;
notifyAll();
}
public synchronized void waitForReciveDone() {
while(!recivedDone) {
try {
wait();
} catch (InterruptedException e) {
// Ignore
}
}
}
}
private void innerHandle(String command, final RepositoryWrapper rw, InputStream rawIn, OutputStream rawOut, final FreenetURI rUri, final FreenetURI iUri) throws IOException, InterruptedException {
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Lock lock = rw.rwLock.readLock();
if (lock.tryLock() || lock.tryLock(LOCK_TIMEOUT, LOCK_TIMEUNIT)) {
try {
handleGitUploadPack(rw.db, rawIn, rawOut);
} finally {
lock.unlock();
}
} else {
fatal(rawOut, "Was not able to obtain a read lock within 5 seconds.\nTry again later.");
return;
}
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) {
fatal(rawOut, "Server is read only.");
return;
}
if (iUri == null) {
fatal(rawOut, "Try an insert uri for push.");
return;
}
LockWorkerThread t = new LockWorkerThread(rw, rawIn, rawOut, rUri, iUri);
eXecutor.execute(t);
t.waitForReciveDone();
if (t.error != null) {
fatal(rawOut, t.error);
}
} else {
Logger.error(this, "Unknown command: "+command);
fatal(rawOut, "Unknown command: "+command);
}
}
private void handleGitUploadPack(Repository db, InputStream rawIn, OutputStream rawOut) throws IOException {
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
}
private boolean handleGitReceivePack(final Repository db, InputStream rawIn, OutputStream rawOut) throws IOException {
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
try {
rp.getNewObjectIds();
} catch ( NullPointerException npe) {
return false;
}
return true;
}
private void fatal(OutputStream rawOut, String string) throws IOException {
PacketLineOut pckOut = new PacketLineOut(rawOut);
byte[] data = ("ERR "+string).getBytes();
pckOut.writePacket(data);
pckOut.flush();
rawOut.flush();
}
}
|
saces/SchwachkopfEinsteck
|
5ceba7ffe51afaa1518d250fe9c864888d3fe614
|
introduce incremental updates
|
diff --git a/src/plugins/schwachkopfeinsteck/GitPlugin.java b/src/plugins/schwachkopfeinsteck/GitPlugin.java
index 991f2ef..9489a64 100644
--- a/src/plugins/schwachkopfeinsteck/GitPlugin.java
+++ b/src/plugins/schwachkopfeinsteck/GitPlugin.java
@@ -1,96 +1,96 @@
package plugins.schwachkopfeinsteck;
import java.io.File;
import java.io.IOException;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import plugins.schwachkopfeinsteck.toadlets.AdminToadlet;
import plugins.schwachkopfeinsteck.toadlets.BrowseToadlet;
import plugins.schwachkopfeinsteck.toadlets.RepositoriesToadlet;
import freenet.l10n.BaseL10n.LANGUAGE;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginRealVersioned;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Logger;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterface;
public class GitPlugin implements FredPlugin, FredPluginL10n, FredPluginThreadless, FredPluginVersioned, FredPluginRealVersioned {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
public static final String PLUGIN_URI = "/GitPlugin";
private static final String PLUGIN_CATEGORY = "Git Tools";
public static final String PLUGIN_TITLE = "Git Plugin";
private PluginContext pluginContext;
private WebInterface webInterface;
private AnonymousGitDaemon simpleDaemon;
private RepositoryManager repositoryManager;
public void runPlugin(PluginRespirator pluginRespirator) {
pluginContext = new PluginContext(pluginRespirator);
final File cacheDir;
try {
cacheDir = RepositoryManager.ensureCacheDirExists("./gitcache");
} catch (IOException e) {
// It makes really no sense without cache, blow away.
throw new Error(e);
}
- repositoryManager = new RepositoryManager(cacheDir);
+ repositoryManager = new RepositoryManager(cacheDir, pluginContext);
// for now a single server only, later versions can do multiple servers
// and each can have its own cache/config
simpleDaemon = new AnonymousGitDaemon("huhu", repositoryManager, pluginContext);
webInterface = new WebInterface(pluginContext);
webInterface.addNavigationCategory(PLUGIN_URI+"/", PLUGIN_CATEGORY, "Git Toolbox", this);
// Visible pages
BrowseToadlet browseToadlet = new BrowseToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(browseToadlet, PLUGIN_CATEGORY, "Browse", "Browse a git repository like GitWeb");
AdminToadlet adminToadlet = new AdminToadlet(pluginContext, simpleDaemon, repositoryManager);
webInterface.registerVisible(adminToadlet, PLUGIN_CATEGORY, "Admin", "Admin the git server");
RepositoriesToadlet reposToadlet = new RepositoriesToadlet(pluginContext, simpleDaemon, repositoryManager);
webInterface.registerVisible(reposToadlet, PLUGIN_CATEGORY, "Repositories", "Create & Delete server's repositories");
}
public void terminate() {
if (simpleDaemon.isRunning())
simpleDaemon.stop();
simpleDaemon = null;
webInterface.kill();
webInterface = null;
repositoryManager.kill();
repositoryManager = null;
}
public String getString(String key) {
// return the key for now, l10n comes later
return key;
}
public void setLanguage(LANGUAGE newLanguage) {
// ignored for now, l10n comes later
}
public String getVersion() {
return Version.getLongVersionString();
}
public long getRealVersion() {
return Version.getRealVersion();
}
}
diff --git a/src/plugins/schwachkopfeinsteck/ReposInserter1.java b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
index af5a5af..b86e23d 100644
--- a/src/plugins/schwachkopfeinsteck/ReposInserter1.java
+++ b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
@@ -1,177 +1,197 @@
package plugins.schwachkopfeinsteck;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectDatabase;
import org.eclipse.jgit.lib.ObjectDirectory;
import org.eclipse.jgit.lib.PackFile;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.RefAdvertiser;
import freenet.client.InsertContext;
import freenet.client.async.BaseManifestPutter;
import freenet.client.async.ClientPutCallback;
import freenet.client.async.ManifestElement;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
import freenet.support.api.Bucket;
import freenet.support.io.ArrayBucket;
import freenet.support.io.BucketTools;
import freenet.support.io.Closer;
import freenet.support.io.TempBucketFactory;
public class ReposInserter1 extends BaseManifestPutter {
public ReposInserter1(ClientPutCallback cb,
- File reposDir, Repository db, short prioClass,
+ HashMap<String, FreenetURI> packList, File reposDir, Repository db, short prioClass,
FreenetURI target, String defaultName, InsertContext ctx,
boolean getCHKOnly2, RequestClient clientContext,
boolean earlyEncode, TempBucketFactory tempBucketFactory) {
- super(cb, paramTrick(reposDir, db, tempBucketFactory), prioClass, target, defaultName, ctx, getCHKOnly2,
+ super(cb, paramTrick(packList, reposDir, db, tempBucketFactory), prioClass, target, defaultName, ctx, getCHKOnly2,
clientContext, earlyEncode);
}
- private static HashMap<String, Object> paramTrick(File reposDir, Repository db, TempBucketFactory tbf) {
+ private static HashMap<String, Object> paramTrick(HashMap<String, FreenetURI> packList, File reposDir, Repository db, TempBucketFactory tbf) {
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("rDir", reposDir);
result.put("tbf", tbf);
result.put("db", db);
+ result.put("packList", packList);
return result;
}
@Override
protected void makePutHandlers(HashMap<String, Object> manifestElements,
String defaultName) {
File reposDir = (File) manifestElements.get("rDir");
TempBucketFactory tbf = (TempBucketFactory) manifestElements.get("tbf");
Repository db = (Repository) manifestElements.get("db");
+ HashMap<String, FreenetURI> packList = (HashMap<String, FreenetURI>) manifestElements.get("packList");
// make the default page
String defaultText = "This is a git repository.";
Bucket b = new ArrayBucket(defaultText.getBytes());
ManifestElement defaultItem = new ManifestElement("defaultText", b, "text/plain", b.size());
freenet.client.async.BaseManifestPutter.ContainerBuilder container = getRootContainer();
container.addItem("defaultText", defaultItem, true);
// generate info files for dumb servers (fproxy)
container.pushCurrentDir();
container.pushCurrentDir();
try {
// info/refs
Bucket refs = generateInfoRefs(db, tbf);
ManifestElement refsItem = new ManifestElement("refs", refs, "text/plain", refs.size());
container.makeSubDirCD("info");
container.addItem("refs", refsItem, false);
container.popCurrentDir();
// objects/info/packs
Bucket packs = generateObjectsInfoPacks(db, tbf);
ManifestElement packsItem = new ManifestElement("packs", packs, "text/plain", packs.size());
container.makeSubDirCD("objects");
container.makeSubDirCD("info");
container.addItem("packs", packsItem, false);
container.popCurrentDir();
- parseDir(reposDir, container, tbf);
+ parseDir(reposDir, container, tbf, false, packList);
} catch (IOException e) {
e.printStackTrace();
throw new Error(e);
}
}
private Bucket generateInfoRefs(Repository db, TempBucketFactory tbf) throws IOException {
Bucket result = tbf.makeBucket(-1);
final RevWalk walk = new RevWalk(db);
final RevFlag ADVERTISED = walk.newFlag("ADVERTISED");
final OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(result.getOutputStream()), Constants.CHARSET);
final RefAdvertiser adv = new RefAdvertiser() {
@Override
protected void writeOne(final CharSequence line) throws IOException {
// Whoever decided that info/refs should use a different
// delimiter than the native git:// protocol shouldn't
// be allowed to design this sort of stuff. :-(
out.append(line.toString().replace(' ', '\t'));
}
@Override
protected void end() {
// No end marker required for info/refs format.
}
};
adv.init(walk, ADVERTISED);
adv.setDerefTags(true);
Map<String, Ref> refs = db.getAllRefs();
refs.remove(Constants.HEAD);
adv.send(refs);
out.close();
result.setReadOnly();
return result;
}
private Bucket generateObjectsInfoPacks(Repository db, TempBucketFactory tbf) throws IOException {
Bucket result = tbf.makeBucket(-1);
final OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(result.getOutputStream()), Constants.CHARSET);
final ObjectDatabase ob = db.getObjectDatabase();
if (ob instanceof ObjectDirectory) {
for (PackFile pack : ((ObjectDirectory) ob).getPacks()) {
out.append("P ");
out.append(pack.getPackFile().getName());
out.append('\n');
}
}
out.append('\n');
out.close();
result.setReadOnly();
return result;
}
- private void parseDir(File dir, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
+ private void parseDir(File dir, ContainerBuilder container, TempBucketFactory tbf, boolean checkPack, HashMap<String, FreenetURI> packList) throws IOException {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
container.pushCurrentDir();
container.makeSubDirCD(file.getName());
- parseDir(file, container, tbf);
+ if (checkPack && file.getName().equals("pack")) {
+ parsePackList(file, packList, container, tbf);
+ } else {
+ parseDir(file, container, tbf, (file.getName().equals("objects")), packList);
+ }
container.popCurrentDir();
} else {
addFile(file, container, tbf);
}
}
}
+ private void parsePackList(File dir, HashMap<String, FreenetURI> packList, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
+ File[] files = dir.listFiles();
+ for (File file : files) {
+ String name = file.getName();
+ if (packList.containsKey(name)) {
+ FreenetURI target = packList.get(name);
+ ManifestElement me = new ManifestElement(file.getName(), target, "text/plain");
+ container.addItem(file.getName(), me, false);
+ } else {
+ addFile(file, container, tbf);
+ }
+ }
+ }
+
private void addFile(File file, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
Bucket b = makeBucket(file, tbf);
ManifestElement me = new ManifestElement(file.getName(), b, "text/plain", b.size());
container.addItem(file.getName(), me, false);
}
private Bucket makeBucket(File file, TempBucketFactory tbf) throws IOException {
Bucket b = tbf.makeBucket(file.length());
InputStream is = new FileInputStream(file);
try {
BucketTools.copyFrom(b, is, Long.MAX_VALUE);
} catch (IOException e) {
Closer.close(b);
throw e;
} finally {
Closer.close(is);
}
b.setReadOnly();
return b;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/RepositoryManager.java b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
index ea67ffe..f5cd416 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoryManager.java
+++ b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
@@ -1,217 +1,314 @@
package plugins.schwachkopfeinsteck;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.WeakHashMap;
+import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.jgit.lib.Repository;
import com.db4o.ObjectContainer;
+import freenet.client.FetchContext;
+import freenet.client.FetchException;
+import freenet.client.FetchWaiter;
import freenet.client.InsertContext;
import freenet.client.InsertException;
+import freenet.client.Metadata;
+import freenet.client.async.ClientContext;
+import freenet.client.async.ClientGetter;
import freenet.client.async.ClientRequester;
import freenet.client.async.DatabaseDisabledException;
+import freenet.client.async.SnoopMetadata;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
+import freenet.node.RequestStarter;
+import freenet.support.Fields;
import freenet.support.Logger;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
public class RepositoryManager {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
public static class RepositoryWrapper {
public final String name;
public final Repository db;
public final ReentrantReadWriteLock rwLock;
RepositoryWrapper(String name2, Repository db2, ReentrantReadWriteLock rwLock2) {
name = name2;
db = db2;
rwLock = rwLock2;
}
}
+ private final PluginContext pluginContext;
private final File cacheDir;
private final WeakHashMap<String, ReentrantReadWriteLock> locks = new WeakHashMap<String, ReentrantReadWriteLock>();
private final WeakHashMap<String, Repository> dbCache = new WeakHashMap<String, Repository>();
private final HashMap<String, ClientRequester> jobs = new HashMap<String, ClientRequester>();
- RepositoryManager(File cachedir) {
+ RepositoryManager(File cachedir, PluginContext plugincontext) {
cacheDir = cachedir;
+ pluginContext = plugincontext;
}
private ReentrantReadWriteLock getRRWLock(String name) {
ReentrantReadWriteLock result;
synchronized(locks) {
result = locks.get(name);
if (result == null) {
result = new ReentrantReadWriteLock(true);
locks.put(name, result);
}
}
return result;
}
private Repository internalGetRepository(String name) throws IOException {
Repository result;
synchronized(dbCache) {
result = dbCache.get(name);
if (result == null) {
File reposDir = new File(cacheDir, name);
if (!reposDir.exists()) {
return null;
}
result = new Repository(reposDir);
dbCache.put(name, result);
}
}
return result;
}
public RepositoryWrapper getRepository(String name) throws IOException {
Repository db = internalGetRepository(name);
if (db == null) {
return null;
}
ReentrantReadWriteLock lock = getRRWLock(name);
return new RepositoryWrapper(name, db, lock);
}
public static File ensureCacheDirExists(String dir) throws IOException {
File newDir = new File(dir);
if (newDir.exists()) {
if (!newDir.isDirectory()) {
throw new IOException("Not a directory: "+newDir.getAbsolutePath());
}
return newDir;
}
if (newDir.mkdirs()) {
return newDir;
}
throw new IOException("Unable to create cache directory: "+newDir.getAbsolutePath());
}
/**
* get the internal repository name from freenet uri.
* must be the request uri.
*/
public static String getRepositoryName(FreenetURI uri) {
String docName = uri.getDocName();
uri = uri.setKeyType("SSK");
String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
return new String(reposName + '@' + docName);
}
public String getCacheDir() {
return cacheDir.getPath();
}
public void deleteRepository(String reposName) {
ReentrantReadWriteLock lock = getRRWLock(reposName);
synchronized (lock) {
File repos = new File(cacheDir, reposName);
FileUtil.removeAll(repos);
}
}
public void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(cacheDir, repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
ReentrantReadWriteLock lock = getRRWLock(repos.getName());
synchronized (lock) {
File descfile = new File(repos, "description");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
}
private void updateEditionHint(File repos, long edition) throws IOException {
ReentrantReadWriteLock lock = getRRWLock(repos.getName());
synchronized (lock) {
File descfile = new File(repos, "EditionHint");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(Long.toString(edition).getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
}
+ private long getEditionHint(File repos) {
+ ReentrantReadWriteLock lock = getRRWLock(repos.getName());
+ String hint;
+ synchronized (lock) {
+ File hintfile = new File(repos, "EditionHint");
+ if (!hintfile.exists()) {
+ return -1;
+ }
+ try {
+ hint = FileUtil.readUTF(hintfile);
+ } catch (IOException e) {
+ Logger.error(this, "Failed to read EditionHint for: "+repos.getName()+". Forcing full upload.");
+ return -1;
+ }
+ }
+ return Fields.parseLong(hint, -1);
+ }
+
private void tryCreateRepository(String reposName) throws IOException {
tryCreateRepository(reposName, null);
}
public void tryCreateRepository(String reposName, String description) throws IOException {
File reposDir = new File(cacheDir, reposName);
Repository repos;
repos = new Repository(reposDir);
repos.create(true);
if (description != null) {
updateDescription(reposDir, description);
}
}
@Deprecated
public File getCacheDirFile() {
return cacheDir;
}
public void kill() {
// TODO stopp lockking, kill all jobs.
// empty caches.
}
public FreenetURI insert(RepositoryWrapper rw, FreenetURI fetchURI, FreenetURI insertURI, PluginContext pluginContext) throws InsertException {
+ File reposDir = new File(cacheDir, rw.name);
+
+ //get the edition hint
+ long hint = getEditionHint(reposDir);
+ HashMap<String, FreenetURI> packList = null;
+ if (hint > -1) {
+ // it seems the repository was inserted before, try to fetch the manifest to reuse the pack files
+ FreenetURI u = fetchURI.setSuggestedEdition(hint).sskForUSK();
+ packList = getPackList(u);
+ }
+
RequestClient rc = new RequestClient() {
public boolean persistent() {
return false;
}
public void removeFrom(ObjectContainer container) {
}
};
InsertContext iCtx = pluginContext.hlsc.getInsertContext(true);
iCtx.compressorDescriptor = "LZMA";
VerboseWaiter pw = new VerboseWaiter();
- File reposDir = new File(cacheDir, rw.name);
- ReposInserter1 dmp = new ReposInserter1(pw, reposDir, rw.db, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
+ ReposInserter1 dmp = new ReposInserter1(pw, packList, reposDir, rw.db, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
iCtx.eventProducer.addEventListener(pw);
try {
pluginContext.clientCore.clientContext.start(dmp);
} catch (DatabaseDisabledException e) {
// Impossible
}
FreenetURI result;
try {
result = pw.waitForCompletion();
} finally {
iCtx.eventProducer.removeEventListener(pw);
}
try {
updateEditionHint(reposDir, result.getEdition());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
-
+
+ public static class Snooper implements SnoopMetadata {
+ private Metadata metaData;
+
+ Snooper() {
+ }
+
+ public boolean snoopMetadata(Metadata meta, ObjectContainer container, ClientContext context) {
+ if (meta.isSimpleManifest()) {
+ metaData = meta;
+ return true;
+ }
+ return false;
+ }
+ }
+
+ // get the fragment 'pack files list' from metadata, expect a ssk
+ private HashMap<String, FreenetURI> getPackList(FreenetURI uri) {
+ // get the list for reusing pack files
+ Snooper snooper = new Snooper();
+ FetchContext context = pluginContext.hlsc.getFetchContext();
+ FetchWaiter fw = new FetchWaiter();
+ ClientGetter get = new ClientGetter(fw, uri.setMetaString(new String[]{"fake"}), context, RequestStarter.INTERACTIVE_PRIORITY_CLASS, (RequestClient)pluginContext.hlsc, null, null);
+ get.setMetaSnoop(snooper);
+ try {
+ get.start(null, pluginContext.clientCore.clientContext);
+ fw.waitForCompletion();
+ } catch (FetchException e) {
+ Logger.error(this, "Fetch failure.", e);
+ }
+
+ if (snooper.metaData == null) {
+ // nope. force a full insert
+ return null;
+ }
+ HashMap<String, Metadata> list;
+ try {
+ // FIXME deal with MultiLevelMetadata, the pack dir can get huge
+ list = snooper.metaData.getDocument("objects").getDocument("pack").getDocuments();
+ } catch (Throwable t) {
+ Logger.error(this, "Error transforming metadata, really a git repository? Or a Bug/MissingFeature.", t);
+ return null;
+ }
+ HashMap<String, FreenetURI> result = new HashMap<String, FreenetURI>();
+ for (Entry<String, Metadata> e:list.entrySet()) {
+ String n = e.getKey();
+ Metadata m = e.getValue();
+ if (m.isSingleFileRedirect()) {
+ // already a redirect, reuse it
+ FreenetURI u = m.getSingleTarget();
+ result.put(n, u);
+ } else {
+ FreenetURI u = uri.setMetaString(new String[]{"objects", "pack", n});
+ result.put(n, u);
+ }
+ }
+ return result;
+ }
}
|
saces/SchwachkopfEinsteck
|
04ed6bf0d545f18060a91b2fddbc0daa3cee5c7e
|
more RepositoryManager, introduce locking, minor misc
|
diff --git a/README b/README
index 58aa01d..b8048c2 100644
--- a/README
+++ b/README
@@ -1,90 +1,90 @@
SchwachkopfEinsteck
===================
'SchwachkopfEinsteck' is german, it just translates to 'GitPlugin' :)
Prebuilt version: http://github.com/saces/SchwachkopfEinsteck/downloads
Just load the latest, it should go intuitiveâ¦
Source Version for the impatient:
Clone/update the repository, cd into it, update submodules and type 'ant'.
Grab the plugin from dist/SchwachkopfEinsteck.jar and load itâ¦
get sources (a fresh clone):
get the super project
git clone git://github.com/saces/SchwachkopfEinsteck.git SchwachkopfEinsteck
cd SchwachkopfEinsteck
init and update submodules
git submodule init
git submodule update
update sources:
update the super project
git pull git://github.com/saces/SchwachkopfEinsteck.git
update submodules
git submodule update
build:
cd into the project root and type 'ant'.
The new created plugin will be dist/SchwachkopfEinsteck.jar
configuration:
After loading the plugin visit http://127.0.0.1:8888/GitPlugin/admin or
'Git Tools'->'Admin' in the menu. Adjust the host and port if needed
(usually this should not be necessary) and press 'Start'.
Using It:
GO! GO! GO!
go to http://127.0.0.1:8888/GitPlugin/repos (Menu->Git Tools->Repositories)
create a new repository.
copy the inserturi from sucess page
git remote add <pasteithere> myFreenetRepos
or
git remote add git://127.0.0.1:9418/USK@inserturi,ABC/name/0/ myFreenetRepos
now push to it
git push myFreenetRepos master
or
git push git://127.0.0.1:9418/USK@inserturi,ABC/name/0/
- fetch is work in progress, so you have to pull/fetch via fproxy for now
+ fetch is work in progress, so you have to pull/fetch remote repositories via fproxy for now
git clone http://127.0.0.1:8888/USK@requesturi,ADC/name/0/
git pull http://127.0.0.1:8888/USK@requesturi,ADC/name/0/
--obsolete--
Qualifying: (testing local repository creation, anonymous git transport)
go to http://127.0.0.1:8888/GitPlugin/repos (Menu->Git Tools->Repositories)
if any repository is left from warmup round, delete it
create a new repository.
for now the URIs are noted in the repository description.
git push git://127.0.0.1:9418/USK@crypticbitpuree,ABC/name/0/
git pull git://127.0.0.1:9418/USK@crypticbitpuree,ADC/name/0/
happy qualifying ;)
Warmup round: (testing the anonymous git transport)
create a bare repository in gitcache/test
cd <freenetdir>
mkdir gitcache
cd gitcache
mkdir test
cd test
git --bare init
the repository name ('test') is hardcoded for testing the anonymous git
transport. so any remote repository ends up in the repository you just
created.
git push git://127.0.0.1:9418/ignoredreposname
git pull git://127.0.0.1:9418/ignoredreposname
happy warm up testing ;)
TODO & Issues
=============
* local repository caching and locking
* implement synchronization from freenet to local cache (pull/fetch)
diff --git a/src/plugins/schwachkopfeinsteck/ReposInserter1.java b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
index e307ae0..af5a5af 100644
--- a/src/plugins/schwachkopfeinsteck/ReposInserter1.java
+++ b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
@@ -1,212 +1,177 @@
package plugins.schwachkopfeinsteck;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectDatabase;
import org.eclipse.jgit.lib.ObjectDirectory;
import org.eclipse.jgit.lib.PackFile;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.RefAdvertiser;
-import com.db4o.ObjectContainer;
-
import freenet.client.InsertContext;
-import freenet.client.InsertException;
import freenet.client.async.BaseManifestPutter;
import freenet.client.async.ClientPutCallback;
-import freenet.client.async.DatabaseDisabledException;
import freenet.client.async.ManifestElement;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
import freenet.support.api.Bucket;
import freenet.support.io.ArrayBucket;
import freenet.support.io.BucketTools;
import freenet.support.io.Closer;
import freenet.support.io.TempBucketFactory;
-import freenet.support.plugins.helpers1.PluginContext;
public class ReposInserter1 extends BaseManifestPutter {
public ReposInserter1(ClientPutCallback cb,
File reposDir, Repository db, short prioClass,
FreenetURI target, String defaultName, InsertContext ctx,
boolean getCHKOnly2, RequestClient clientContext,
boolean earlyEncode, TempBucketFactory tempBucketFactory) {
super(cb, paramTrick(reposDir, db, tempBucketFactory), prioClass, target, defaultName, ctx, getCHKOnly2,
clientContext, earlyEncode);
}
private static HashMap<String, Object> paramTrick(File reposDir, Repository db, TempBucketFactory tbf) {
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("rDir", reposDir);
result.put("tbf", tbf);
result.put("db", db);
return result;
}
@Override
protected void makePutHandlers(HashMap<String, Object> manifestElements,
String defaultName) {
File reposDir = (File) manifestElements.get("rDir");
TempBucketFactory tbf = (TempBucketFactory) manifestElements.get("tbf");
Repository db = (Repository) manifestElements.get("db");
// make the default page
String defaultText = "This is a git repository.";
Bucket b = new ArrayBucket(defaultText.getBytes());
ManifestElement defaultItem = new ManifestElement("defaultText", b, "text/plain", b.size());
freenet.client.async.BaseManifestPutter.ContainerBuilder container = getRootContainer();
container.addItem("defaultText", defaultItem, true);
// generate info files for dumb servers (fproxy)
container.pushCurrentDir();
container.pushCurrentDir();
try {
// info/refs
Bucket refs = generateInfoRefs(db, tbf);
ManifestElement refsItem = new ManifestElement("refs", refs, "text/plain", refs.size());
container.makeSubDirCD("info");
container.addItem("refs", refsItem, false);
container.popCurrentDir();
// objects/info/packs
Bucket packs = generateObjectsInfoPacks(db, tbf);
ManifestElement packsItem = new ManifestElement("packs", packs, "text/plain", packs.size());
container.makeSubDirCD("objects");
container.makeSubDirCD("info");
container.addItem("packs", packsItem, false);
container.popCurrentDir();
parseDir(reposDir, container, tbf);
} catch (IOException e) {
e.printStackTrace();
throw new Error(e);
}
}
private Bucket generateInfoRefs(Repository db, TempBucketFactory tbf) throws IOException {
Bucket result = tbf.makeBucket(-1);
final RevWalk walk = new RevWalk(db);
final RevFlag ADVERTISED = walk.newFlag("ADVERTISED");
final OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(result.getOutputStream()), Constants.CHARSET);
final RefAdvertiser adv = new RefAdvertiser() {
@Override
protected void writeOne(final CharSequence line) throws IOException {
// Whoever decided that info/refs should use a different
// delimiter than the native git:// protocol shouldn't
// be allowed to design this sort of stuff. :-(
out.append(line.toString().replace(' ', '\t'));
}
@Override
protected void end() {
// No end marker required for info/refs format.
}
};
adv.init(walk, ADVERTISED);
adv.setDerefTags(true);
Map<String, Ref> refs = db.getAllRefs();
refs.remove(Constants.HEAD);
adv.send(refs);
out.close();
result.setReadOnly();
return result;
}
private Bucket generateObjectsInfoPacks(Repository db, TempBucketFactory tbf) throws IOException {
Bucket result = tbf.makeBucket(-1);
final OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(result.getOutputStream()), Constants.CHARSET);
final ObjectDatabase ob = db.getObjectDatabase();
if (ob instanceof ObjectDirectory) {
for (PackFile pack : ((ObjectDirectory) ob).getPacks()) {
out.append("P ");
out.append(pack.getPackFile().getName());
out.append('\n');
}
}
out.append('\n');
out.close();
result.setReadOnly();
return result;
}
private void parseDir(File dir, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
container.pushCurrentDir();
container.makeSubDirCD(file.getName());
parseDir(file, container, tbf);
container.popCurrentDir();
} else {
addFile(file, container, tbf);
}
}
}
private void addFile(File file, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
Bucket b = makeBucket(file, tbf);
ManifestElement me = new ManifestElement(file.getName(), b, "text/plain", b.size());
container.addItem(file.getName(), me, false);
}
private Bucket makeBucket(File file, TempBucketFactory tbf) throws IOException {
Bucket b = tbf.makeBucket(file.length());
InputStream is = new FileInputStream(file);
try {
BucketTools.copyFrom(b, is, Long.MAX_VALUE);
} catch (IOException e) {
Closer.close(b);
throw e;
} finally {
Closer.close(is);
}
b.setReadOnly();
return b;
}
-
- public static FreenetURI insert(Repository db, File reposDir, FreenetURI insertURI, PluginContext pluginContext) throws InsertException {
- RequestClient rc = new RequestClient() {
- public boolean persistent() {
- return false;
- }
- public void removeFrom(ObjectContainer container) {
- }
-
- };
- InsertContext iCtx = pluginContext.hlsc.getInsertContext(true);
- iCtx.compressorDescriptor = "LZMA";
- VerboseWaiter pw = new VerboseWaiter();
- ReposInserter1 dmp = new ReposInserter1(pw, reposDir, db, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
- iCtx.eventProducer.addEventListener(pw);
- try {
- pluginContext.clientCore.clientContext.start(dmp);
- } catch (DatabaseDisabledException e) {
- // Impossible
- }
- FreenetURI result;
- try {
- result = pw.waitForCompletion();
- } finally {
- iCtx.eventProducer.removeEventListener(pw);
- }
- return result;
- }
-
-
}
diff --git a/src/plugins/schwachkopfeinsteck/RepositoryManager.java b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
index a1a378a..ea67ffe 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoryManager.java
+++ b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
@@ -1,87 +1,217 @@
package plugins.schwachkopfeinsteck;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import java.util.HashMap;
+import java.util.WeakHashMap;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.jgit.lib.Repository;
-import freenet.node.useralerts.SimpleUserAlert;
-import freenet.node.useralerts.UserAlert;
+import com.db4o.ObjectContainer;
+
+import freenet.client.InsertContext;
+import freenet.client.InsertException;
+import freenet.client.async.ClientRequester;
+import freenet.client.async.DatabaseDisabledException;
+import freenet.keys.FreenetURI;
+import freenet.node.RequestClient;
import freenet.support.Logger;
import freenet.support.io.FileUtil;
+import freenet.support.plugins.helpers1.PluginContext;
public class RepositoryManager {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
+ public static class RepositoryWrapper {
+ public final String name;
+ public final Repository db;
+ public final ReentrantReadWriteLock rwLock;
+
+ RepositoryWrapper(String name2, Repository db2, ReentrantReadWriteLock rwLock2) {
+ name = name2;
+ db = db2;
+ rwLock = rwLock2;
+ }
+ }
+
private final File cacheDir;
+ private final WeakHashMap<String, ReentrantReadWriteLock> locks = new WeakHashMap<String, ReentrantReadWriteLock>();
+ private final WeakHashMap<String, Repository> dbCache = new WeakHashMap<String, Repository>();
+ private final HashMap<String, ClientRequester> jobs = new HashMap<String, ClientRequester>();
RepositoryManager(File cachedir) {
cacheDir = cachedir;
}
+ private ReentrantReadWriteLock getRRWLock(String name) {
+ ReentrantReadWriteLock result;
+ synchronized(locks) {
+ result = locks.get(name);
+ if (result == null) {
+ result = new ReentrantReadWriteLock(true);
+ locks.put(name, result);
+ }
+ }
+ return result;
+ }
+
+ private Repository internalGetRepository(String name) throws IOException {
+ Repository result;
+ synchronized(dbCache) {
+ result = dbCache.get(name);
+ if (result == null) {
+ File reposDir = new File(cacheDir, name);
+ if (!reposDir.exists()) {
+ return null;
+ }
+ result = new Repository(reposDir);
+ dbCache.put(name, result);
+ }
+ }
+ return result;
+ }
+
+ public RepositoryWrapper getRepository(String name) throws IOException {
+ Repository db = internalGetRepository(name);
+ if (db == null) {
+ return null;
+ }
+ ReentrantReadWriteLock lock = getRRWLock(name);
+ return new RepositoryWrapper(name, db, lock);
+ }
+
public static File ensureCacheDirExists(String dir) throws IOException {
File newDir = new File(dir);
if (newDir.exists()) {
+ if (!newDir.isDirectory()) {
+ throw new IOException("Not a directory: "+newDir.getAbsolutePath());
+ }
return newDir;
}
if (newDir.mkdirs()) {
return newDir;
}
throw new IOException("Unable to create cache directory: "+newDir.getAbsolutePath());
}
+ /**
+ * get the internal repository name from freenet uri.
+ * must be the request uri.
+ */
+ public static String getRepositoryName(FreenetURI uri) {
+ String docName = uri.getDocName();
+ uri = uri.setKeyType("SSK");
+ String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
+ return new String(reposName + '@' + docName);
+ }
+
public String getCacheDir() {
return cacheDir.getPath();
}
public void deleteRepository(String reposName) {
- File repos = new File(cacheDir, reposName);
- FileUtil.removeAll(repos);
+ ReentrantReadWriteLock lock = getRRWLock(reposName);
+ synchronized (lock) {
+ File repos = new File(cacheDir, reposName);
+ FileUtil.removeAll(repos);
+ }
}
public void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(cacheDir, repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
- File descfile = new File(repos, "description");
- if (descfile.exists()) {
- descfile.delete();
+ ReentrantReadWriteLock lock = getRRWLock(repos.getName());
+ synchronized (lock) {
+ File descfile = new File(repos, "description");
+ if (descfile.exists()) {
+ descfile.delete();
+ }
+ InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
+ FileUtil.writeTo(is, descfile);
+ }
+ }
+
+ private void updateEditionHint(File repos, long edition) throws IOException {
+ ReentrantReadWriteLock lock = getRRWLock(repos.getName());
+ synchronized (lock) {
+ File descfile = new File(repos, "EditionHint");
+ if (descfile.exists()) {
+ descfile.delete();
+ }
+ InputStream is = new ByteArrayInputStream(Long.toString(edition).getBytes("UTF-8"));
+ FileUtil.writeTo(is, descfile);
}
- InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
- FileUtil.writeTo(is, descfile);
}
private void tryCreateRepository(String reposName) throws IOException {
tryCreateRepository(reposName, null);
}
public void tryCreateRepository(String reposName, String description) throws IOException {
File reposDir = new File(cacheDir, reposName);
Repository repos;
repos = new Repository(reposDir);
repos.create(true);
if (description != null) {
updateDescription(reposDir, description);
}
}
@Deprecated
public File getCacheDirFile() {
return cacheDir;
}
public void kill() {
// TODO stopp lockking, kill all jobs.
// empty caches.
}
+
+ public FreenetURI insert(RepositoryWrapper rw, FreenetURI fetchURI, FreenetURI insertURI, PluginContext pluginContext) throws InsertException {
+ RequestClient rc = new RequestClient() {
+ public boolean persistent() {
+ return false;
+ }
+ public void removeFrom(ObjectContainer container) {
+ }
+
+ };
+ InsertContext iCtx = pluginContext.hlsc.getInsertContext(true);
+ iCtx.compressorDescriptor = "LZMA";
+ VerboseWaiter pw = new VerboseWaiter();
+ File reposDir = new File(cacheDir, rw.name);
+ ReposInserter1 dmp = new ReposInserter1(pw, reposDir, rw.db, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
+ iCtx.eventProducer.addEventListener(pw);
+ try {
+ pluginContext.clientCore.clientContext.start(dmp);
+ } catch (DatabaseDisabledException e) {
+ // Impossible
+ }
+ FreenetURI result;
+ try {
+ result = pw.waitForCompletion();
+ } finally {
+ iCtx.eventProducer.removeEventListener(pw);
+ }
+ try {
+ updateEditionHint(reposDir, result.getEdition());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return result;
+ }
+
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
index 01af506..d13bc70 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
@@ -1,36 +1,34 @@
package plugins.schwachkopfeinsteck.daemon;
-import java.io.File;
-
import plugins.schwachkopfeinsteck.RepositoryManager;
import freenet.support.incubation.server.AbstractServer;
import freenet.support.incubation.server.AbstractService;
import freenet.support.plugins.helpers1.PluginContext;
public class AnonymousGitDaemon extends AbstractServer {
private boolean isReadOnly = true;
private final PluginContext pluginContext;
private final RepositoryManager repositoryManager;
public AnonymousGitDaemon(String servername, RepositoryManager repositorymanager, PluginContext plugincontext) {
super(servername, plugincontext.node.executor);
pluginContext = plugincontext;
repositoryManager = repositorymanager;
}
@Override
protected AbstractService getService() {
- return new AnonymousGitService(isReadOnly(), eXecutor, pluginContext);
+ return new AnonymousGitService(isReadOnly(), eXecutor, pluginContext, repositoryManager);
}
public void setReadOnly(boolean readOnly) {
isReadOnly = readOnly;
}
public boolean isReadOnly() {
return isReadOnly;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index 4be1244..a4c57a1 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,166 +1,276 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
-import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.net.MalformedURLException;
import java.net.Socket;
-
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.PacketLineOut;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.UploadPack;
-import plugins.schwachkopfeinsteck.ReposInserter1;
+import plugins.schwachkopfeinsteck.RepositoryManager;
+import plugins.schwachkopfeinsteck.RepositoryManager.RepositoryWrapper;
import freenet.client.InsertException;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableUSK;
import freenet.support.Executor;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
import freenet.support.plugins.helpers1.PluginContext;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private final boolean isReadOnly;
private final Executor eXecutor;
private final PluginContext pluginContext;
+ private final RepositoryManager repositoryManager;
+
+ private static final long LOCK_TIMEOUT = 5;
+ private static final TimeUnit LOCK_TIMEUNIT = TimeUnit.SECONDS;
+
- public AnonymousGitService(boolean readOnly, Executor executor, PluginContext plugincontext) {
+ public AnonymousGitService(boolean readOnly, Executor executor, PluginContext plugincontext, RepositoryManager repositorymanager) {
isReadOnly = readOnly;
eXecutor = executor;
pluginContext = plugincontext;
+ repositoryManager = repositorymanager;
}
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
//System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
// adjust uri string
if (reposName.startsWith("/")) {
reposName = reposName.substring(1);
}
if (!reposName.endsWith("/")) {
reposName = reposName + '/';
}
- // reposname is the uri
+ // reposName is the uri
FreenetURI iUri = null;
- FreenetURI rUri = new FreenetURI(reposName);
+ FreenetURI rUri;
+ try {
+ rUri = new FreenetURI(reposName);
+ } catch (MalformedURLException e1) {
+ fatal(rawOut, "Not a valid Freenet URI: "+e1.getLocalizedMessage());
+ return;
+ }
if (!rUri.isUSK()) {
- fatal(rawOut, "Repository uri must be an USK");
+ fatal(rawOut, "Repository uri must be an USK.");
return;
}
+ // if it is an insert uri, get the request uri from it.
if(rUri.getExtra()[1] == 1) {
iUri = rUri;
InsertableUSK iUsk = InsertableUSK.createInsertable(rUri, false);
rUri = iUsk.getURI();
}
- //System.out.print("händle:"+command);
- //System.out.println(" for:"+reposName);
+ // reposName is the internal repository name
+ reposName = RepositoryManager.getRepositoryName(rUri);
+
+ RepositoryWrapper rw = repositoryManager.getRepository(reposName);
+ if (rw == null) {
+ fatal(rawOut, "No such repository.");
+ return;
+ }
+
+ try {
+ innerHandle(command, rw, rawIn, rawOut, rUri, iUri);
+ } catch (InterruptedException e) {
+ Logger.error(this, "Interrupted.", e);
+ fatal(rawOut, "Interrupted.");
+ }
+ }
+
+ private class LockWorkerThread extends Thread {
+
+ private volatile boolean recivedDone = false;
+
+ private final RepositoryWrapper rW;
+ private final InputStream rawIn;
+ private final OutputStream rawOut;
+
+ private String error = null;
+ private final FreenetURI fetchUri;
+ private final FreenetURI insertUri;
+
+ LockWorkerThread(RepositoryWrapper rw, InputStream rawin, OutputStream rawout, FreenetURI fetchuri, FreenetURI inserturi) {
+ rW = rw;
+ rawIn = rawin;
+ rawOut = rawout;
+ fetchUri = fetchuri;
+ insertUri = inserturi;
+ }
+
+ @Override
+ public void run() {
+ try {
+ innerRun();
+ } catch (InterruptedException e) {
+ Logger.error(this, "Interrupted.", e);
+ } catch (IOException e) {
+ Logger.error(this, "IO Error.", e);
+ }
+ }
+
+ private void innerRun() throws InterruptedException, IOException {
+ Lock lock = rW.rwLock.writeLock();
+ if (lock.tryLock() || lock.tryLock(LOCK_TIMEOUT, LOCK_TIMEUNIT)) {
+ boolean sucess = false;
+ boolean triggerUpload;
+ try {
+ triggerUpload = handleGitReceivePack(rW.db, rawIn, rawOut);
+ sucess = true;
+ } finally {
+ if (!sucess) {
+ lock.unlock();
+ }
+ recivedDone();
+ }
+
+ if (!triggerUpload) {
+ if (logMINOR) Logger.minor(this, "Nothing updated. Do not upload.");
+ lock.unlock();
+ return;
+ }
+
+ // downgrade from write to read lock
+ Lock newLock = rW.rwLock.readLock();
+ newLock.lock();
+ lock.unlock();
+ lock = newLock;
+
+ try {
+ repositoryManager.insert(rW, fetchUri, insertUri, pluginContext);
+ } catch (InsertException e) {
+ error = "Insert Failure: "+InsertException.getMessage(e.getMode());
+ Logger.error(this, error, e);
+ } finally {
+ lock.unlock();
+ }
+ } else {
+ error = "Was not able to obtain a write lock within 5 seconds.\nTry again later.";
+ recivedDone();
+ }
+ }
+
+ private synchronized void recivedDone() {
+ recivedDone = true;
+ notifyAll();
+ }
+ public synchronized void waitForReciveDone() {
+ while(!recivedDone) {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ // Ignore
+ }
+ }
+ }
+ }
+
+ private void innerHandle(String command, final RepositoryWrapper rw, InputStream rawIn, OutputStream rawOut, final FreenetURI rUri, final FreenetURI iUri) throws IOException, InterruptedException {
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
- Repository db = getRepository(reposName);
- final UploadPack rp = new UploadPack(db);
- //rp.setTimeout(Daemon.this.getTimeout());
- rp.upload(rawIn, rawOut, null);
+ Lock lock = rw.rwLock.readLock();
+ if (lock.tryLock() || lock.tryLock(LOCK_TIMEOUT, LOCK_TIMEUNIT)) {
+ try {
+ handleGitUploadPack(rw.db, rawIn, rawOut);
+ } finally {
+ lock.unlock();
+ }
+ } else {
+ fatal(rawOut, "Was not able to obtain a read lock within 5 seconds.\nTry again later.");
+ return;
+ }
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) {
fatal(rawOut, "Server is read only.");
return;
}
if (iUri == null) {
fatal(rawOut, "Try an insert uri for push.");
return;
}
- final Repository db = getRepository(reposName);
- final ReceivePack rp = new ReceivePack(db);
- final String name = "anonymous";
- final String email = name + "@freenet";
- rp.setRefLogIdent(new PersonIdent(name, email));
- //rp.setTimeout(Daemon.this.getTimeout());
- rp.receive(rawIn, rawOut, null);
-
- final FreenetURI insertURI = iUri;
- final File reposDir = getRepositoryPath(reposName);
-
- // FIXME
- // trigger the upload, the quick&dirty way
- eXecutor.execute(new Runnable (){
- public void run() {
- try {
- ReposInserter1.insert(db, reposDir, insertURI, pluginContext);
- } catch (InsertException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }});
- } else {
- fatal(rawOut, "Unknown command: "+command);
- System.err.println("Unknown command: "+command);
- }
- //System.out.println("x händle request: pfertsch");
+ LockWorkerThread t = new LockWorkerThread(rw, rawIn, rawOut, rUri, iUri);
+ eXecutor.execute(t);
- }
+ t.waitForReciveDone();
- private File getRepositoryPath(String reposname) throws IOException {
- FreenetURI uri = new FreenetURI(reposname);
- if(uri.getExtra()[1] == 1) {
- InsertableUSK iUsk = InsertableUSK.createInsertable(uri, false);
- uri = iUsk.getURI();
+ if (t.error != null) {
+ fatal(rawOut, t.error);
+ }
+ } else {
+ Logger.error(this, "Unknown command: "+command);
+ fatal(rawOut, "Unknown command: "+command);
}
+ }
- String docName = uri.getDocName();
- uri = uri.setKeyType("SSK");
- String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
- return new File("gitcache", reposName + '@' + docName).getCanonicalFile();
+ private void handleGitUploadPack(Repository db, InputStream rawIn, OutputStream rawOut) throws IOException {
+ final UploadPack rp = new UploadPack(db);
+ //rp.setTimeout(Daemon.this.getTimeout());
+ rp.upload(rawIn, rawOut, null);
}
- private Repository getRepository(String reposname) throws IOException {
- Repository db;
- File path = getRepositoryPath(reposname);
- db = new Repository(path);
- return db;
+ private boolean handleGitReceivePack(final Repository db, InputStream rawIn, OutputStream rawOut) throws IOException {
+ final ReceivePack rp = new ReceivePack(db);
+ final String name = "anonymous";
+ final String email = name + "@freenet";
+ rp.setRefLogIdent(new PersonIdent(name, email));
+ //rp.setTimeout(Daemon.this.getTimeout());
+ rp.receive(rawIn, rawOut, null);
+ try {
+ rp.getNewObjectIds();
+ } catch ( NullPointerException npe) {
+ return false;
+ }
+ return true;
}
private void fatal(OutputStream rawOut, String string) throws IOException {
PacketLineOut pckOut = new PacketLineOut(rawOut);
byte[] data = ("ERR "+string).getBytes();
pckOut.writePacket(data);
pckOut.flush();
rawOut.flush();
}
}
diff --git a/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
index a322ce6..2694587 100644
--- a/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
@@ -1,401 +1,397 @@
package plugins.schwachkopfeinsteck.toadlets;
-import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
-import org.eclipse.jgit.lib.Repository;
-
import plugins.schwachkopfeinsteck.GitPlugin;
import plugins.schwachkopfeinsteck.RepositoryManager;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.keys.FreenetURI;
import freenet.node.useralerts.SimpleUserAlert;
import freenet.node.useralerts.UserAlert;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
private static final String CMD_BROWSE = "browse";
private static final String CMD_CREATE = "create";
private static final String CMD_DELETE = "delete";
private static final String CMD_FORK = "fork";
private static final String CMD_SAVEDESCRIPTION = "save";
private static final String PARAM_DELETECONFIRM = "deleteconfirm";
private static final String PARAM_DESCRIPTION = "description";
private static final String PARAM_INSERTURI = "inserturi";
private static final String PARAM_NAME = "name";
private static final String PARAM_REPOSNAME = "reposuri";
private static final String PARAM_REQUESTURI = "requesturi";
private static final String PARAM_SOURCE = "source";
private static final String PARAM_URI = "uri";
private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
private final RepositoryManager repositoryManager;
// '/', ';', '?' are forbidden to not confuse the URL parser,
// all others are forbidden to prevent file system clashes
private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon, RepositoryManager repositorymanager) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
repositoryManager = repositorymanager;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
List<String> errors = new LinkedList<String>();
makeMainPage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makeMainPage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
try {
repositoryManager.updateDescription(repos, desc);
} catch (IOException e) {
e.printStackTrace();
errors.add("Error while updating description : "+e.getLocalizedMessage());
}
} else if (request.isPartSet(CMD_DELETE)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
if (request.isPartSet(PARAM_DELETECONFIRM)) {
repositoryManager.deleteRepository(repos);
} else {
makeDeleteConfirmPage(ctx, repos);
return;
}
} else if (request.isPartSet(CMD_CREATE)) {
String name = request.getPartAsString(PARAM_NAME, 1024);
String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
errors.add("Are you jokingly? Every field is empty.");
} else {
if ((rUri.length() == 0) && (iUri.length() == 0)) {
FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
iUri = kp[0].setDocName(null).toString(false, false);
rUri = kp[1].setDocName(null).toString(false, false);
errors.add("URI was empty, I generated one for you.");
}
name = sanitizeDocName(name, errors);
// TODO some more uri wodoo
// a bare fetch uri means import, a bare insert uri get its fetch uri added
// try to get name from uri if name is not given
// auto convert ssk
// etc pp
if (errors.size() == 0) {
tryCreateRepository(name, rUri, iUri, errors);
}
if (errors.size() > 0) {
makeCreatePage(ctx, name, rUri, iUri, errors);
return;
}
makeCreatedReposPage(ctx, name, rUri, iUri, errors);
return;
}
} else {
errors.add("Did not understand. Maybe not implemented jet? :P");
}
makeMainPage(ctx, errors);
}
private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, null, null, null);
makeForkBox(contentNode, null, null, null);
makeRepositoryBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeDeleteConfirmBox(contentNode, reposName);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeCreatedReposBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
boxForm.addChild("b", reposName);
boxForm.addChild("br");
boxForm.addChild("a", "href", path(), "Hell, NO!");
boxForm.addChild("#", "\u00a0");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
}
private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
box.addChild("#", "Created a new repository. Congratz!");
box.addChild("br");
box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+rUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
box.addChild("br");
box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+iUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
}
private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Request URI:\u00a0 ");
if (rUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (iUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
}
private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
if (source != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (uri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
}
private void makeRepositoryBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
File cacheDir = repositoryManager.getCacheDirFile();
File[] dirs = cacheDir.listFiles();
if (dirs.length == 0) {
box.addChild("#", "No repositories set up.");
return;
}
HTMLNode table = box.addChild("table", "width", "100%");
HTMLNode tableHead = table.addChild("thead");
HTMLNode tableRow = tableHead.addChild("tr");
HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
nextTableCell.addChild("#", "Name");
nextTableCell = tableRow.addChild("th");
nextTableCell.addChild("#", "Description");
for (File dir: dirs) {
HTMLNode htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeNameCell(dir));
htmlTableRow.addChild(makeDescriptionCell(dir));
htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeDeleteCell(dir));
htmlTableRow.addChild(makeEmptyCell());
htmlTableRow.addChild(makeForkCell(dir));
}
}
private HTMLNode makeEmptyCell() {
HTMLNode cell = new HTMLNode("td");
cell.addChild("#", "\u00a0");
return cell;
}
private HTMLNode makeNameCell(File repos) {
HTMLNode cell = new HTMLNode("td", "colspan", "3");
String dirName = repos.getName();
cell.addChild("b", dirName);
return cell;
}
private HTMLNode makeDescriptionCell(File repos) {
HTMLNode cell = new HTMLNode("td", "rowspan", "2");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
String desc = getReposDescription(repos);
if (desc != null) {
area.addChild("#", desc);
} else {
area.addChild("#", "\u00a0");
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
return cell;
}
private HTMLNode makeDeleteCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
return cell;
}
private HTMLNode makeForkCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
return cell;
}
private String getReposDescription(File dir) {
File descfile = new File(dir, "description");
if (!descfile.exists()) return "<Describe me!>";
String desc;
try {
desc = FileUtil.readUTF(descfile);
} catch (IOException e) {
Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
return "Error: "+e.getLocalizedMessage();
}
return desc;
}
private String getReposURI(File repos) {
return repos.getName();
}
private String getReposURI(String repos) {
return repos;
}
private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
String dirName = rUri + '@' + name;
try {
repositoryManager.tryCreateRepository(dirName, "add a description here");
} catch (IOException e) {
Logger.error(this, "Error while create repository: "+dirName, e);
errors.add(e.getLocalizedMessage());
return;
}
String alert = "Due lack of a better idea the URIs are noted here:\n"+
"Created Repository :"+dirName+"\n"+
"Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
"Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
pluginContext.clientCore.alerts.register(new SimpleUserAlert(true, "Repository created", alert, "Repository created", UserAlert.MINOR));
}
private String sanitizeDocName(String docName, List<String> errors) {
int len = docName.length();
for (int i=0 ; i<len ; i++) {
char c = docName.charAt(i);
if (forbiddenChars.contains(c)) {
errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
}
}
return docName;
}
}
|
saces/SchwachkopfEinsteck
|
a0cc8df5cc2e888b8be08befb970fac3ed37abd3
|
introduce RepositoryManager
|
diff --git a/src/plugins/schwachkopfeinsteck/GitPlugin.java b/src/plugins/schwachkopfeinsteck/GitPlugin.java
index 6f9d869..991f2ef 100644
--- a/src/plugins/schwachkopfeinsteck/GitPlugin.java
+++ b/src/plugins/schwachkopfeinsteck/GitPlugin.java
@@ -1,81 +1,96 @@
package plugins.schwachkopfeinsteck;
+import java.io.File;
+import java.io.IOException;
+
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import plugins.schwachkopfeinsteck.toadlets.AdminToadlet;
import plugins.schwachkopfeinsteck.toadlets.BrowseToadlet;
import plugins.schwachkopfeinsteck.toadlets.RepositoriesToadlet;
import freenet.l10n.BaseL10n.LANGUAGE;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginRealVersioned;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Logger;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterface;
public class GitPlugin implements FredPlugin, FredPluginL10n, FredPluginThreadless, FredPluginVersioned, FredPluginRealVersioned {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
public static final String PLUGIN_URI = "/GitPlugin";
private static final String PLUGIN_CATEGORY = "Git Tools";
public static final String PLUGIN_TITLE = "Git Plugin";
private PluginContext pluginContext;
private WebInterface webInterface;
private AnonymousGitDaemon simpleDaemon;
+ private RepositoryManager repositoryManager;
public void runPlugin(PluginRespirator pluginRespirator) {
pluginContext = new PluginContext(pluginRespirator);
+ final File cacheDir;
+ try {
+ cacheDir = RepositoryManager.ensureCacheDirExists("./gitcache");
+ } catch (IOException e) {
+ // It makes really no sense without cache, blow away.
+ throw new Error(e);
+ }
+
+ repositoryManager = new RepositoryManager(cacheDir);
// for now a single server only, later versions can do multiple servers
// and each can have its own cache/config
- simpleDaemon = new AnonymousGitDaemon("huhu", pluginContext.node.executor, pluginContext);
- simpleDaemon.setCacheDir("./gitcache");
+ simpleDaemon = new AnonymousGitDaemon("huhu", repositoryManager, pluginContext);
webInterface = new WebInterface(pluginContext);
webInterface.addNavigationCategory(PLUGIN_URI+"/", PLUGIN_CATEGORY, "Git Toolbox", this);
// Visible pages
BrowseToadlet browseToadlet = new BrowseToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(browseToadlet, PLUGIN_CATEGORY, "Browse", "Browse a git repository like GitWeb");
- AdminToadlet adminToadlet = new AdminToadlet(pluginContext, simpleDaemon);
+ AdminToadlet adminToadlet = new AdminToadlet(pluginContext, simpleDaemon, repositoryManager);
webInterface.registerVisible(adminToadlet, PLUGIN_CATEGORY, "Admin", "Admin the git server");
- RepositoriesToadlet reposToadlet = new RepositoriesToadlet(pluginContext, simpleDaemon);
+ RepositoriesToadlet reposToadlet = new RepositoriesToadlet(pluginContext, simpleDaemon, repositoryManager);
webInterface.registerVisible(reposToadlet, PLUGIN_CATEGORY, "Repositories", "Create & Delete server's repositories");
}
public void terminate() {
- webInterface.kill();
if (simpleDaemon.isRunning())
simpleDaemon.stop();
simpleDaemon = null;
+ webInterface.kill();
+ webInterface = null;
+ repositoryManager.kill();
+ repositoryManager = null;
}
public String getString(String key) {
// return the key for now, l10n comes later
return key;
}
public void setLanguage(LANGUAGE newLanguage) {
// ignored for now, l10n comes later
}
public String getVersion() {
return Version.getLongVersionString();
}
public long getRealVersion() {
return Version.getRealVersion();
}
}
diff --git a/src/plugins/schwachkopfeinsteck/RepositoryManager.java b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
new file mode 100644
index 0000000..a1a378a
--- /dev/null
+++ b/src/plugins/schwachkopfeinsteck/RepositoryManager.java
@@ -0,0 +1,87 @@
+package plugins.schwachkopfeinsteck;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.eclipse.jgit.lib.Repository;
+
+import freenet.node.useralerts.SimpleUserAlert;
+import freenet.node.useralerts.UserAlert;
+import freenet.support.Logger;
+import freenet.support.io.FileUtil;
+
+public class RepositoryManager {
+
+ private static volatile boolean logMINOR;
+ private static volatile boolean logDEBUG;
+
+ static {
+ Logger.registerClass(GitPlugin.class);
+ }
+
+ private final File cacheDir;
+
+ RepositoryManager(File cachedir) {
+ cacheDir = cachedir;
+ }
+
+ public static File ensureCacheDirExists(String dir) throws IOException {
+ File newDir = new File(dir);
+ if (newDir.exists()) {
+ return newDir;
+ }
+ if (newDir.mkdirs()) {
+ return newDir;
+ }
+ throw new IOException("Unable to create cache directory: "+newDir.getAbsolutePath());
+ }
+
+ public String getCacheDir() {
+ return cacheDir.getPath();
+ }
+
+ public void deleteRepository(String reposName) {
+ File repos = new File(cacheDir, reposName);
+ FileUtil.removeAll(repos);
+ }
+
+ public void updateDescription(String repos, String desc) throws IOException {
+ File reposFile = new File(cacheDir, repos);
+ updateDescription(reposFile, desc);
+ }
+
+ private void updateDescription(File repos, String desc) throws IOException {
+ File descfile = new File(repos, "description");
+ if (descfile.exists()) {
+ descfile.delete();
+ }
+ InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
+ FileUtil.writeTo(is, descfile);
+ }
+
+ private void tryCreateRepository(String reposName) throws IOException {
+ tryCreateRepository(reposName, null);
+ }
+
+ public void tryCreateRepository(String reposName, String description) throws IOException {
+ File reposDir = new File(cacheDir, reposName);
+ Repository repos;
+ repos = new Repository(reposDir);
+ repos.create(true);
+ if (description != null) {
+ updateDescription(reposDir, description);
+ }
+ }
+
+ @Deprecated
+ public File getCacheDirFile() {
+ return cacheDir;
+ }
+
+ public void kill() {
+ // TODO stopp lockking, kill all jobs.
+ // empty caches.
+ }
+}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
index e3f6024..01af506 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
@@ -1,54 +1,36 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.File;
-import freenet.support.Executor;
+import plugins.schwachkopfeinsteck.RepositoryManager;
+
import freenet.support.incubation.server.AbstractServer;
import freenet.support.incubation.server.AbstractService;
import freenet.support.plugins.helpers1.PluginContext;
public class AnonymousGitDaemon extends AbstractServer {
- private File reposdir;
private boolean isReadOnly = true;
private final PluginContext pluginContext;
+ private final RepositoryManager repositoryManager;
- public AnonymousGitDaemon(String servername, Executor executor, PluginContext plugincontext) {
- super(servername, executor);
+ public AnonymousGitDaemon(String servername, RepositoryManager repositorymanager, PluginContext plugincontext) {
+ super(servername, plugincontext.node.executor);
pluginContext = plugincontext;
+ repositoryManager = repositorymanager;
}
@Override
protected AbstractService getService() {
return new AnonymousGitService(isReadOnly(), eXecutor, pluginContext);
}
- public void setCacheDir(String dir) {
- if (reposdir != null) {
- // move
- } else {
- File newDir = new File(dir);
- if (!newDir.exists()) {
- newDir.mkdirs();
- }
- reposdir = newDir;
- }
- }
-
- public String getCacheDir() {
- return reposdir.getPath();
- }
-
- public File getCacheDirFile() {
- return reposdir;
- }
-
public void setReadOnly(boolean readOnly) {
isReadOnly = readOnly;
}
public boolean isReadOnly() {
return isReadOnly;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/toadlets/AdminToadlet.java b/src/plugins/schwachkopfeinsteck/toadlets/AdminToadlet.java
index 2927b79..a1b9bae 100644
--- a/src/plugins/schwachkopfeinsteck/toadlets/AdminToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/toadlets/AdminToadlet.java
@@ -1,161 +1,164 @@
package plugins.schwachkopfeinsteck.toadlets;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import plugins.schwachkopfeinsteck.GitPlugin;
+import plugins.schwachkopfeinsteck.RepositoryManager;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class AdminToadlet extends WebInterfaceToadlet {
private static final String PARAM_PORT = "port";
private static final String PARAM_BINDTO = "bindto";
private static final String PARAM_ALLOWEDHOSTS = "allowedhosts";
private static final String PARAM_CACHEDIR = "chachedir";
private static final String PARAM_READONLY = "readonly";
private static final String CMD_START = "start";
private static final String CMD_STOP = "stop";
private static final String CMD_RESTART = "restart";
private static final String CMD_APPLY = "apply";
private final AnonymousGitDaemon daemon;
+ private final RepositoryManager repositoryManager;
- public AdminToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
+ public AdminToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon, RepositoryManager repositorymanager) {
super(context, GitPlugin.PLUGIN_URI, "admin");
daemon = simpleDaemon;
+ repositoryManager = repositorymanager;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!normalizePath(req.getPath()).equals("/")) {
errors.add("The path '"+uri+"' was not found");
}
makePage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makePage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_STOP)) {
daemon.stop();
} else {
String bindTo = request.getPartAsString(PARAM_BINDTO, 50);
int port = request.getIntPart(PARAM_PORT, 9481);
String allowedHosts = request.getPartAsString(PARAM_ALLOWEDHOSTS, 50);
String ro = request.getPartAsString(PARAM_READONLY, 50);
if (request.isPartSet(CMD_START)) {
daemon.setAdress(bindTo, port, allowedHosts, false);
daemon.setReadOnly(ro.length() > 0);
daemon.start();
} else if (request.isPartSet(CMD_RESTART)) {
daemon.stop();
try {
//sleep 3 sec, give the old bind a chance to vanishâ¦
Thread.sleep(3000);
} catch (InterruptedException e) {
// ignored
}
daemon.setAdress(bindTo, port, allowedHosts, false);
daemon.setReadOnly(ro.length() > 0);
daemon.start();
} else {
errors.add("Unknown command.");
}
}
makePage(ctx, errors);
}
private void makePage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin the git server", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, path(), null, null));
errors.clear();
}
makeCommonBox(contentNode);
makeSimpleBox(contentNode);
makeSSHBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCommonBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Common settings", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "commonForm");
boxForm.addChild("#", "GitPlugin uses a local cache to serve from. Congratulation, you have found the reference point for 'backup'.");
boxForm.addChild("br");
boxForm.addChild("#", "Cache dir: \u00a0 ");
- boxForm.addChild("input", new String[] { "type", "name", "size", "value", "disabled"}, new String[] { "text", PARAM_CACHEDIR, "50", daemon.getCacheDir(), "disabled" });
+ boxForm.addChild("input", new String[] { "type", "name", "size", "value", "disabled"}, new String[] { "text", PARAM_CACHEDIR, "50", repositoryManager.getCacheDir(), "disabled" });
boxForm.addChild("br");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_APPLY, "Apply", "disabled" });
}
private void makeSimpleBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Simple git server (git://)", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "simpleServerForm");
boxForm.addChild("#", "This is the anonymous git server. No authentication/encryption/accesscontrol at all. Be carefully.");
boxForm.addChild("br");
boxForm.addChild("#", "Port: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_PORT, "7", "9418" });
boxForm.addChild("br");
boxForm.addChild("#", "Bind to: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_BINDTO, "20", "127.0.0.1" });
boxForm.addChild("br");
boxForm.addChild("#", "Allowed hosts: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_ALLOWEDHOSTS, "20", "127.0.0.1" });
boxForm.addChild("br");
if (daemon.isReadOnly()) {
boxForm.addChild("input", new String[] { "type", "name", "value", "checked" }, new String[] { "checkbox", PARAM_READONLY, "ok", "checked" });
} else {
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "checkbox", PARAM_READONLY, "ok" });
}
boxForm.addChild("#", "\u00a0Read only access");
boxForm.addChild("br");
boxForm.addChild("br");
if (daemon.isRunning()) {
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_START, "Start", "disabled" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_STOP, "Stop" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_RESTART, "Restart" });
} else {
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_START, "Start"});
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_STOP, "Stop", "disabled" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_RESTART, "Restart", "disabled" });
}
}
private void makeSSHBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "SSH git server (git+ssh://)", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "sshServerForm");
boxForm.addChild("#", "Setting up SSH for an 'Just an idea' implementation is far to much. Sorry folks.");
boxForm.addChild("br");
boxForm.addChild("#", "Basic code for SSH (jSch) is in, just send patches ;)");
}
}
diff --git a/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
index a7dc402..a322ce6 100644
--- a/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
@@ -1,428 +1,401 @@
package plugins.schwachkopfeinsteck.toadlets;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jgit.lib.Repository;
import plugins.schwachkopfeinsteck.GitPlugin;
+import plugins.schwachkopfeinsteck.RepositoryManager;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.keys.FreenetURI;
import freenet.node.useralerts.SimpleUserAlert;
import freenet.node.useralerts.UserAlert;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
private static final String CMD_BROWSE = "browse";
private static final String CMD_CREATE = "create";
private static final String CMD_DELETE = "delete";
private static final String CMD_FORK = "fork";
private static final String CMD_SAVEDESCRIPTION = "save";
private static final String PARAM_DELETECONFIRM = "deleteconfirm";
private static final String PARAM_DESCRIPTION = "description";
private static final String PARAM_INSERTURI = "inserturi";
private static final String PARAM_NAME = "name";
private static final String PARAM_REPOSNAME = "reposuri";
private static final String PARAM_REQUESTURI = "requesturi";
private static final String PARAM_SOURCE = "source";
private static final String PARAM_URI = "uri";
private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
+ private final RepositoryManager repositoryManager;
// '/', ';', '?' are forbidden to not confuse the URL parser,
// all others are forbidden to prevent file system clashes
private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
- public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
+ public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon, RepositoryManager repositorymanager) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
+ repositoryManager = repositorymanager;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
List<String> errors = new LinkedList<String>();
makeMainPage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makeMainPage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
try {
- updateDescription(repos, desc);
+ repositoryManager.updateDescription(repos, desc);
} catch (IOException e) {
e.printStackTrace();
errors.add("Error while updating description : "+e.getLocalizedMessage());
}
} else if (request.isPartSet(CMD_DELETE)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
if (request.isPartSet(PARAM_DELETECONFIRM)) {
- deleteRepository(repos);
+ repositoryManager.deleteRepository(repos);
} else {
makeDeleteConfirmPage(ctx, repos);
return;
}
} else if (request.isPartSet(CMD_CREATE)) {
String name = request.getPartAsString(PARAM_NAME, 1024);
String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
errors.add("Are you jokingly? Every field is empty.");
} else {
if ((rUri.length() == 0) && (iUri.length() == 0)) {
FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
iUri = kp[0].setDocName(null).toString(false, false);
rUri = kp[1].setDocName(null).toString(false, false);
errors.add("URI was empty, I generated one for you.");
}
name = sanitizeDocName(name, errors);
// TODO some more uri wodoo
// a bare fetch uri means import, a bare insert uri get its fetch uri added
// try to get name from uri if name is not given
// auto convert ssk
// etc pp
if (errors.size() == 0) {
tryCreateRepository(name, rUri, iUri, errors);
}
if (errors.size() > 0) {
makeCreatePage(ctx, name, rUri, iUri, errors);
return;
}
makeCreatedReposPage(ctx, name, rUri, iUri, errors);
return;
}
} else {
errors.add("Did not understand. Maybe not implemented jet? :P");
}
makeMainPage(ctx, errors);
}
private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, null, null, null);
makeForkBox(contentNode, null, null, null);
makeRepositoryBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeDeleteConfirmBox(contentNode, reposName);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeCreatedReposBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
boxForm.addChild("b", reposName);
boxForm.addChild("br");
boxForm.addChild("a", "href", path(), "Hell, NO!");
boxForm.addChild("#", "\u00a0");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
}
private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
box.addChild("#", "Created a new repository. Congratz!");
box.addChild("br");
box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+rUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
box.addChild("br");
box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+iUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
}
private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Request URI:\u00a0 ");
if (rUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (iUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
}
private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
if (source != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (uri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
}
private void makeRepositoryBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
- File cacheDir = daemon.getCacheDirFile();
+ File cacheDir = repositoryManager.getCacheDirFile();
File[] dirs = cacheDir.listFiles();
if (dirs.length == 0) {
box.addChild("#", "No repositories set up.");
return;
}
HTMLNode table = box.addChild("table", "width", "100%");
HTMLNode tableHead = table.addChild("thead");
HTMLNode tableRow = tableHead.addChild("tr");
HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
nextTableCell.addChild("#", "Name");
nextTableCell = tableRow.addChild("th");
nextTableCell.addChild("#", "Description");
for (File dir: dirs) {
HTMLNode htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeNameCell(dir));
htmlTableRow.addChild(makeDescriptionCell(dir));
htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeDeleteCell(dir));
htmlTableRow.addChild(makeEmptyCell());
htmlTableRow.addChild(makeForkCell(dir));
}
}
private HTMLNode makeEmptyCell() {
HTMLNode cell = new HTMLNode("td");
cell.addChild("#", "\u00a0");
return cell;
}
private HTMLNode makeNameCell(File repos) {
HTMLNode cell = new HTMLNode("td", "colspan", "3");
String dirName = repos.getName();
cell.addChild("b", dirName);
return cell;
}
private HTMLNode makeDescriptionCell(File repos) {
HTMLNode cell = new HTMLNode("td", "rowspan", "2");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
String desc = getReposDescription(repos);
if (desc != null) {
area.addChild("#", desc);
} else {
area.addChild("#", "\u00a0");
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
return cell;
}
private HTMLNode makeDeleteCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
return cell;
}
private HTMLNode makeForkCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
return cell;
}
private String getReposDescription(File dir) {
File descfile = new File(dir, "description");
if (!descfile.exists()) return "<Describe me!>";
String desc;
try {
desc = FileUtil.readUTF(descfile);
} catch (IOException e) {
Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
return "Error: "+e.getLocalizedMessage();
}
return desc;
}
- private void updateDescription(String repos, String desc) throws IOException {
- File reposFile = new File(daemon.getCacheDirFile(), repos);
- updateDescription(reposFile, desc);
- }
-
- private void updateDescription(File repos, String desc) throws IOException {
- File descfile = new File(repos, "description");
- if (descfile.exists()) {
- descfile.delete();
- }
- InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
- FileUtil.writeTo(is, descfile);
- }
-
- private void deleteRepository(String reposName) {
- File repos = new File(daemon.getCacheDirFile(), reposName);
- FileUtil.removeAll(repos);
- }
-
private String getReposURI(File repos) {
return repos.getName();
}
private String getReposURI(String repos) {
return repos;
}
private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
String dirName = rUri + '@' + name;
- File reposDir = new File(daemon.getCacheDirFile(), dirName);
- Repository repos;
try {
- repos = new Repository(reposDir);
- repos.create(true);
+ repositoryManager.tryCreateRepository(dirName, "add a description here");
} catch (IOException e) {
- Logger.error(this, "Error while create repository: "+reposDir.getAbsolutePath(), e);
+ Logger.error(this, "Error while create repository: "+dirName, e);
errors.add(e.getLocalizedMessage());
return;
}
- String comment = "add a description here";
String alert = "Due lack of a better idea the URIs are noted here:\n"+
"Created Repository :"+dirName+"\n"+
"Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
"Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
pluginContext.clientCore.alerts.register(new SimpleUserAlert(true, "Repository created", alert, "Repository created", UserAlert.MINOR));
-
- try {
- updateDescription(reposDir, comment);
- } catch (IOException e) {
- Logger.error(this, "Error while updating repository description for: "+reposDir.getAbsolutePath(), e);
- errors.add(e.getLocalizedMessage());
- }
}
private String sanitizeDocName(String docName, List<String> errors) {
int len = docName.length();
for (int i=0 ; i<len ; i++) {
char c = docName.charAt(i);
if (forbiddenChars.contains(c)) {
errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
}
}
return docName;
}
}
|
saces/SchwachkopfEinsteck
|
b0760a4f2a9af7934eda2dfdd05f92aee6fbca31
|
fix 'Already sent headers'.
|
diff --git a/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
index e14a5c0..a7dc402 100644
--- a/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
@@ -1,427 +1,428 @@
package plugins.schwachkopfeinsteck.toadlets;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jgit.lib.Repository;
import plugins.schwachkopfeinsteck.GitPlugin;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.keys.FreenetURI;
import freenet.node.useralerts.SimpleUserAlert;
import freenet.node.useralerts.UserAlert;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
private static final String CMD_BROWSE = "browse";
private static final String CMD_CREATE = "create";
private static final String CMD_DELETE = "delete";
private static final String CMD_FORK = "fork";
private static final String CMD_SAVEDESCRIPTION = "save";
private static final String PARAM_DELETECONFIRM = "deleteconfirm";
private static final String PARAM_DESCRIPTION = "description";
private static final String PARAM_INSERTURI = "inserturi";
private static final String PARAM_NAME = "name";
private static final String PARAM_REPOSNAME = "reposuri";
private static final String PARAM_REQUESTURI = "requesturi";
private static final String PARAM_SOURCE = "source";
private static final String PARAM_URI = "uri";
private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
// '/', ';', '?' are forbidden to not confuse the URL parser,
// all others are forbidden to prevent file system clashes
private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
List<String> errors = new LinkedList<String>();
makeMainPage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makeMainPage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
try {
updateDescription(repos, desc);
} catch (IOException e) {
e.printStackTrace();
errors.add("Error while updating description : "+e.getLocalizedMessage());
}
} else if (request.isPartSet(CMD_DELETE)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
if (request.isPartSet(PARAM_DELETECONFIRM)) {
deleteRepository(repos);
} else {
makeDeleteConfirmPage(ctx, repos);
return;
}
} else if (request.isPartSet(CMD_CREATE)) {
String name = request.getPartAsString(PARAM_NAME, 1024);
String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
errors.add("Are you jokingly? Every field is empty.");
} else {
if ((rUri.length() == 0) && (iUri.length() == 0)) {
FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
iUri = kp[0].setDocName(null).toString(false, false);
rUri = kp[1].setDocName(null).toString(false, false);
errors.add("URI was empty, I generated one for you.");
}
name = sanitizeDocName(name, errors);
// TODO some more uri wodoo
// a bare fetch uri means import, a bare insert uri get its fetch uri added
// try to get name from uri if name is not given
// auto convert ssk
// etc pp
if (errors.size() == 0) {
tryCreateRepository(name, rUri, iUri, errors);
}
if (errors.size() > 0) {
makeCreatePage(ctx, name, rUri, iUri, errors);
return;
}
makeCreatedReposPage(ctx, name, rUri, iUri, errors);
+ return;
}
} else {
errors.add("Did not understand. Maybe not implemented jet? :P");
}
makeMainPage(ctx, errors);
}
private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, null, null, null);
makeForkBox(contentNode, null, null, null);
makeRepositoryBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeDeleteConfirmBox(contentNode, reposName);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeCreatedReposBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
boxForm.addChild("b", reposName);
boxForm.addChild("br");
boxForm.addChild("a", "href", path(), "Hell, NO!");
boxForm.addChild("#", "\u00a0");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
}
private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
box.addChild("#", "Created a new repository. Congratz!");
box.addChild("br");
box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+rUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
box.addChild("br");
box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+iUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
}
private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Request URI:\u00a0 ");
if (rUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (iUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
}
private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
if (source != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (uri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
}
private void makeRepositoryBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
File cacheDir = daemon.getCacheDirFile();
File[] dirs = cacheDir.listFiles();
if (dirs.length == 0) {
box.addChild("#", "No repositories set up.");
return;
}
HTMLNode table = box.addChild("table", "width", "100%");
HTMLNode tableHead = table.addChild("thead");
HTMLNode tableRow = tableHead.addChild("tr");
HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
nextTableCell.addChild("#", "Name");
nextTableCell = tableRow.addChild("th");
nextTableCell.addChild("#", "Description");
for (File dir: dirs) {
HTMLNode htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeNameCell(dir));
htmlTableRow.addChild(makeDescriptionCell(dir));
htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeDeleteCell(dir));
htmlTableRow.addChild(makeEmptyCell());
htmlTableRow.addChild(makeForkCell(dir));
}
}
private HTMLNode makeEmptyCell() {
HTMLNode cell = new HTMLNode("td");
cell.addChild("#", "\u00a0");
return cell;
}
private HTMLNode makeNameCell(File repos) {
HTMLNode cell = new HTMLNode("td", "colspan", "3");
String dirName = repos.getName();
cell.addChild("b", dirName);
return cell;
}
private HTMLNode makeDescriptionCell(File repos) {
HTMLNode cell = new HTMLNode("td", "rowspan", "2");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
String desc = getReposDescription(repos);
if (desc != null) {
area.addChild("#", desc);
} else {
area.addChild("#", "\u00a0");
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
return cell;
}
private HTMLNode makeDeleteCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
return cell;
}
private HTMLNode makeForkCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
return cell;
}
private String getReposDescription(File dir) {
File descfile = new File(dir, "description");
if (!descfile.exists()) return "<Describe me!>";
String desc;
try {
desc = FileUtil.readUTF(descfile);
} catch (IOException e) {
Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
return "Error: "+e.getLocalizedMessage();
}
return desc;
}
private void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(daemon.getCacheDirFile(), repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
File descfile = new File(repos, "description");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
private void deleteRepository(String reposName) {
File repos = new File(daemon.getCacheDirFile(), reposName);
FileUtil.removeAll(repos);
}
private String getReposURI(File repos) {
return repos.getName();
}
private String getReposURI(String repos) {
return repos;
}
private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
String dirName = rUri + '@' + name;
File reposDir = new File(daemon.getCacheDirFile(), dirName);
Repository repos;
try {
repos = new Repository(reposDir);
repos.create(true);
} catch (IOException e) {
Logger.error(this, "Error while create repository: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
return;
}
String comment = "add a description here";
String alert = "Due lack of a better idea the URIs are noted here:\n"+
"Created Repository :"+dirName+"\n"+
"Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
"Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
pluginContext.clientCore.alerts.register(new SimpleUserAlert(true, "Repository created", alert, "Repository created", UserAlert.MINOR));
try {
updateDescription(reposDir, comment);
} catch (IOException e) {
Logger.error(this, "Error while updating repository description for: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
}
}
private String sanitizeDocName(String docName, List<String> errors) {
int len = docName.length();
for (int i=0 ; i<len ; i++) {
char c = docName.charAt(i);
if (forbiddenChars.contains(c)) {
errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
}
}
return docName;
}
}
|
saces/SchwachkopfEinsteck
|
5b86788a2ec8addb1840bf932ebbc96432972b32
|
typo in fproxy port
|
diff --git a/README b/README
index 14171cf..58aa01d 100644
--- a/README
+++ b/README
@@ -1,90 +1,90 @@
SchwachkopfEinsteck
===================
'SchwachkopfEinsteck' is german, it just translates to 'GitPlugin' :)
Prebuilt version: http://github.com/saces/SchwachkopfEinsteck/downloads
Just load the latest, it should go intuitiveâ¦
Source Version for the impatient:
Clone/update the repository, cd into it, update submodules and type 'ant'.
Grab the plugin from dist/SchwachkopfEinsteck.jar and load itâ¦
get sources (a fresh clone):
get the super project
git clone git://github.com/saces/SchwachkopfEinsteck.git SchwachkopfEinsteck
cd SchwachkopfEinsteck
init and update submodules
git submodule init
git submodule update
update sources:
update the super project
git pull git://github.com/saces/SchwachkopfEinsteck.git
update submodules
git submodule update
build:
cd into the project root and type 'ant'.
The new created plugin will be dist/SchwachkopfEinsteck.jar
configuration:
After loading the plugin visit http://127.0.0.1:8888/GitPlugin/admin or
'Git Tools'->'Admin' in the menu. Adjust the host and port if needed
(usually this should not be necessary) and press 'Start'.
Using It:
GO! GO! GO!
- go to http://127.0.0.1:8889/GitPlugin/repos (Menu->Git Tools->Repositories)
+ go to http://127.0.0.1:8888/GitPlugin/repos (Menu->Git Tools->Repositories)
create a new repository.
copy the inserturi from sucess page
git remote add <pasteithere> myFreenetRepos
or
git remote add git://127.0.0.1:9418/USK@inserturi,ABC/name/0/ myFreenetRepos
now push to it
git push myFreenetRepos master
or
git push git://127.0.0.1:9418/USK@inserturi,ABC/name/0/
fetch is work in progress, so you have to pull/fetch via fproxy for now
git clone http://127.0.0.1:8888/USK@requesturi,ADC/name/0/
git pull http://127.0.0.1:8888/USK@requesturi,ADC/name/0/
--obsolete--
Qualifying: (testing local repository creation, anonymous git transport)
- go to http://127.0.0.1:8889/GitPlugin/repos (Menu->Git Tools->Repositories)
+ go to http://127.0.0.1:8888/GitPlugin/repos (Menu->Git Tools->Repositories)
if any repository is left from warmup round, delete it
create a new repository.
for now the URIs are noted in the repository description.
git push git://127.0.0.1:9418/USK@crypticbitpuree,ABC/name/0/
git pull git://127.0.0.1:9418/USK@crypticbitpuree,ADC/name/0/
happy qualifying ;)
Warmup round: (testing the anonymous git transport)
create a bare repository in gitcache/test
cd <freenetdir>
mkdir gitcache
cd gitcache
mkdir test
cd test
git --bare init
the repository name ('test') is hardcoded for testing the anonymous git
transport. so any remote repository ends up in the repository you just
created.
git push git://127.0.0.1:9418/ignoredreposname
git pull git://127.0.0.1:9418/ignoredreposname
happy warm up testing ;)
TODO & Issues
=============
* local repository caching and locking
* implement synchronization from freenet to local cache (pull/fetch)
|
saces/SchwachkopfEinsteck
|
2bc6115fd698c631c8f0ea643c9f4ac03d97c270
|
Refactoring: move toadlets into package 'toadlets'
|
diff --git a/src/plugins/schwachkopfeinsteck/GitPlugin.java b/src/plugins/schwachkopfeinsteck/GitPlugin.java
index b0cb99d..6f9d869 100644
--- a/src/plugins/schwachkopfeinsteck/GitPlugin.java
+++ b/src/plugins/schwachkopfeinsteck/GitPlugin.java
@@ -1,78 +1,81 @@
package plugins.schwachkopfeinsteck;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
+import plugins.schwachkopfeinsteck.toadlets.AdminToadlet;
+import plugins.schwachkopfeinsteck.toadlets.BrowseToadlet;
+import plugins.schwachkopfeinsteck.toadlets.RepositoriesToadlet;
import freenet.l10n.BaseL10n.LANGUAGE;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginRealVersioned;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Logger;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterface;
public class GitPlugin implements FredPlugin, FredPluginL10n, FredPluginThreadless, FredPluginVersioned, FredPluginRealVersioned {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
public static final String PLUGIN_URI = "/GitPlugin";
private static final String PLUGIN_CATEGORY = "Git Tools";
public static final String PLUGIN_TITLE = "Git Plugin";
private PluginContext pluginContext;
private WebInterface webInterface;
private AnonymousGitDaemon simpleDaemon;
public void runPlugin(PluginRespirator pluginRespirator) {
pluginContext = new PluginContext(pluginRespirator);
// for now a single server only, later versions can do multiple servers
// and each can have its own cache/config
simpleDaemon = new AnonymousGitDaemon("huhu", pluginContext.node.executor, pluginContext);
simpleDaemon.setCacheDir("./gitcache");
webInterface = new WebInterface(pluginContext);
webInterface.addNavigationCategory(PLUGIN_URI+"/", PLUGIN_CATEGORY, "Git Toolbox", this);
// Visible pages
BrowseToadlet browseToadlet = new BrowseToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(browseToadlet, PLUGIN_CATEGORY, "Browse", "Browse a git repository like GitWeb");
AdminToadlet adminToadlet = new AdminToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(adminToadlet, PLUGIN_CATEGORY, "Admin", "Admin the git server");
RepositoriesToadlet reposToadlet = new RepositoriesToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(reposToadlet, PLUGIN_CATEGORY, "Repositories", "Create & Delete server's repositories");
}
public void terminate() {
webInterface.kill();
if (simpleDaemon.isRunning())
simpleDaemon.stop();
simpleDaemon = null;
}
public String getString(String key) {
// return the key for now, l10n comes later
return key;
}
public void setLanguage(LANGUAGE newLanguage) {
// ignored for now, l10n comes later
}
public String getVersion() {
return Version.getLongVersionString();
}
public long getRealVersion() {
return Version.getRealVersion();
}
}
diff --git a/src/plugins/schwachkopfeinsteck/AdminToadlet.java b/src/plugins/schwachkopfeinsteck/toadlets/AdminToadlet.java
similarity index 98%
rename from src/plugins/schwachkopfeinsteck/AdminToadlet.java
rename to src/plugins/schwachkopfeinsteck/toadlets/AdminToadlet.java
index 76f415d..2927b79 100644
--- a/src/plugins/schwachkopfeinsteck/AdminToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/toadlets/AdminToadlet.java
@@ -1,160 +1,161 @@
-package plugins.schwachkopfeinsteck;
+package plugins.schwachkopfeinsteck.toadlets;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
+import plugins.schwachkopfeinsteck.GitPlugin;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class AdminToadlet extends WebInterfaceToadlet {
private static final String PARAM_PORT = "port";
private static final String PARAM_BINDTO = "bindto";
private static final String PARAM_ALLOWEDHOSTS = "allowedhosts";
private static final String PARAM_CACHEDIR = "chachedir";
private static final String PARAM_READONLY = "readonly";
private static final String CMD_START = "start";
private static final String CMD_STOP = "stop";
private static final String CMD_RESTART = "restart";
private static final String CMD_APPLY = "apply";
private final AnonymousGitDaemon daemon;
public AdminToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "admin");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!normalizePath(req.getPath()).equals("/")) {
errors.add("The path '"+uri+"' was not found");
}
makePage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makePage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_STOP)) {
daemon.stop();
} else {
String bindTo = request.getPartAsString(PARAM_BINDTO, 50);
int port = request.getIntPart(PARAM_PORT, 9481);
String allowedHosts = request.getPartAsString(PARAM_ALLOWEDHOSTS, 50);
String ro = request.getPartAsString(PARAM_READONLY, 50);
if (request.isPartSet(CMD_START)) {
daemon.setAdress(bindTo, port, allowedHosts, false);
daemon.setReadOnly(ro.length() > 0);
daemon.start();
} else if (request.isPartSet(CMD_RESTART)) {
daemon.stop();
try {
//sleep 3 sec, give the old bind a chance to vanishâ¦
Thread.sleep(3000);
} catch (InterruptedException e) {
// ignored
}
daemon.setAdress(bindTo, port, allowedHosts, false);
daemon.setReadOnly(ro.length() > 0);
daemon.start();
} else {
errors.add("Unknown command.");
}
}
makePage(ctx, errors);
}
private void makePage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin the git server", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, path(), null, null));
errors.clear();
}
makeCommonBox(contentNode);
makeSimpleBox(contentNode);
makeSSHBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCommonBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Common settings", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "commonForm");
boxForm.addChild("#", "GitPlugin uses a local cache to serve from. Congratulation, you have found the reference point for 'backup'.");
boxForm.addChild("br");
boxForm.addChild("#", "Cache dir: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value", "disabled"}, new String[] { "text", PARAM_CACHEDIR, "50", daemon.getCacheDir(), "disabled" });
boxForm.addChild("br");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_APPLY, "Apply", "disabled" });
}
private void makeSimpleBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Simple git server (git://)", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "simpleServerForm");
boxForm.addChild("#", "This is the anonymous git server. No authentication/encryption/accesscontrol at all. Be carefully.");
boxForm.addChild("br");
boxForm.addChild("#", "Port: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_PORT, "7", "9418" });
boxForm.addChild("br");
boxForm.addChild("#", "Bind to: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_BINDTO, "20", "127.0.0.1" });
boxForm.addChild("br");
boxForm.addChild("#", "Allowed hosts: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_ALLOWEDHOSTS, "20", "127.0.0.1" });
boxForm.addChild("br");
if (daemon.isReadOnly()) {
boxForm.addChild("input", new String[] { "type", "name", "value", "checked" }, new String[] { "checkbox", PARAM_READONLY, "ok", "checked" });
} else {
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "checkbox", PARAM_READONLY, "ok" });
}
boxForm.addChild("#", "\u00a0Read only access");
boxForm.addChild("br");
boxForm.addChild("br");
if (daemon.isRunning()) {
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_START, "Start", "disabled" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_STOP, "Stop" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_RESTART, "Restart" });
} else {
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_START, "Start"});
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_STOP, "Stop", "disabled" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_RESTART, "Restart", "disabled" });
}
}
private void makeSSHBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "SSH git server (git+ssh://)", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "sshServerForm");
boxForm.addChild("#", "Setting up SSH for an 'Just an idea' implementation is far to much. Sorry folks.");
boxForm.addChild("br");
boxForm.addChild("#", "Basic code for SSH (jSch) is in, just send patches ;)");
}
}
diff --git a/src/plugins/schwachkopfeinsteck/BrowseToadlet.java b/src/plugins/schwachkopfeinsteck/toadlets/BrowseToadlet.java
similarity index 95%
rename from src/plugins/schwachkopfeinsteck/BrowseToadlet.java
rename to src/plugins/schwachkopfeinsteck/toadlets/BrowseToadlet.java
index adab126..2766104 100644
--- a/src/plugins/schwachkopfeinsteck/BrowseToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/toadlets/BrowseToadlet.java
@@ -1,53 +1,54 @@
-package plugins.schwachkopfeinsteck;
+package plugins.schwachkopfeinsteck.toadlets;
import java.io.IOException;
import java.net.URI;
+import plugins.schwachkopfeinsteck.GitPlugin;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class BrowseToadlet extends WebInterfaceToadlet {
private static final String PARAM_URI = "URI";
private static final String CMD_BROWSE = "browse";
private final AnonymousGitDaemon daemon;
public BrowseToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
makePage(ctx);
}
private void makePage(ToadletContext ctx) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Browse git repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Browsa a git repos", contentNode);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "uriForm");
boxForm.addChild("#", "Not implemented yet.");
boxForm.addChild("br");
boxForm.addChild("#", "Repos URI: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size"}, new String[] { "text", PARAM_URI, "70" });
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_BROWSE, "Open", "disabled" });
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
}
diff --git a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
similarity index 99%
rename from src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
rename to src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
index 794862a..e14a5c0 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/toadlets/RepositoriesToadlet.java
@@ -1,426 +1,427 @@
-package plugins.schwachkopfeinsteck;
+package plugins.schwachkopfeinsteck.toadlets;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jgit.lib.Repository;
+import plugins.schwachkopfeinsteck.GitPlugin;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.keys.FreenetURI;
import freenet.node.useralerts.SimpleUserAlert;
import freenet.node.useralerts.UserAlert;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
private static final String CMD_BROWSE = "browse";
private static final String CMD_CREATE = "create";
private static final String CMD_DELETE = "delete";
private static final String CMD_FORK = "fork";
private static final String CMD_SAVEDESCRIPTION = "save";
private static final String PARAM_DELETECONFIRM = "deleteconfirm";
private static final String PARAM_DESCRIPTION = "description";
private static final String PARAM_INSERTURI = "inserturi";
private static final String PARAM_NAME = "name";
private static final String PARAM_REPOSNAME = "reposuri";
private static final String PARAM_REQUESTURI = "requesturi";
private static final String PARAM_SOURCE = "source";
private static final String PARAM_URI = "uri";
private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
// '/', ';', '?' are forbidden to not confuse the URL parser,
// all others are forbidden to prevent file system clashes
private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
List<String> errors = new LinkedList<String>();
makeMainPage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makeMainPage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
try {
updateDescription(repos, desc);
} catch (IOException e) {
e.printStackTrace();
errors.add("Error while updating description : "+e.getLocalizedMessage());
}
} else if (request.isPartSet(CMD_DELETE)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
if (request.isPartSet(PARAM_DELETECONFIRM)) {
deleteRepository(repos);
} else {
makeDeleteConfirmPage(ctx, repos);
return;
}
} else if (request.isPartSet(CMD_CREATE)) {
String name = request.getPartAsString(PARAM_NAME, 1024);
String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
errors.add("Are you jokingly? Every field is empty.");
} else {
if ((rUri.length() == 0) && (iUri.length() == 0)) {
FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
iUri = kp[0].setDocName(null).toString(false, false);
rUri = kp[1].setDocName(null).toString(false, false);
errors.add("URI was empty, I generated one for you.");
}
name = sanitizeDocName(name, errors);
// TODO some more uri wodoo
// a bare fetch uri means import, a bare insert uri get its fetch uri added
// try to get name from uri if name is not given
// auto convert ssk
// etc pp
if (errors.size() == 0) {
tryCreateRepository(name, rUri, iUri, errors);
}
if (errors.size() > 0) {
makeCreatePage(ctx, name, rUri, iUri, errors);
return;
}
makeCreatedReposPage(ctx, name, rUri, iUri, errors);
}
} else {
errors.add("Did not understand. Maybe not implemented jet? :P");
}
makeMainPage(ctx, errors);
}
private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, null, null, null);
makeForkBox(contentNode, null, null, null);
makeRepositoryBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeDeleteConfirmBox(contentNode, reposName);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeCreatedReposBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
boxForm.addChild("b", reposName);
boxForm.addChild("br");
boxForm.addChild("a", "href", path(), "Hell, NO!");
boxForm.addChild("#", "\u00a0");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
}
private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
box.addChild("#", "Created a new repository. Congratz!");
box.addChild("br");
box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+rUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
box.addChild("br");
box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9418/U"+iUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
}
private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Request URI:\u00a0 ");
if (rUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (iUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
}
private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
if (source != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (uri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
}
private void makeRepositoryBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
File cacheDir = daemon.getCacheDirFile();
File[] dirs = cacheDir.listFiles();
if (dirs.length == 0) {
box.addChild("#", "No repositories set up.");
return;
}
HTMLNode table = box.addChild("table", "width", "100%");
HTMLNode tableHead = table.addChild("thead");
HTMLNode tableRow = tableHead.addChild("tr");
HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
nextTableCell.addChild("#", "Name");
nextTableCell = tableRow.addChild("th");
nextTableCell.addChild("#", "Description");
for (File dir: dirs) {
HTMLNode htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeNameCell(dir));
htmlTableRow.addChild(makeDescriptionCell(dir));
htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeDeleteCell(dir));
htmlTableRow.addChild(makeEmptyCell());
htmlTableRow.addChild(makeForkCell(dir));
}
}
private HTMLNode makeEmptyCell() {
HTMLNode cell = new HTMLNode("td");
cell.addChild("#", "\u00a0");
return cell;
}
private HTMLNode makeNameCell(File repos) {
HTMLNode cell = new HTMLNode("td", "colspan", "3");
String dirName = repos.getName();
cell.addChild("b", dirName);
return cell;
}
private HTMLNode makeDescriptionCell(File repos) {
HTMLNode cell = new HTMLNode("td", "rowspan", "2");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
String desc = getReposDescription(repos);
if (desc != null) {
area.addChild("#", desc);
} else {
area.addChild("#", "\u00a0");
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
return cell;
}
private HTMLNode makeDeleteCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
return cell;
}
private HTMLNode makeForkCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
return cell;
}
private String getReposDescription(File dir) {
File descfile = new File(dir, "description");
if (!descfile.exists()) return "<Describe me!>";
String desc;
try {
desc = FileUtil.readUTF(descfile);
} catch (IOException e) {
Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
return "Error: "+e.getLocalizedMessage();
}
return desc;
}
private void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(daemon.getCacheDirFile(), repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
File descfile = new File(repos, "description");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
private void deleteRepository(String reposName) {
File repos = new File(daemon.getCacheDirFile(), reposName);
FileUtil.removeAll(repos);
}
private String getReposURI(File repos) {
return repos.getName();
}
private String getReposURI(String repos) {
return repos;
}
private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
String dirName = rUri + '@' + name;
File reposDir = new File(daemon.getCacheDirFile(), dirName);
Repository repos;
try {
repos = new Repository(reposDir);
repos.create(true);
} catch (IOException e) {
Logger.error(this, "Error while create repository: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
return;
}
String comment = "add a description here";
String alert = "Due lack of a better idea the URIs are noted here:\n"+
"Created Repository :"+dirName+"\n"+
"Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
"Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
pluginContext.clientCore.alerts.register(new SimpleUserAlert(true, "Repository created", alert, "Repository created", UserAlert.MINOR));
try {
updateDescription(reposDir, comment);
} catch (IOException e) {
Logger.error(this, "Error while updating repository description for: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
}
}
private String sanitizeDocName(String docName, List<String> errors) {
int len = docName.length();
for (int i=0 ; i<len ; i++) {
char c = docName.charAt(i);
if (forbiddenChars.contains(c)) {
errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
}
}
return docName;
}
}
|
saces/SchwachkopfEinsteck
|
efc79b9064c0ed1a8c55c1c2a643a1c075310b02
|
remove TODO for submodules. submodules are objects too (like anything in git), so it is clients problem to deal with, not servers.
|
diff --git a/README b/README
index 83e7012..14171cf 100644
--- a/README
+++ b/README
@@ -1,92 +1,90 @@
SchwachkopfEinsteck
===================
'SchwachkopfEinsteck' is german, it just translates to 'GitPlugin' :)
Prebuilt version: http://github.com/saces/SchwachkopfEinsteck/downloads
Just load the latest, it should go intuitiveâ¦
Source Version for the impatient:
Clone/update the repository, cd into it, update submodules and type 'ant'.
Grab the plugin from dist/SchwachkopfEinsteck.jar and load itâ¦
get sources (a fresh clone):
get the super project
git clone git://github.com/saces/SchwachkopfEinsteck.git SchwachkopfEinsteck
cd SchwachkopfEinsteck
init and update submodules
git submodule init
git submodule update
update sources:
update the super project
git pull git://github.com/saces/SchwachkopfEinsteck.git
update submodules
git submodule update
build:
cd into the project root and type 'ant'.
The new created plugin will be dist/SchwachkopfEinsteck.jar
configuration:
After loading the plugin visit http://127.0.0.1:8888/GitPlugin/admin or
'Git Tools'->'Admin' in the menu. Adjust the host and port if needed
(usually this should not be necessary) and press 'Start'.
Using It:
GO! GO! GO!
go to http://127.0.0.1:8889/GitPlugin/repos (Menu->Git Tools->Repositories)
create a new repository.
copy the inserturi from sucess page
git remote add <pasteithere> myFreenetRepos
or
git remote add git://127.0.0.1:9418/USK@inserturi,ABC/name/0/ myFreenetRepos
now push to it
git push myFreenetRepos master
or
git push git://127.0.0.1:9418/USK@inserturi,ABC/name/0/
fetch is work in progress, so you have to pull/fetch via fproxy for now
git clone http://127.0.0.1:8888/USK@requesturi,ADC/name/0/
git pull http://127.0.0.1:8888/USK@requesturi,ADC/name/0/
--obsolete--
Qualifying: (testing local repository creation, anonymous git transport)
go to http://127.0.0.1:8889/GitPlugin/repos (Menu->Git Tools->Repositories)
if any repository is left from warmup round, delete it
create a new repository.
for now the URIs are noted in the repository description.
git push git://127.0.0.1:9418/USK@crypticbitpuree,ABC/name/0/
git pull git://127.0.0.1:9418/USK@crypticbitpuree,ADC/name/0/
happy qualifying ;)
Warmup round: (testing the anonymous git transport)
create a bare repository in gitcache/test
cd <freenetdir>
mkdir gitcache
cd gitcache
mkdir test
cd test
git --bare init
the repository name ('test') is hardcoded for testing the anonymous git
transport. so any remote repository ends up in the repository you just
created.
git push git://127.0.0.1:9418/ignoredreposname
git pull git://127.0.0.1:9418/ignoredreposname
happy warm up testing ;)
TODO & Issues
=============
* local repository caching and locking
* implement synchronization from freenet to local cache (pull/fetch)
-* figure out what 'submodule' needs server side, implement what needed
-
|
saces/SchwachkopfEinsteck
|
f288fef2b81bc0cc2c93003dfb78f024fb941d94
|
resolve dependicy for native git, update-server-info is generated on the fly
|
diff --git a/src/plugins/schwachkopfeinsteck/ReposInserter1.java b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
index adbfaf2..e307ae0 100644
--- a/src/plugins/schwachkopfeinsteck/ReposInserter1.java
+++ b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
@@ -1,126 +1,212 @@
package plugins.schwachkopfeinsteck;
+import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStreamWriter;
import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.ObjectDatabase;
+import org.eclipse.jgit.lib.ObjectDirectory;
+import org.eclipse.jgit.lib.PackFile;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevFlag;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.transport.RefAdvertiser;
import com.db4o.ObjectContainer;
import freenet.client.InsertContext;
import freenet.client.InsertException;
import freenet.client.async.BaseManifestPutter;
import freenet.client.async.ClientPutCallback;
import freenet.client.async.DatabaseDisabledException;
import freenet.client.async.ManifestElement;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
import freenet.support.api.Bucket;
import freenet.support.io.ArrayBucket;
import freenet.support.io.BucketTools;
import freenet.support.io.Closer;
import freenet.support.io.TempBucketFactory;
import freenet.support.plugins.helpers1.PluginContext;
public class ReposInserter1 extends BaseManifestPutter {
public ReposInserter1(ClientPutCallback cb,
- File reposDir, short prioClass,
+ File reposDir, Repository db, short prioClass,
FreenetURI target, String defaultName, InsertContext ctx,
boolean getCHKOnly2, RequestClient clientContext,
boolean earlyEncode, TempBucketFactory tempBucketFactory) {
- super(cb, paramTrick(reposDir, tempBucketFactory), prioClass, target, defaultName, ctx, getCHKOnly2,
+ super(cb, paramTrick(reposDir, db, tempBucketFactory), prioClass, target, defaultName, ctx, getCHKOnly2,
clientContext, earlyEncode);
}
- private static HashMap<String, Object> paramTrick(File reposDir, TempBucketFactory tbf) {
+ private static HashMap<String, Object> paramTrick(File reposDir, Repository db, TempBucketFactory tbf) {
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("rDir", reposDir);
result.put("tbf", tbf);
+ result.put("db", db);
return result;
}
@Override
protected void makePutHandlers(HashMap<String, Object> manifestElements,
String defaultName) {
File reposDir = (File) manifestElements.get("rDir");
TempBucketFactory tbf = (TempBucketFactory) manifestElements.get("tbf");
+ Repository db = (Repository) manifestElements.get("db");
+
+ // make the default page
String defaultText = "This is a git repository.";
Bucket b = new ArrayBucket(defaultText.getBytes());
ManifestElement defaultItem = new ManifestElement("defaultText", b, "text/plain", b.size());
freenet.client.async.BaseManifestPutter.ContainerBuilder container = getRootContainer();
container.addItem("defaultText", defaultItem, true);
+
+ // generate info files for dumb servers (fproxy)
+ container.pushCurrentDir();
+ container.pushCurrentDir();
try {
+ // info/refs
+ Bucket refs = generateInfoRefs(db, tbf);
+ ManifestElement refsItem = new ManifestElement("refs", refs, "text/plain", refs.size());
+ container.makeSubDirCD("info");
+ container.addItem("refs", refsItem, false);
+ container.popCurrentDir();
+
+ // objects/info/packs
+ Bucket packs = generateObjectsInfoPacks(db, tbf);
+ ManifestElement packsItem = new ManifestElement("packs", packs, "text/plain", packs.size());
+ container.makeSubDirCD("objects");
+ container.makeSubDirCD("info");
+ container.addItem("packs", packsItem, false);
+ container.popCurrentDir();
+
parseDir(reposDir, container, tbf);
} catch (IOException e) {
e.printStackTrace();
throw new Error(e);
}
}
+ private Bucket generateInfoRefs(Repository db, TempBucketFactory tbf) throws IOException {
+ Bucket result = tbf.makeBucket(-1);
+ final RevWalk walk = new RevWalk(db);
+ final RevFlag ADVERTISED = walk.newFlag("ADVERTISED");
+
+ final OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(result.getOutputStream()), Constants.CHARSET);
+
+ final RefAdvertiser adv = new RefAdvertiser() {
+ @Override
+ protected void writeOne(final CharSequence line) throws IOException {
+ // Whoever decided that info/refs should use a different
+ // delimiter than the native git:// protocol shouldn't
+ // be allowed to design this sort of stuff. :-(
+ out.append(line.toString().replace(' ', '\t'));
+ }
+
+ @Override
+ protected void end() {
+ // No end marker required for info/refs format.
+ }
+ };
+ adv.init(walk, ADVERTISED);
+ adv.setDerefTags(true);
+
+ Map<String, Ref> refs = db.getAllRefs();
+ refs.remove(Constants.HEAD);
+ adv.send(refs);
+ out.close();
+ result.setReadOnly();
+ return result;
+ }
+
+ private Bucket generateObjectsInfoPacks(Repository db, TempBucketFactory tbf) throws IOException {
+ Bucket result = tbf.makeBucket(-1);
+
+ final OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(result.getOutputStream()), Constants.CHARSET);
+ final ObjectDatabase ob = db.getObjectDatabase();
+ if (ob instanceof ObjectDirectory) {
+ for (PackFile pack : ((ObjectDirectory) ob).getPacks()) {
+ out.append("P ");
+ out.append(pack.getPackFile().getName());
+ out.append('\n');
+ }
+ }
+ out.append('\n');
+ out.close();
+ result.setReadOnly();
+ return result;
+ }
+
private void parseDir(File dir, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
container.pushCurrentDir();
container.makeSubDirCD(file.getName());
parseDir(file, container, tbf);
container.popCurrentDir();
} else {
addFile(file, container, tbf);
}
}
}
private void addFile(File file, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
Bucket b = makeBucket(file, tbf);
ManifestElement me = new ManifestElement(file.getName(), b, "text/plain", b.size());
container.addItem(file.getName(), me, false);
}
private Bucket makeBucket(File file, TempBucketFactory tbf) throws IOException {
Bucket b = tbf.makeBucket(file.length());
InputStream is = new FileInputStream(file);
try {
BucketTools.copyFrom(b, is, Long.MAX_VALUE);
} catch (IOException e) {
Closer.close(b);
throw e;
} finally {
Closer.close(is);
}
b.setReadOnly();
return b;
}
- public static FreenetURI insert(File reposDir, FreenetURI insertURI, PluginContext pluginContext) throws InsertException {
+ public static FreenetURI insert(Repository db, File reposDir, FreenetURI insertURI, PluginContext pluginContext) throws InsertException {
RequestClient rc = new RequestClient() {
public boolean persistent() {
return false;
}
public void removeFrom(ObjectContainer container) {
}
};
InsertContext iCtx = pluginContext.hlsc.getInsertContext(true);
iCtx.compressorDescriptor = "LZMA";
VerboseWaiter pw = new VerboseWaiter();
- ReposInserter1 dmp = new ReposInserter1(pw, reposDir, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
+ ReposInserter1 dmp = new ReposInserter1(pw, reposDir, db, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
iCtx.eventProducer.addEventListener(pw);
try {
pluginContext.clientCore.clientContext.start(dmp);
} catch (DatabaseDisabledException e) {
// Impossible
}
FreenetURI result;
try {
result = pw.waitForCompletion();
} finally {
iCtx.eventProducer.removeEventListener(pw);
}
return result;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index 80affb5..4be1244 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,177 +1,166 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.PacketLineOut;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.UploadPack;
import plugins.schwachkopfeinsteck.ReposInserter1;
import freenet.client.InsertException;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableUSK;
import freenet.support.Executor;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
import freenet.support.plugins.helpers1.PluginContext;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private final boolean isReadOnly;
private final Executor eXecutor;
private final PluginContext pluginContext;
public AnonymousGitService(boolean readOnly, Executor executor, PluginContext plugincontext) {
isReadOnly = readOnly;
eXecutor = executor;
pluginContext = plugincontext;
}
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
//System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
// adjust uri string
if (reposName.startsWith("/")) {
reposName = reposName.substring(1);
}
if (!reposName.endsWith("/")) {
reposName = reposName + '/';
}
// reposname is the uri
FreenetURI iUri = null;
FreenetURI rUri = new FreenetURI(reposName);
if (!rUri.isUSK()) {
fatal(rawOut, "Repository uri must be an USK");
return;
}
if(rUri.getExtra()[1] == 1) {
iUri = rUri;
InsertableUSK iUsk = InsertableUSK.createInsertable(rUri, false);
rUri = iUsk.getURI();
}
//System.out.print("händle:"+command);
//System.out.println(" for:"+reposName);
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Repository db = getRepository(reposName);
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) {
fatal(rawOut, "Server is read only.");
return;
}
if (iUri == null) {
fatal(rawOut, "Try an insert uri for push.");
return;
}
- Repository db = getRepository(reposName);
+ final Repository db = getRepository(reposName);
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
final FreenetURI insertURI = iUri;
final File reposDir = getRepositoryPath(reposName);
- // FIXME
- Process p = Runtime.getRuntime().exec("git update-server-info --force", null, reposDir);
- try {
- p.waitFor();
- } catch (InterruptedException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- // BAH, do not insert
- return;
- }
-
// FIXME
// trigger the upload, the quick&dirty way
eXecutor.execute(new Runnable (){
public void run() {
try {
- ReposInserter1.insert(reposDir, insertURI, pluginContext);
+ ReposInserter1.insert(db, reposDir, insertURI, pluginContext);
} catch (InsertException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});
} else {
fatal(rawOut, "Unknown command: "+command);
System.err.println("Unknown command: "+command);
}
//System.out.println("x händle request: pfertsch");
}
private File getRepositoryPath(String reposname) throws IOException {
FreenetURI uri = new FreenetURI(reposname);
if(uri.getExtra()[1] == 1) {
InsertableUSK iUsk = InsertableUSK.createInsertable(uri, false);
uri = iUsk.getURI();
}
String docName = uri.getDocName();
uri = uri.setKeyType("SSK");
String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
return new File("gitcache", reposName + '@' + docName).getCanonicalFile();
}
private Repository getRepository(String reposname) throws IOException {
Repository db;
File path = getRepositoryPath(reposname);
db = new Repository(path);
return db;
}
private void fatal(OutputStream rawOut, String string) throws IOException {
PacketLineOut pckOut = new PacketLineOut(rawOut);
byte[] data = ("ERR "+string).getBytes();
pckOut.writePacket(data);
pckOut.flush();
rawOut.flush();
}
}
|
saces/SchwachkopfEinsteck
|
ad9982ee45269f5a1498439e2de0c07d6884871a
|
Version 1
|
diff --git a/src/plugins/schwachkopfeinsteck/Version.java b/src/plugins/schwachkopfeinsteck/Version.java
index d334020..3d5c708 100644
--- a/src/plugins/schwachkopfeinsteck/Version.java
+++ b/src/plugins/schwachkopfeinsteck/Version.java
@@ -1,31 +1,31 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.schwachkopfeinsteck;
/**
* @author saces
*
*/
public class Version {
/** SVN revision number. Only set if the plugin is compiled properly e.g. by emu. */
public static final String gitRevision = "@custom@";
/** Version number of the plugin for getRealVersion(). Increment this on making
* a major change, a significant bugfix etc. These numbers are used in auto-update
* etc, at a minimum any build inserted into auto-update should have a unique
* version.
*/
- private static final long realVersion = 0;
+ private static final long realVersion = 1;
- private static final String longVersionString = "Just an idea " + gitRevision;
+ private static final String longVersionString = "0.0.0 " + gitRevision;
public static String getLongVersionString() {
return longVersionString;
}
public static long getRealVersion() {
return realVersion;
}
}
|
saces/SchwachkopfEinsteck
|
d8ea747e4fa02df98e670c02897283b32953a123
|
add some preliminary insert code
|
diff --git a/src/plugins/schwachkopfeinsteck/GitPlugin.java b/src/plugins/schwachkopfeinsteck/GitPlugin.java
index 3d0c476..b0cb99d 100644
--- a/src/plugins/schwachkopfeinsteck/GitPlugin.java
+++ b/src/plugins/schwachkopfeinsteck/GitPlugin.java
@@ -1,78 +1,78 @@
package plugins.schwachkopfeinsteck;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.l10n.BaseL10n.LANGUAGE;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginRealVersioned;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Logger;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterface;
public class GitPlugin implements FredPlugin, FredPluginL10n, FredPluginThreadless, FredPluginVersioned, FredPluginRealVersioned {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
public static final String PLUGIN_URI = "/GitPlugin";
private static final String PLUGIN_CATEGORY = "Git Tools";
public static final String PLUGIN_TITLE = "Git Plugin";
private PluginContext pluginContext;
private WebInterface webInterface;
private AnonymousGitDaemon simpleDaemon;
public void runPlugin(PluginRespirator pluginRespirator) {
pluginContext = new PluginContext(pluginRespirator);
// for now a single server only, later versions can do multiple servers
// and each can have its own cache/config
- simpleDaemon = new AnonymousGitDaemon("huhu", pluginContext.node.executor);
+ simpleDaemon = new AnonymousGitDaemon("huhu", pluginContext.node.executor, pluginContext);
simpleDaemon.setCacheDir("./gitcache");
webInterface = new WebInterface(pluginContext);
webInterface.addNavigationCategory(PLUGIN_URI+"/", PLUGIN_CATEGORY, "Git Toolbox", this);
// Visible pages
BrowseToadlet browseToadlet = new BrowseToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(browseToadlet, PLUGIN_CATEGORY, "Browse", "Browse a git repository like GitWeb");
AdminToadlet adminToadlet = new AdminToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(adminToadlet, PLUGIN_CATEGORY, "Admin", "Admin the git server");
RepositoriesToadlet reposToadlet = new RepositoriesToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(reposToadlet, PLUGIN_CATEGORY, "Repositories", "Create & Delete server's repositories");
}
public void terminate() {
webInterface.kill();
if (simpleDaemon.isRunning())
simpleDaemon.stop();
simpleDaemon = null;
}
public String getString(String key) {
// return the key for now, l10n comes later
return key;
}
public void setLanguage(LANGUAGE newLanguage) {
// ignored for now, l10n comes later
}
public String getVersion() {
return Version.getLongVersionString();
}
public long getRealVersion() {
return Version.getRealVersion();
}
}
diff --git a/src/plugins/schwachkopfeinsteck/ReposInserter1.java b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
new file mode 100644
index 0000000..adbfaf2
--- /dev/null
+++ b/src/plugins/schwachkopfeinsteck/ReposInserter1.java
@@ -0,0 +1,126 @@
+package plugins.schwachkopfeinsteck;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+
+import com.db4o.ObjectContainer;
+
+import freenet.client.InsertContext;
+import freenet.client.InsertException;
+import freenet.client.async.BaseManifestPutter;
+import freenet.client.async.ClientPutCallback;
+import freenet.client.async.DatabaseDisabledException;
+import freenet.client.async.ManifestElement;
+import freenet.keys.FreenetURI;
+import freenet.node.RequestClient;
+import freenet.support.api.Bucket;
+import freenet.support.io.ArrayBucket;
+import freenet.support.io.BucketTools;
+import freenet.support.io.Closer;
+import freenet.support.io.TempBucketFactory;
+import freenet.support.plugins.helpers1.PluginContext;
+
+public class ReposInserter1 extends BaseManifestPutter {
+
+ public ReposInserter1(ClientPutCallback cb,
+ File reposDir, short prioClass,
+ FreenetURI target, String defaultName, InsertContext ctx,
+ boolean getCHKOnly2, RequestClient clientContext,
+ boolean earlyEncode, TempBucketFactory tempBucketFactory) {
+ super(cb, paramTrick(reposDir, tempBucketFactory), prioClass, target, defaultName, ctx, getCHKOnly2,
+ clientContext, earlyEncode);
+ }
+
+ private static HashMap<String, Object> paramTrick(File reposDir, TempBucketFactory tbf) {
+ HashMap<String, Object> result = new HashMap<String, Object>();
+ result.put("rDir", reposDir);
+ result.put("tbf", tbf);
+ return result;
+ }
+
+ @Override
+ protected void makePutHandlers(HashMap<String, Object> manifestElements,
+ String defaultName) {
+ File reposDir = (File) manifestElements.get("rDir");
+ TempBucketFactory tbf = (TempBucketFactory) manifestElements.get("tbf");
+ String defaultText = "This is a git repository.";
+ Bucket b = new ArrayBucket(defaultText.getBytes());
+ ManifestElement defaultItem = new ManifestElement("defaultText", b, "text/plain", b.size());
+ freenet.client.async.BaseManifestPutter.ContainerBuilder container = getRootContainer();
+ container.addItem("defaultText", defaultItem, true);
+ try {
+ parseDir(reposDir, container, tbf);
+ } catch (IOException e) {
+ e.printStackTrace();
+ throw new Error(e);
+ }
+ }
+
+ private void parseDir(File dir, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
+ File[] files = dir.listFiles();
+ for (File file : files) {
+ if (file.isDirectory()) {
+ container.pushCurrentDir();
+ container.makeSubDirCD(file.getName());
+ parseDir(file, container, tbf);
+ container.popCurrentDir();
+ } else {
+ addFile(file, container, tbf);
+ }
+ }
+ }
+
+ private void addFile(File file, ContainerBuilder container, TempBucketFactory tbf) throws IOException {
+ Bucket b = makeBucket(file, tbf);
+ ManifestElement me = new ManifestElement(file.getName(), b, "text/plain", b.size());
+ container.addItem(file.getName(), me, false);
+ }
+
+ private Bucket makeBucket(File file, TempBucketFactory tbf) throws IOException {
+ Bucket b = tbf.makeBucket(file.length());
+ InputStream is = new FileInputStream(file);
+ try {
+ BucketTools.copyFrom(b, is, Long.MAX_VALUE);
+ } catch (IOException e) {
+ Closer.close(b);
+ throw e;
+ } finally {
+ Closer.close(is);
+ }
+ b.setReadOnly();
+ return b;
+ }
+
+ public static FreenetURI insert(File reposDir, FreenetURI insertURI, PluginContext pluginContext) throws InsertException {
+ RequestClient rc = new RequestClient() {
+ public boolean persistent() {
+ return false;
+ }
+ public void removeFrom(ObjectContainer container) {
+ }
+
+ };
+ InsertContext iCtx = pluginContext.hlsc.getInsertContext(true);
+ iCtx.compressorDescriptor = "LZMA";
+ VerboseWaiter pw = new VerboseWaiter();
+ ReposInserter1 dmp = new ReposInserter1(pw, reposDir, (short) 1, insertURI.setMetaString(null), "index.html", iCtx, false, rc, false, pluginContext.clientCore.tempBucketFactory);
+ iCtx.eventProducer.addEventListener(pw);
+ try {
+ pluginContext.clientCore.clientContext.start(dmp);
+ } catch (DatabaseDisabledException e) {
+ // Impossible
+ }
+ FreenetURI result;
+ try {
+ result = pw.waitForCompletion();
+ } finally {
+ iCtx.eventProducer.removeEventListener(pw);
+ }
+ return result;
+ }
+
+
+}
diff --git a/src/plugins/schwachkopfeinsteck/VerboseWaiter.java b/src/plugins/schwachkopfeinsteck/VerboseWaiter.java
new file mode 100644
index 0000000..f7d8339
--- /dev/null
+++ b/src/plugins/schwachkopfeinsteck/VerboseWaiter.java
@@ -0,0 +1,39 @@
+package plugins.schwachkopfeinsteck;
+
+import com.db4o.ObjectContainer;
+
+import freenet.client.PutWaiter;
+import freenet.client.async.BaseClientPutter;
+import freenet.client.async.ClientContext;
+import freenet.client.events.ClientEvent;
+import freenet.client.events.ClientEventListener;
+import freenet.keys.FreenetURI;
+import freenet.support.Logger;
+
+public class VerboseWaiter extends PutWaiter implements ClientEventListener {
+
+ public VerboseWaiter() {
+ super();
+ }
+
+ @Override
+ public void onFetchable(BaseClientPutter state, ObjectContainer container) {
+ Logger.error(this, "Put fetchable");
+ super.onFetchable(state, container);
+ }
+
+ @Override
+ public synchronized void onGeneratedURI(FreenetURI uri, BaseClientPutter state, ObjectContainer container) {
+ Logger.error(this, "Got UriGenerated: "+uri.toString(false, false));
+ super.onGeneratedURI(uri, state, container);
+ }
+
+ public void onRemoveEventProducer(ObjectContainer container) {
+ Logger.error(this, "TODO", new Exception("TODO"));
+ }
+
+ public void receive(ClientEvent ce, ObjectContainer maybeContainer, ClientContext context) {
+ Logger.error(this, "Progress: "+ce.getDescription());
+ }
+}
+
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
index 275728b..e3f6024 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
@@ -1,51 +1,54 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.File;
import freenet.support.Executor;
import freenet.support.incubation.server.AbstractServer;
import freenet.support.incubation.server.AbstractService;
+import freenet.support.plugins.helpers1.PluginContext;
public class AnonymousGitDaemon extends AbstractServer {
private File reposdir;
private boolean isReadOnly = true;
+ private final PluginContext pluginContext;
- public AnonymousGitDaemon(String servername, Executor executor) {
+ public AnonymousGitDaemon(String servername, Executor executor, PluginContext plugincontext) {
super(servername, executor);
+ pluginContext = plugincontext;
}
@Override
protected AbstractService getService() {
- return new AnonymousGitService(isReadOnly());
+ return new AnonymousGitService(isReadOnly(), eXecutor, pluginContext);
}
public void setCacheDir(String dir) {
if (reposdir != null) {
// move
} else {
File newDir = new File(dir);
if (!newDir.exists()) {
newDir.mkdirs();
}
reposdir = newDir;
}
}
public String getCacheDir() {
return reposdir.getPath();
}
public File getCacheDirFile() {
return reposdir;
}
public void setReadOnly(boolean readOnly) {
isReadOnly = readOnly;
}
public boolean isReadOnly() {
return isReadOnly;
}
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index 76c112f..80affb5 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,138 +1,177 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.PacketLineOut;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.UploadPack;
+import plugins.schwachkopfeinsteck.ReposInserter1;
+
+import freenet.client.InsertException;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableUSK;
+import freenet.support.Executor;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
+import freenet.support.plugins.helpers1.PluginContext;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private final boolean isReadOnly;
+ private final Executor eXecutor;
+ private final PluginContext pluginContext;
- public AnonymousGitService(boolean readOnly) {
+ public AnonymousGitService(boolean readOnly, Executor executor, PluginContext plugincontext) {
isReadOnly = readOnly;
+ eXecutor = executor;
+ pluginContext = plugincontext;
}
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
//System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
// adjust uri string
if (reposName.startsWith("/")) {
reposName = reposName.substring(1);
}
if (!reposName.endsWith("/")) {
reposName = reposName + '/';
}
// reposname is the uri
FreenetURI iUri = null;
FreenetURI rUri = new FreenetURI(reposName);
if (!rUri.isUSK()) {
fatal(rawOut, "Repository uri must be an USK");
return;
}
if(rUri.getExtra()[1] == 1) {
iUri = rUri;
InsertableUSK iUsk = InsertableUSK.createInsertable(rUri, false);
rUri = iUsk.getURI();
}
//System.out.print("händle:"+command);
//System.out.println(" for:"+reposName);
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Repository db = getRepository(reposName);
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) {
fatal(rawOut, "Server is read only.");
return;
}
if (iUri == null) {
fatal(rawOut, "Try an insert uri for push.");
return;
}
Repository db = getRepository(reposName);
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
+
+ final FreenetURI insertURI = iUri;
+ final File reposDir = getRepositoryPath(reposName);
+
+ // FIXME
+ Process p = Runtime.getRuntime().exec("git update-server-info --force", null, reposDir);
+ try {
+ p.waitFor();
+ } catch (InterruptedException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ // BAH, do not insert
+ return;
+ }
+
+ // FIXME
+ // trigger the upload, the quick&dirty way
+ eXecutor.execute(new Runnable (){
+ public void run() {
+ try {
+ ReposInserter1.insert(reposDir, insertURI, pluginContext);
+ } catch (InsertException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }});
} else {
fatal(rawOut, "Unknown command: "+command);
System.err.println("Unknown command: "+command);
}
//System.out.println("x händle request: pfertsch");
}
- private Repository getRepository(String reposname) throws IOException {
+ private File getRepositoryPath(String reposname) throws IOException {
FreenetURI uri = new FreenetURI(reposname);
if(uri.getExtra()[1] == 1) {
InsertableUSK iUsk = InsertableUSK.createInsertable(uri, false);
uri = iUsk.getURI();
}
String docName = uri.getDocName();
uri = uri.setKeyType("SSK");
String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
+ return new File("gitcache", reposName + '@' + docName).getCanonicalFile();
+ }
+
+ private Repository getRepository(String reposname) throws IOException {
Repository db;
- File path = new File("gitcache", reposName + '@' + docName).getCanonicalFile();
+ File path = getRepositoryPath(reposname);
db = new Repository(path);
return db;
}
private void fatal(OutputStream rawOut, String string) throws IOException {
PacketLineOut pckOut = new PacketLineOut(rawOut);
byte[] data = ("ERR "+string).getBytes();
pckOut.writePacket(data);
pckOut.flush();
rawOut.flush();
}
}
|
saces/SchwachkopfEinsteck
|
0e80f5a194d4c34b1cf4af0e58a5d82859206e44
|
Fix port number, transposed digits.
|
diff --git a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
index 27df5a2..794862a 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
@@ -1,426 +1,426 @@
package plugins.schwachkopfeinsteck;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jgit.lib.Repository;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.keys.FreenetURI;
import freenet.node.useralerts.SimpleUserAlert;
import freenet.node.useralerts.UserAlert;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
private static final String CMD_BROWSE = "browse";
private static final String CMD_CREATE = "create";
private static final String CMD_DELETE = "delete";
private static final String CMD_FORK = "fork";
private static final String CMD_SAVEDESCRIPTION = "save";
private static final String PARAM_DELETECONFIRM = "deleteconfirm";
private static final String PARAM_DESCRIPTION = "description";
private static final String PARAM_INSERTURI = "inserturi";
private static final String PARAM_NAME = "name";
private static final String PARAM_REPOSNAME = "reposuri";
private static final String PARAM_REQUESTURI = "requesturi";
private static final String PARAM_SOURCE = "source";
private static final String PARAM_URI = "uri";
private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
// '/', ';', '?' are forbidden to not confuse the URL parser,
// all others are forbidden to prevent file system clashes
private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
List<String> errors = new LinkedList<String>();
makeMainPage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makeMainPage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
try {
updateDescription(repos, desc);
} catch (IOException e) {
e.printStackTrace();
errors.add("Error while updating description : "+e.getLocalizedMessage());
}
} else if (request.isPartSet(CMD_DELETE)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
if (request.isPartSet(PARAM_DELETECONFIRM)) {
deleteRepository(repos);
} else {
makeDeleteConfirmPage(ctx, repos);
return;
}
} else if (request.isPartSet(CMD_CREATE)) {
String name = request.getPartAsString(PARAM_NAME, 1024);
String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
errors.add("Are you jokingly? Every field is empty.");
} else {
if ((rUri.length() == 0) && (iUri.length() == 0)) {
FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
iUri = kp[0].setDocName(null).toString(false, false);
rUri = kp[1].setDocName(null).toString(false, false);
errors.add("URI was empty, I generated one for you.");
}
name = sanitizeDocName(name, errors);
// TODO some more uri wodoo
// a bare fetch uri means import, a bare insert uri get its fetch uri added
// try to get name from uri if name is not given
// auto convert ssk
// etc pp
if (errors.size() == 0) {
tryCreateRepository(name, rUri, iUri, errors);
}
if (errors.size() > 0) {
makeCreatePage(ctx, name, rUri, iUri, errors);
return;
}
makeCreatedReposPage(ctx, name, rUri, iUri, errors);
}
} else {
errors.add("Did not understand. Maybe not implemented jet? :P");
}
makeMainPage(ctx, errors);
}
private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, null, null, null);
makeForkBox(contentNode, null, null, null);
makeRepositoryBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeDeleteConfirmBox(contentNode, reposName);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeCreatedReposBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
boxForm.addChild("b", reposName);
boxForm.addChild("br");
boxForm.addChild("a", "href", path(), "Hell, NO!");
boxForm.addChild("#", "\u00a0");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
}
private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
box.addChild("#", "Created a new repository. Congratz!");
box.addChild("br");
box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
- box.addChild("code", "git://127.0.0.1:9481/U"+rUri.substring(1)+'/'+name+"/0/");
+ box.addChild("code", "git://127.0.0.1:9418/U"+rUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
box.addChild("br");
box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
- box.addChild("code", "git://127.0.0.1:9481/U"+iUri.substring(1)+'/'+name+"/0/");
+ box.addChild("code", "git://127.0.0.1:9418/U"+iUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
}
private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Request URI:\u00a0 ");
if (rUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (iUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
}
private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
if (source != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (uri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
}
private void makeRepositoryBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
File cacheDir = daemon.getCacheDirFile();
File[] dirs = cacheDir.listFiles();
if (dirs.length == 0) {
box.addChild("#", "No repositories set up.");
return;
}
HTMLNode table = box.addChild("table", "width", "100%");
HTMLNode tableHead = table.addChild("thead");
HTMLNode tableRow = tableHead.addChild("tr");
HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
nextTableCell.addChild("#", "Name");
nextTableCell = tableRow.addChild("th");
nextTableCell.addChild("#", "Description");
for (File dir: dirs) {
HTMLNode htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeNameCell(dir));
htmlTableRow.addChild(makeDescriptionCell(dir));
htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeDeleteCell(dir));
htmlTableRow.addChild(makeEmptyCell());
htmlTableRow.addChild(makeForkCell(dir));
}
}
private HTMLNode makeEmptyCell() {
HTMLNode cell = new HTMLNode("td");
cell.addChild("#", "\u00a0");
return cell;
}
private HTMLNode makeNameCell(File repos) {
HTMLNode cell = new HTMLNode("td", "colspan", "3");
String dirName = repos.getName();
cell.addChild("b", dirName);
return cell;
}
private HTMLNode makeDescriptionCell(File repos) {
HTMLNode cell = new HTMLNode("td", "rowspan", "2");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
String desc = getReposDescription(repos);
if (desc != null) {
area.addChild("#", desc);
} else {
area.addChild("#", "\u00a0");
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
return cell;
}
private HTMLNode makeDeleteCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
return cell;
}
private HTMLNode makeForkCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
return cell;
}
private String getReposDescription(File dir) {
File descfile = new File(dir, "description");
if (!descfile.exists()) return "<Describe me!>";
String desc;
try {
desc = FileUtil.readUTF(descfile);
} catch (IOException e) {
Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
return "Error: "+e.getLocalizedMessage();
}
return desc;
}
private void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(daemon.getCacheDirFile(), repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
File descfile = new File(repos, "description");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
private void deleteRepository(String reposName) {
File repos = new File(daemon.getCacheDirFile(), reposName);
FileUtil.removeAll(repos);
}
private String getReposURI(File repos) {
return repos.getName();
}
private String getReposURI(String repos) {
return repos;
}
private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
String dirName = rUri + '@' + name;
File reposDir = new File(daemon.getCacheDirFile(), dirName);
Repository repos;
try {
repos = new Repository(reposDir);
repos.create(true);
} catch (IOException e) {
Logger.error(this, "Error while create repository: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
return;
}
String comment = "add a description here";
String alert = "Due lack of a better idea the URIs are noted here:\n"+
"Created Repository :"+dirName+"\n"+
"Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
"Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
pluginContext.clientCore.alerts.register(new SimpleUserAlert(true, "Repository created", alert, "Repository created", UserAlert.MINOR));
try {
updateDescription(reposDir, comment);
} catch (IOException e) {
Logger.error(this, "Error while updating repository description for: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
}
}
private String sanitizeDocName(String docName, List<String> errors) {
int len = docName.length();
for (int i=0 ; i<len ; i++) {
char c = docName.charAt(i);
if (forbiddenChars.contains(c)) {
errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
}
}
return docName;
}
}
|
saces/SchwachkopfEinsteck
|
306f5cfcdfdf1bd4e2a4f51b8c2ca4cf6c591265
|
remove unused import
|
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index a9cfbdc..76c112f 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,139 +1,138 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.PacketLineOut;
import org.eclipse.jgit.transport.ReceivePack;
-import org.eclipse.jgit.transport.SideBandOutputStream;
import org.eclipse.jgit.transport.UploadPack;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableUSK;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private final boolean isReadOnly;
public AnonymousGitService(boolean readOnly) {
isReadOnly = readOnly;
}
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
//System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
// adjust uri string
if (reposName.startsWith("/")) {
reposName = reposName.substring(1);
}
if (!reposName.endsWith("/")) {
reposName = reposName + '/';
}
// reposname is the uri
FreenetURI iUri = null;
FreenetURI rUri = new FreenetURI(reposName);
if (!rUri.isUSK()) {
fatal(rawOut, "Repository uri must be an USK");
return;
}
if(rUri.getExtra()[1] == 1) {
iUri = rUri;
InsertableUSK iUsk = InsertableUSK.createInsertable(rUri, false);
rUri = iUsk.getURI();
}
//System.out.print("händle:"+command);
//System.out.println(" for:"+reposName);
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Repository db = getRepository(reposName);
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) {
fatal(rawOut, "Server is read only.");
return;
}
if (iUri == null) {
fatal(rawOut, "Try an insert uri for push.");
return;
}
Repository db = getRepository(reposName);
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
} else {
fatal(rawOut, "Unknown command: "+command);
System.err.println("Unknown command: "+command);
}
//System.out.println("x händle request: pfertsch");
}
private Repository getRepository(String reposname) throws IOException {
FreenetURI uri = new FreenetURI(reposname);
if(uri.getExtra()[1] == 1) {
InsertableUSK iUsk = InsertableUSK.createInsertable(uri, false);
uri = iUsk.getURI();
}
String docName = uri.getDocName();
uri = uri.setKeyType("SSK");
String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
Repository db;
File path = new File("gitcache", reposName + '@' + docName).getCanonicalFile();
db = new Repository(path);
return db;
}
private void fatal(OutputStream rawOut, String string) throws IOException {
PacketLineOut pckOut = new PacketLineOut(rawOut);
byte[] data = ("ERR "+string).getBytes();
pckOut.writePacket(data);
pckOut.flush();
rawOut.flush();
}
}
|
saces/SchwachkopfEinsteck
|
a24d07253d9062728385474cd369e0aa6e4a072e
|
make the user alert dismissable
|
diff --git a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
index 419ac39..27df5a2 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
@@ -1,426 +1,426 @@
package plugins.schwachkopfeinsteck;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jgit.lib.Repository;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.keys.FreenetURI;
import freenet.node.useralerts.SimpleUserAlert;
import freenet.node.useralerts.UserAlert;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
private static final String CMD_BROWSE = "browse";
private static final String CMD_CREATE = "create";
private static final String CMD_DELETE = "delete";
private static final String CMD_FORK = "fork";
private static final String CMD_SAVEDESCRIPTION = "save";
private static final String PARAM_DELETECONFIRM = "deleteconfirm";
private static final String PARAM_DESCRIPTION = "description";
private static final String PARAM_INSERTURI = "inserturi";
private static final String PARAM_NAME = "name";
private static final String PARAM_REPOSNAME = "reposuri";
private static final String PARAM_REQUESTURI = "requesturi";
private static final String PARAM_SOURCE = "source";
private static final String PARAM_URI = "uri";
private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
// '/', ';', '?' are forbidden to not confuse the URL parser,
// all others are forbidden to prevent file system clashes
private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
List<String> errors = new LinkedList<String>();
makeMainPage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makeMainPage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
try {
updateDescription(repos, desc);
} catch (IOException e) {
e.printStackTrace();
errors.add("Error while updating description : "+e.getLocalizedMessage());
}
} else if (request.isPartSet(CMD_DELETE)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
if (request.isPartSet(PARAM_DELETECONFIRM)) {
deleteRepository(repos);
} else {
makeDeleteConfirmPage(ctx, repos);
return;
}
} else if (request.isPartSet(CMD_CREATE)) {
String name = request.getPartAsString(PARAM_NAME, 1024);
String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
errors.add("Are you jokingly? Every field is empty.");
} else {
if ((rUri.length() == 0) && (iUri.length() == 0)) {
FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
iUri = kp[0].setDocName(null).toString(false, false);
rUri = kp[1].setDocName(null).toString(false, false);
errors.add("URI was empty, I generated one for you.");
}
name = sanitizeDocName(name, errors);
// TODO some more uri wodoo
// a bare fetch uri means import, a bare insert uri get its fetch uri added
// try to get name from uri if name is not given
// auto convert ssk
// etc pp
if (errors.size() == 0) {
tryCreateRepository(name, rUri, iUri, errors);
}
if (errors.size() > 0) {
makeCreatePage(ctx, name, rUri, iUri, errors);
return;
}
makeCreatedReposPage(ctx, name, rUri, iUri, errors);
}
} else {
errors.add("Did not understand. Maybe not implemented jet? :P");
}
makeMainPage(ctx, errors);
}
private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, null, null, null);
makeForkBox(contentNode, null, null, null);
makeRepositoryBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeDeleteConfirmBox(contentNode, reposName);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeCreatedReposBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
boxForm.addChild("b", reposName);
boxForm.addChild("br");
boxForm.addChild("a", "href", path(), "Hell, NO!");
boxForm.addChild("#", "\u00a0");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
}
private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
box.addChild("#", "Created a new repository. Congratz!");
box.addChild("br");
box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9481/U"+rUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
box.addChild("br");
box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9481/U"+iUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
}
private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Request URI:\u00a0 ");
if (rUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (iUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
}
private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
if (source != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (uri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
}
private void makeRepositoryBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
File cacheDir = daemon.getCacheDirFile();
File[] dirs = cacheDir.listFiles();
if (dirs.length == 0) {
box.addChild("#", "No repositories set up.");
return;
}
HTMLNode table = box.addChild("table", "width", "100%");
HTMLNode tableHead = table.addChild("thead");
HTMLNode tableRow = tableHead.addChild("tr");
HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
nextTableCell.addChild("#", "Name");
nextTableCell = tableRow.addChild("th");
nextTableCell.addChild("#", "Description");
for (File dir: dirs) {
HTMLNode htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeNameCell(dir));
htmlTableRow.addChild(makeDescriptionCell(dir));
htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeDeleteCell(dir));
htmlTableRow.addChild(makeEmptyCell());
htmlTableRow.addChild(makeForkCell(dir));
}
}
private HTMLNode makeEmptyCell() {
HTMLNode cell = new HTMLNode("td");
cell.addChild("#", "\u00a0");
return cell;
}
private HTMLNode makeNameCell(File repos) {
HTMLNode cell = new HTMLNode("td", "colspan", "3");
String dirName = repos.getName();
cell.addChild("b", dirName);
return cell;
}
private HTMLNode makeDescriptionCell(File repos) {
HTMLNode cell = new HTMLNode("td", "rowspan", "2");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
String desc = getReposDescription(repos);
if (desc != null) {
area.addChild("#", desc);
} else {
area.addChild("#", "\u00a0");
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
return cell;
}
private HTMLNode makeDeleteCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
return cell;
}
private HTMLNode makeForkCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
return cell;
}
private String getReposDescription(File dir) {
File descfile = new File(dir, "description");
if (!descfile.exists()) return "<Describe me!>";
String desc;
try {
desc = FileUtil.readUTF(descfile);
} catch (IOException e) {
Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
return "Error: "+e.getLocalizedMessage();
}
return desc;
}
private void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(daemon.getCacheDirFile(), repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
File descfile = new File(repos, "description");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
private void deleteRepository(String reposName) {
File repos = new File(daemon.getCacheDirFile(), reposName);
FileUtil.removeAll(repos);
}
private String getReposURI(File repos) {
return repos.getName();
}
private String getReposURI(String repos) {
return repos;
}
private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
String dirName = rUri + '@' + name;
File reposDir = new File(daemon.getCacheDirFile(), dirName);
Repository repos;
try {
repos = new Repository(reposDir);
repos.create(true);
} catch (IOException e) {
Logger.error(this, "Error while create repository: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
return;
}
String comment = "add a description here";
String alert = "Due lack of a better idea the URIs are noted here:\n"+
"Created Repository :"+dirName+"\n"+
"Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
"Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
- pluginContext.clientCore.alerts.register(new SimpleUserAlert(false, "Repository created", alert, "Repository created", UserAlert.MINOR));
+ pluginContext.clientCore.alerts.register(new SimpleUserAlert(true, "Repository created", alert, "Repository created", UserAlert.MINOR));
try {
updateDescription(reposDir, comment);
} catch (IOException e) {
Logger.error(this, "Error while updating repository description for: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
}
}
private String sanitizeDocName(String docName, List<String> errors) {
int len = docName.length();
for (int i=0 ; i<len ; i++) {
char c = docName.charAt(i);
if (forbiddenChars.contains(c)) {
errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
}
}
return docName;
}
}
|
saces/SchwachkopfEinsteck
|
76407f8afc06f32970ef653ac4268bb4878099c4
|
fix error messages, client show a proper error msg now instead protocol error
|
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index 3da15a1..a9cfbdc 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,139 +1,139 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.PacketLineOut;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.SideBandOutputStream;
import org.eclipse.jgit.transport.UploadPack;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableUSK;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private final boolean isReadOnly;
public AnonymousGitService(boolean readOnly) {
isReadOnly = readOnly;
}
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
//System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
// adjust uri string
if (reposName.startsWith("/")) {
reposName = reposName.substring(1);
}
if (!reposName.endsWith("/")) {
reposName = reposName + '/';
}
// reposname is the uri
FreenetURI iUri = null;
FreenetURI rUri = new FreenetURI(reposName);
if (!rUri.isUSK()) {
fatal(rawOut, "Repository uri must be an USK");
return;
}
if(rUri.getExtra()[1] == 1) {
iUri = rUri;
InsertableUSK iUsk = InsertableUSK.createInsertable(rUri, false);
rUri = iUsk.getURI();
}
//System.out.print("händle:"+command);
//System.out.println(" for:"+reposName);
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Repository db = getRepository(reposName);
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) {
fatal(rawOut, "Server is read only.");
return;
}
if (iUri == null) {
fatal(rawOut, "Try an insert uri for push.");
return;
}
Repository db = getRepository(reposName);
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
} else {
fatal(rawOut, "Unknown command: "+command);
System.err.println("Unknown command: "+command);
}
//System.out.println("x händle request: pfertsch");
}
private Repository getRepository(String reposname) throws IOException {
FreenetURI uri = new FreenetURI(reposname);
if(uri.getExtra()[1] == 1) {
InsertableUSK iUsk = InsertableUSK.createInsertable(uri, false);
uri = iUsk.getURI();
}
String docName = uri.getDocName();
uri = uri.setKeyType("SSK");
String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
Repository db;
File path = new File("gitcache", reposName + '@' + docName).getCanonicalFile();
db = new Repository(path);
return db;
}
private void fatal(OutputStream rawOut, String string) throws IOException {
PacketLineOut pckOut = new PacketLineOut(rawOut);
- byte[] data = string.getBytes();
- pckOut.writeChannelPacket(SideBandOutputStream.CH_ERROR, data, 0, data.length);
+ byte[] data = ("ERR "+string).getBytes();
+ pckOut.writePacket(data);
pckOut.flush();
rawOut.flush();
}
}
|
saces/SchwachkopfEinsteck
|
c8694045f78de483ec6694a9330c47e46697b227
|
send back error messages
|
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index 90d2277..3da15a1 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,107 +1,139 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
+import org.eclipse.jgit.transport.PacketLineOut;
import org.eclipse.jgit.transport.ReceivePack;
+import org.eclipse.jgit.transport.SideBandOutputStream;
import org.eclipse.jgit.transport.UploadPack;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableUSK;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private final boolean isReadOnly;
public AnonymousGitService(boolean readOnly) {
isReadOnly = readOnly;
}
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
//System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
+ // adjust uri string
if (reposName.startsWith("/")) {
reposName = reposName.substring(1);
}
if (!reposName.endsWith("/")) {
reposName = reposName + '/';
}
+ // reposname is the uri
+ FreenetURI iUri = null;
+ FreenetURI rUri = new FreenetURI(reposName);
+ if (!rUri.isUSK()) {
+ fatal(rawOut, "Repository uri must be an USK");
+ return;
+ }
+ if(rUri.getExtra()[1] == 1) {
+ iUri = rUri;
+ InsertableUSK iUsk = InsertableUSK.createInsertable(rUri, false);
+ rUri = iUsk.getURI();
+ }
+
//System.out.print("händle:"+command);
//System.out.println(" for:"+reposName);
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Repository db = getRepository(reposName);
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
- if (isReadOnly) return;
+ if (isReadOnly) {
+ fatal(rawOut, "Server is read only.");
+ return;
+ }
+ if (iUri == null) {
+ fatal(rawOut, "Try an insert uri for push.");
+ return;
+ }
Repository db = getRepository(reposName);
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
} else {
+ fatal(rawOut, "Unknown command: "+command);
System.err.println("Unknown command: "+command);
}
//System.out.println("x händle request: pfertsch");
}
private Repository getRepository(String reposname) throws IOException {
FreenetURI uri = new FreenetURI(reposname);
if(uri.getExtra()[1] == 1) {
InsertableUSK iUsk = InsertableUSK.createInsertable(uri, false);
uri = iUsk.getURI();
}
String docName = uri.getDocName();
uri = uri.setKeyType("SSK");
String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
Repository db;
File path = new File("gitcache", reposName + '@' + docName).getCanonicalFile();
db = new Repository(path);
return db;
}
+ private void fatal(OutputStream rawOut, String string) throws IOException {
+ PacketLineOut pckOut = new PacketLineOut(rawOut);
+ byte[] data = string.getBytes();
+ pckOut.writeChannelPacket(SideBandOutputStream.CH_ERROR, data, 0, data.length);
+ pckOut.flush();
+ rawOut.flush();
+ }
+
}
|
saces/SchwachkopfEinsteck
|
5fd93f5d190f7d887b2abdd9a8496bbd2915b3b9
|
do not store the private uri in description, it gets inserted⦠use an user alert instead
|
diff --git a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
index f927f09..419ac39 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
@@ -1,420 +1,426 @@
package plugins.schwachkopfeinsteck;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jgit.lib.Repository;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.keys.FreenetURI;
+import freenet.node.useralerts.SimpleUserAlert;
+import freenet.node.useralerts.UserAlert;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
private static final String CMD_BROWSE = "browse";
private static final String CMD_CREATE = "create";
private static final String CMD_DELETE = "delete";
private static final String CMD_FORK = "fork";
private static final String CMD_SAVEDESCRIPTION = "save";
private static final String PARAM_DELETECONFIRM = "deleteconfirm";
private static final String PARAM_DESCRIPTION = "description";
private static final String PARAM_INSERTURI = "inserturi";
private static final String PARAM_NAME = "name";
private static final String PARAM_REPOSNAME = "reposuri";
private static final String PARAM_REQUESTURI = "requesturi";
private static final String PARAM_SOURCE = "source";
private static final String PARAM_URI = "uri";
private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
// '/', ';', '?' are forbidden to not confuse the URL parser,
// all others are forbidden to prevent file system clashes
private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
List<String> errors = new LinkedList<String>();
makeMainPage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makeMainPage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
try {
updateDescription(repos, desc);
} catch (IOException e) {
e.printStackTrace();
errors.add("Error while updating description : "+e.getLocalizedMessage());
}
} else if (request.isPartSet(CMD_DELETE)) {
String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
if (request.isPartSet(PARAM_DELETECONFIRM)) {
deleteRepository(repos);
} else {
makeDeleteConfirmPage(ctx, repos);
return;
}
} else if (request.isPartSet(CMD_CREATE)) {
String name = request.getPartAsString(PARAM_NAME, 1024);
String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
errors.add("Are you jokingly? Every field is empty.");
} else {
if ((rUri.length() == 0) && (iUri.length() == 0)) {
FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
iUri = kp[0].setDocName(null).toString(false, false);
rUri = kp[1].setDocName(null).toString(false, false);
errors.add("URI was empty, I generated one for you.");
}
name = sanitizeDocName(name, errors);
// TODO some more uri wodoo
// a bare fetch uri means import, a bare insert uri get its fetch uri added
// try to get name from uri if name is not given
// auto convert ssk
// etc pp
if (errors.size() == 0) {
tryCreateRepository(name, rUri, iUri, errors);
}
if (errors.size() > 0) {
makeCreatePage(ctx, name, rUri, iUri, errors);
return;
}
makeCreatedReposPage(ctx, name, rUri, iUri, errors);
}
} else {
errors.add("Did not understand. Maybe not implemented jet? :P");
}
makeMainPage(ctx, errors);
}
private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, null, null, null);
makeForkBox(contentNode, null, null, null);
makeRepositoryBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeDeleteConfirmBox(contentNode, reposName);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, null, null, null));
errors.clear();
}
makeCreateBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
makeCreatedReposBox(contentNode, name, rUri, iUri);
contentNode.addChild("br");
contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
boxForm.addChild("b", reposName);
boxForm.addChild("br");
boxForm.addChild("a", "href", path(), "Hell, NO!");
boxForm.addChild("#", "\u00a0");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
}
private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
box.addChild("#", "Created a new repository. Congratz!");
box.addChild("br");
box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9481/U"+rUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
box.addChild("br");
box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
box.addChild("code", "git://127.0.0.1:9481/U"+iUri.substring(1)+'/'+name+"/0/");
box.addChild("br");
}
private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Request URI:\u00a0 ");
if (rUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (iUri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
}
private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
boxForm.addChild("br");
boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
if (source != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
}
boxForm.addChild("br");
boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
if (name != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
}
boxForm.addChild("br");
boxForm.addChild("#", "Insert URI:\u00a0 ");
if (uri != null) {
boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
} else {
boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
}
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
}
private void makeRepositoryBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
File cacheDir = daemon.getCacheDirFile();
File[] dirs = cacheDir.listFiles();
if (dirs.length == 0) {
box.addChild("#", "No repositories set up.");
return;
}
HTMLNode table = box.addChild("table", "width", "100%");
HTMLNode tableHead = table.addChild("thead");
HTMLNode tableRow = tableHead.addChild("tr");
HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
nextTableCell.addChild("#", "Name");
nextTableCell = tableRow.addChild("th");
nextTableCell.addChild("#", "Description");
for (File dir: dirs) {
HTMLNode htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeNameCell(dir));
htmlTableRow.addChild(makeDescriptionCell(dir));
htmlTableRow = table.addChild("tr");
htmlTableRow.addChild(makeDeleteCell(dir));
htmlTableRow.addChild(makeEmptyCell());
htmlTableRow.addChild(makeForkCell(dir));
}
}
private HTMLNode makeEmptyCell() {
HTMLNode cell = new HTMLNode("td");
cell.addChild("#", "\u00a0");
return cell;
}
private HTMLNode makeNameCell(File repos) {
HTMLNode cell = new HTMLNode("td", "colspan", "3");
String dirName = repos.getName();
cell.addChild("b", dirName);
return cell;
}
private HTMLNode makeDescriptionCell(File repos) {
HTMLNode cell = new HTMLNode("td", "rowspan", "2");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
String desc = getReposDescription(repos);
if (desc != null) {
area.addChild("#", desc);
} else {
area.addChild("#", "\u00a0");
}
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
return cell;
}
private HTMLNode makeDeleteCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
return cell;
}
private HTMLNode makeForkCell(File repos) {
HTMLNode cell = new HTMLNode("td");
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
return cell;
}
private String getReposDescription(File dir) {
File descfile = new File(dir, "description");
if (!descfile.exists()) return "<Describe me!>";
String desc;
try {
desc = FileUtil.readUTF(descfile);
} catch (IOException e) {
Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
return "Error: "+e.getLocalizedMessage();
}
return desc;
}
private void updateDescription(String repos, String desc) throws IOException {
File reposFile = new File(daemon.getCacheDirFile(), repos);
updateDescription(reposFile, desc);
}
private void updateDescription(File repos, String desc) throws IOException {
File descfile = new File(repos, "description");
if (descfile.exists()) {
descfile.delete();
}
InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
FileUtil.writeTo(is, descfile);
}
private void deleteRepository(String reposName) {
File repos = new File(daemon.getCacheDirFile(), reposName);
FileUtil.removeAll(repos);
}
private String getReposURI(File repos) {
return repos.getName();
}
private String getReposURI(String repos) {
return repos;
}
private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
String dirName = rUri + '@' + name;
File reposDir = new File(daemon.getCacheDirFile(), dirName);
Repository repos;
try {
repos = new Repository(reposDir);
repos.create(true);
} catch (IOException e) {
Logger.error(this, "Error while create repository: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
return;
}
- String comment = "add a description here\n\n"+
- "Due lack of a better idea the URIs are noted here:\n"+
+ String comment = "add a description here";
+
+ String alert = "Due lack of a better idea the URIs are noted here:\n"+
+ "Created Repository :"+dirName+"\n"+
"Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
"Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
+ pluginContext.clientCore.alerts.register(new SimpleUserAlert(false, "Repository created", alert, "Repository created", UserAlert.MINOR));
+
try {
updateDescription(reposDir, comment);
} catch (IOException e) {
Logger.error(this, "Error while updating repository description for: "+reposDir.getAbsolutePath(), e);
errors.add(e.getLocalizedMessage());
}
}
private String sanitizeDocName(String docName, List<String> errors) {
int len = docName.length();
for (int i=0 ; i<len ; i++) {
char c = docName.charAt(i);
if (forbiddenChars.contains(c)) {
errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
}
}
return docName;
}
}
|
saces/SchwachkopfEinsteck
|
8c0b7af514b43efdc504cd9bf9d1e343828322a1
|
add ui to maintain local repositories
|
diff --git a/README b/README
index cca188e..77d343e 100644
--- a/README
+++ b/README
@@ -1,53 +1,65 @@
SchwachkopfEinsteck
===================
'SchwachkopfEinsteck' is german, it just translates to 'GitPlugin' :)
Prebuilt version: http://github.com/saces/SchwachkopfEinsteck/downloads
Just load the latest, it should go intuitiveâ¦
Source Version for the impatient:
Clone/update the repository, cd into it, update submodules and type 'ant'.
Grab the plugin from dist/SchwachkopfEinsteck.jar and load itâ¦
get sources (a fresh clone):
get the super project
git clone git://github.com/saces/SchwachkopfEinsteck.git SchwachkopfEinsteck
cd SchwachkopfEinsteck
init and update submodules
git submodule init
git submodule update
update sources:
update the super project
git pull git://github.com/saces/SchwachkopfEinsteck.git
update submodules
git submodule update
build:
cd into the project root and type 'ant'.
The new created plugin will be dist/SchwachkopfEinsteck.jar
configuration:
After loading the plugin visit http://127.0.0.1:8888/GitPlugin/admin or
'Git Tools'->'Admin' in the menu. Adjust the host and port if needed
(usually this should not be necessary) and press 'Start'.
Using It:
- warm up round: (testing the anonymous git transport)
+ Qualifying: (testing local repository creation, anonymous git transport)
+ go to http://127.0.0.1:8889/GitPlugin/repos (Menu->Git Tools->Repositories)
+ if any repository is left from warmup round, delete it
+ create a new repository.
+ for now the URIs are noted in the repository description.
+ git push git://127.0.0.1:9418/USK@crypticbitpuree,ABC/name/0/
+ git pull git://127.0.0.1:9418/USK@crypticbitpuree,ADC/name/0/
+
+ happy qualifying ;)
+
+--obsolete--
+
+ Warmup round: (testing the anonymous git transport)
create a bare repository in gitcache/test
cd <freenetdir>
mkdir gitcache
cd gitcache
mkdir test
cd test
git --bare init
the repository name ('test') is hardcoded for testing the anonymous git
transport. so any remote repository ends up in the repository you just
created.
git push git://127.0.0.1:9418/ignoredreposname
git pull git://127.0.0.1:9418/ignoredreposname
happy warm up testing ;)
diff --git a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
index 7727451..f927f09 100644
--- a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java
@@ -1,53 +1,420 @@
package plugins.schwachkopfeinsteck;
+import java.io.ByteArrayInputStream;
+import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
import java.net.URI;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
-import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
+import org.eclipse.jgit.lib.Repository;
+import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
+import freenet.keys.FreenetURI;
import freenet.support.HTMLNode;
+import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
+import freenet.support.io.FileUtil;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class RepositoriesToadlet extends WebInterfaceToadlet {
- private static final String PARAM_URI = "URI";
private static final String CMD_BROWSE = "browse";
+ private static final String CMD_CREATE = "create";
+ private static final String CMD_DELETE = "delete";
+ private static final String CMD_FORK = "fork";
+ private static final String CMD_SAVEDESCRIPTION = "save";
+ private static final String PARAM_DELETECONFIRM = "deleteconfirm";
+ private static final String PARAM_DESCRIPTION = "description";
+ private static final String PARAM_INSERTURI = "inserturi";
+ private static final String PARAM_NAME = "name";
+ private static final String PARAM_REPOSNAME = "reposuri";
+ private static final String PARAM_REQUESTURI = "requesturi";
+ private static final String PARAM_SOURCE = "source";
+ private static final String PARAM_URI = "uri";
+
+ private static final String URI_WIDTH = "130";
private final AnonymousGitDaemon daemon;
+ // '/', ';', '?' are forbidden to not confuse the URL parser,
+ // all others are forbidden to prevent file system clashes
+ private static final HashSet<Character> forbiddenChars = new HashSet<Character>(Arrays.asList(
+ new Character[] { '/', '\\', '?', '*', ':', ';', '|', '\"', '<', '>'}));
+
public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "repos");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if (!normalizePath(req.getPath()).equals("/")) {
sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found");
return;
}
- makePage(ctx);
+ List<String> errors = new LinkedList<String>();
+ makeMainPage(ctx, errors);
+ }
+
+ public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
+
+ List<String> errors = new LinkedList<String>();
+
+ if (!isFormPassword(request)) {
+ errors.add("Invalid form password");
+ makeMainPage(ctx, errors);
+ return;
+ }
+
+ String path = normalizePath(request.getPath());
+ if (request.isPartSet(CMD_SAVEDESCRIPTION)) {
+ String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
+ String desc = request.getPartAsString(PARAM_DESCRIPTION, 4096);
+ try {
+ updateDescription(repos, desc);
+ } catch (IOException e) {
+ e.printStackTrace();
+ errors.add("Error while updating description : "+e.getLocalizedMessage());
+ }
+ } else if (request.isPartSet(CMD_DELETE)) {
+ String repos = request.getPartAsString(PARAM_REPOSNAME, 1024);
+ if (request.isPartSet(PARAM_DELETECONFIRM)) {
+ deleteRepository(repos);
+ } else {
+ makeDeleteConfirmPage(ctx, repos);
+ return;
+ }
+ } else if (request.isPartSet(CMD_CREATE)) {
+ String name = request.getPartAsString(PARAM_NAME, 1024);
+ String iUri = request.getPartAsString(PARAM_INSERTURI, 1024);
+ String rUri = request.getPartAsString(PARAM_REQUESTURI, 1024);
+ if (name.length() == 0 && rUri.length() == 0 && iUri.length() == 0) {
+ errors.add("Are you jokingly? Every field is empty.");
+ } else {
+ if ((rUri.length() == 0) && (iUri.length() == 0)) {
+ FreenetURI[] kp = getClientImpl().generateKeyPair("fake");
+ iUri = kp[0].setDocName(null).toString(false, false);
+ rUri = kp[1].setDocName(null).toString(false, false);
+ errors.add("URI was empty, I generated one for you.");
+ }
+
+ name = sanitizeDocName(name, errors);
+
+ // TODO some more uri wodoo
+ // a bare fetch uri means import, a bare insert uri get its fetch uri added
+ // try to get name from uri if name is not given
+ // auto convert ssk
+ // etc pp
+
+ if (errors.size() == 0) {
+ tryCreateRepository(name, rUri, iUri, errors);
+ }
+ if (errors.size() > 0) {
+ makeCreatePage(ctx, name, rUri, iUri, errors);
+ return;
+ }
+ makeCreatedReposPage(ctx, name, rUri, iUri, errors);
+ }
+ } else {
+ errors.add("Did not understand. Maybe not implemented jet? :P");
+ }
+ makeMainPage(ctx, errors);
}
- private void makePage(ToadletContext ctx) throws ToadletContextClosedException, IOException {
+ private void makeMainPage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
- HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Browsa a git repos", contentNode);
- HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "uriForm");
- boxForm.addChild("#", "Not implemented yet.");
- boxForm.addChild("br");
- boxForm.addChild("#", "Repos URI: \u00a0 ");
- boxForm.addChild("input", new String[] { "type", "name", "size"}, new String[] { "text", PARAM_URI, "70" });
- boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_BROWSE, "Open", "disabled" });
+ if (errors.size() > 0) {
+ contentNode.addChild(createErrorBox(errors, null, null, null));
+ errors.clear();
+ }
+
+ makeCreateBox(contentNode, null, null, null);
+ makeForkBox(contentNode, null, null, null);
+ makeRepositoryBox(contentNode);
+
+ writeHTMLReply(ctx, 200, "OK", outer.generate());
+ }
+
+ private void makeDeleteConfirmPage(ToadletContext ctx, String reposName) throws ToadletContextClosedException, IOException {
+ PageNode pageNode = pluginContext.pageMaker.getPageNode("Confirm delete", ctx);
+ HTMLNode outer = pageNode.outer;
+ HTMLNode contentNode = pageNode.content;
+
+ makeDeleteConfirmBox(contentNode, reposName);
+
+ writeHTMLReply(ctx, 200, "OK", outer.generate());
+ }
+
+ private void makeCreatePage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
+ PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
+ HTMLNode outer = pageNode.outer;
+ HTMLNode contentNode = pageNode.content;
+
+ if (errors.size() > 0) {
+ contentNode.addChild(createErrorBox(errors, null, null, null));
+ errors.clear();
+ }
+
+ makeCreateBox(contentNode, name, rUri, iUri);
+
+ contentNode.addChild("br");
+ contentNode.addChild("a", "href", path(), "Back to main");
+
+ writeHTMLReply(ctx, 200, "OK", outer.generate());
+ }
+
+ private void makeCreatedReposPage(ToadletContext ctx, String name, String rUri, String iUri, List<String> errors) throws ToadletContextClosedException, IOException {
+ PageNode pageNode = pluginContext.pageMaker.getPageNode("Create repository", ctx);
+ HTMLNode outer = pageNode.outer;
+ HTMLNode contentNode = pageNode.content;
+
+ makeCreatedReposBox(contentNode, name, rUri, iUri);
+
+ contentNode.addChild("br");
+ contentNode.addChild("a", "href", path(), "Back to main");
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
+ private void makeDeleteConfirmBox(HTMLNode parent, String reposName) {
+ HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-warning", "Delete a repository", parent);
+ HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "deleteConfirmForm");
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, reposName });
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_DELETECONFIRM, PARAM_DELETECONFIRM });
+ boxForm.addChild("#", "Confirm deletion of repository:\u00a0");
+ boxForm.addChild("b", reposName);
+ boxForm.addChild("br");
+ boxForm.addChild("a", "href", path(), "Hell, NO!");
+ boxForm.addChild("#", "\u00a0");
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
+ }
+
+ private void makeCreatedReposBox(HTMLNode parent, String name, String rUri, String iUri) {
+ HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "\\o/ Repository sucessfully created", parent);
+ box.addChild("#", "Created a new repository. Congratz!");
+ box.addChild("br");
+ box.addChild("#", "Pull URI, give it away if you want:\u00a0 ");
+ box.addChild("code", "git://127.0.0.1:9481/U"+rUri.substring(1)+'/'+name+"/0/");
+ box.addChild("br");
+ box.addChild("br");
+ box.addChild("#", "Push URI, Keep it secret! Never give away or share!:\u00a0 ");
+ box.addChild("code", "git://127.0.0.1:9481/U"+iUri.substring(1)+'/'+name+"/0/");
+ box.addChild("br");
+ }
+
+ private void makeCreateBox(HTMLNode parent, String name, String rUri, String iUri) {
+ HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Create a new repository", parent);
+ HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "createForm");
+ boxForm.addChild("#", "Create a new repository. Leave the URI fields empty to generate a new one.");
+ boxForm.addChild("br");
+ boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
+ if (name != null) {
+ boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
+ } else {
+ boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
+ }
+ boxForm.addChild("br");
+ boxForm.addChild("#", "Request URI:\u00a0 ");
+ if (rUri != null) {
+ boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH, rUri });
+ } else {
+ boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_REQUESTURI, URI_WIDTH});
+ }
+ boxForm.addChild("br");
+ boxForm.addChild("#", "Insert URI:\u00a0 ");
+ if (iUri != null) {
+ boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, iUri });
+ } else {
+ boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
+ }
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_CREATE, "Create" });
+ }
+
+ private void makeForkBox(HTMLNode parent, String source, String name, String uri) {
+ HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Fork a repository", parent);
+ HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "forkForm");
+ boxForm.addChild("#", "Fork a repository. Leave the Insert URI empty to generate a new one.");
+ boxForm.addChild("br");
+ boxForm.addChild("#", "Freenet URI to fork from:\u00a0 ");
+ if (source != null) {
+ boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH, source });
+ } else {
+ boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_SOURCE, URI_WIDTH});
+ }
+ boxForm.addChild("br");
+ boxForm.addChild("#", "Name (will be part of the Freenet URI):\u00a0 ");
+ if (name != null) {
+ boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_NAME, "30", name });
+ } else {
+ boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_NAME, "30"});
+ }
+ boxForm.addChild("br");
+ boxForm.addChild("#", "Insert URI:\u00a0 ");
+ if (uri != null) {
+ boxForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH, uri });
+ } else {
+ boxForm.addChild("input", new String[] { "type", "name", "size" }, new String[] { "text", PARAM_INSERTURI, URI_WIDTH });
+ }
+ boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
+ }
+
+ private void makeRepositoryBox(HTMLNode parent) {
+ HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Repositories", parent);
+
+ File cacheDir = daemon.getCacheDirFile();
+ File[] dirs = cacheDir.listFiles();
+ if (dirs.length == 0) {
+ box.addChild("#", "No repositories set up.");
+ return;
+ }
+
+ HTMLNode table = box.addChild("table", "width", "100%");
+ HTMLNode tableHead = table.addChild("thead");
+ HTMLNode tableRow = tableHead.addChild("tr");
+ HTMLNode nextTableCell = tableRow.addChild("th", "colspan", "3");
+ nextTableCell.addChild("#", "Name");
+ nextTableCell = tableRow.addChild("th");
+ nextTableCell.addChild("#", "Description");
+
+ for (File dir: dirs) {
+ HTMLNode htmlTableRow = table.addChild("tr");
+ htmlTableRow.addChild(makeNameCell(dir));
+ htmlTableRow.addChild(makeDescriptionCell(dir));
+
+ htmlTableRow = table.addChild("tr");
+ htmlTableRow.addChild(makeDeleteCell(dir));
+ htmlTableRow.addChild(makeEmptyCell());
+ htmlTableRow.addChild(makeForkCell(dir));
+ }
+ }
+
+ private HTMLNode makeEmptyCell() {
+ HTMLNode cell = new HTMLNode("td");
+ cell.addChild("#", "\u00a0");
+ return cell;
+ }
+
+ private HTMLNode makeNameCell(File repos) {
+ HTMLNode cell = new HTMLNode("td", "colspan", "3");
+ String dirName = repos.getName();
+ cell.addChild("b", dirName);
+ return cell;
+ }
+
+ private HTMLNode makeDescriptionCell(File repos) {
+ HTMLNode cell = new HTMLNode("td", "rowspan", "2");
+ HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "descriptionForm");
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
+
+ HTMLNode area = boxForm.addChild("textarea", new String[]{ "name", "cols", "rows" }, new String[] { PARAM_DESCRIPTION, "70", "4" });
+ String desc = getReposDescription(repos);
+ if (desc != null) {
+ area.addChild("#", desc);
+ } else {
+ area.addChild("#", "\u00a0");
+ }
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_SAVEDESCRIPTION, "Save" });
+ return cell;
+ }
+
+ private HTMLNode makeDeleteCell(File repos) {
+ HTMLNode cell = new HTMLNode("td");
+ HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "deleteForm");
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", PARAM_REPOSNAME, repos.getName() });
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_DELETE, "Delete" });
+ return cell;
+ }
+
+ private HTMLNode makeForkCell(File repos) {
+ HTMLNode cell = new HTMLNode("td");
+ HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(cell, path(), "forkForm");
+ boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_FORK, "Fork", "disabled" });
+ return cell;
+ }
+
+ private String getReposDescription(File dir) {
+ File descfile = new File(dir, "description");
+ if (!descfile.exists()) return "<Describe me!>";
+ String desc;
+ try {
+ desc = FileUtil.readUTF(descfile);
+ } catch (IOException e) {
+ Logger.error(this, "Error while reading repository description for: "+dir.getAbsolutePath(), e);
+ return "Error: "+e.getLocalizedMessage();
+ }
+ return desc;
+ }
+
+ private void updateDescription(String repos, String desc) throws IOException {
+ File reposFile = new File(daemon.getCacheDirFile(), repos);
+ updateDescription(reposFile, desc);
+ }
+
+ private void updateDescription(File repos, String desc) throws IOException {
+ File descfile = new File(repos, "description");
+ if (descfile.exists()) {
+ descfile.delete();
+ }
+ InputStream is = new ByteArrayInputStream(desc.getBytes("UTF-8"));
+ FileUtil.writeTo(is, descfile);
+ }
+
+ private void deleteRepository(String reposName) {
+ File repos = new File(daemon.getCacheDirFile(), reposName);
+ FileUtil.removeAll(repos);
+ }
+
+ private String getReposURI(File repos) {
+ return repos.getName();
+ }
+ private String getReposURI(String repos) {
+ return repos;
+ }
+
+ private void tryCreateRepository(String name, String rUri, String iUri, List<String> errors) {
+ String dirName = rUri + '@' + name;
+ File reposDir = new File(daemon.getCacheDirFile(), dirName);
+ Repository repos;
+ try {
+ repos = new Repository(reposDir);
+ repos.create(true);
+ } catch (IOException e) {
+ Logger.error(this, "Error while create repository: "+reposDir.getAbsolutePath(), e);
+ errors.add(e.getLocalizedMessage());
+ return;
+ }
+ String comment = "add a description here\n\n"+
+ "Due lack of a better idea the URIs are noted here:\n"+
+ "Pull URI: U"+rUri.substring(1)+'/'+name+"/0/\n"+
+ "Push URI: (Keep it secret) U"+iUri.substring(1)+'/'+name+"/0/\n";
+
+ try {
+ updateDescription(reposDir, comment);
+ } catch (IOException e) {
+ Logger.error(this, "Error while updating repository description for: "+reposDir.getAbsolutePath(), e);
+ errors.add(e.getLocalizedMessage());
+ }
+ }
+
+ private String sanitizeDocName(String docName, List<String> errors) {
+ int len = docName.length();
+ for (int i=0 ; i<len ; i++) {
+ char c = docName.charAt(i);
+ if (forbiddenChars.contains(c)) {
+ errors.add("The name contains a forbidden character at ("+(i+1)+"): '"+c+"'");
+ }
+ }
+ return docName;
+ }
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index b049757..90d2277 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,88 +1,107 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.UploadPack;
+import freenet.keys.FreenetURI;
+import freenet.keys.InsertableUSK;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private final boolean isReadOnly;
public AnonymousGitService(boolean readOnly) {
isReadOnly = readOnly;
}
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
- System.out.println("x händle request:"+cmd);
+ //System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
- System.out.print("händle:"+command);
- System.out.println(" for:"+reposName);
+ if (reposName.startsWith("/")) {
+ reposName = reposName.substring(1);
+ }
+
+ if (!reposName.endsWith("/")) {
+ reposName = reposName + '/';
+ }
+
+ //System.out.print("händle:"+command);
+ //System.out.println(" for:"+reposName);
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Repository db = getRepository(reposName);
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) return;
Repository db = getRepository(reposName);
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
} else {
System.err.println("Unknown command: "+command);
}
- System.out.println("x händle request: pfertsch");
+ //System.out.println("x händle request: pfertsch");
}
private Repository getRepository(String reposname) throws IOException {
+ FreenetURI uri = new FreenetURI(reposname);
+ if(uri.getExtra()[1] == 1) {
+ InsertableUSK iUsk = InsertableUSK.createInsertable(uri, false);
+ uri = iUsk.getURI();
+ }
+
+ String docName = uri.getDocName();
+ uri = uri.setKeyType("SSK");
+ String reposName = uri.setDocName(null).setMetaString(null).toString(false, false);
Repository db;
- File path = new File("gitcache/test").getCanonicalFile();
+ File path = new File("gitcache", reposName + '@' + docName).getCanonicalFile();
db = new Repository(path);
return db;
}
}
|
saces/SchwachkopfEinsteck
|
87bfeb7b1652af26e29d20ca454bc11a26348eda
|
add getter for cacheDir
|
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
index f1d51d8..275728b 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
@@ -1,47 +1,51 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.File;
import freenet.support.Executor;
import freenet.support.incubation.server.AbstractServer;
import freenet.support.incubation.server.AbstractService;
public class AnonymousGitDaemon extends AbstractServer {
private File reposdir;
private boolean isReadOnly = true;
public AnonymousGitDaemon(String servername, Executor executor) {
super(servername, executor);
}
@Override
protected AbstractService getService() {
return new AnonymousGitService(isReadOnly());
}
public void setCacheDir(String dir) {
if (reposdir != null) {
// move
} else {
File newDir = new File(dir);
if (!newDir.exists()) {
newDir.mkdirs();
}
reposdir = newDir;
}
}
public String getCacheDir() {
return reposdir.getPath();
}
+ public File getCacheDirFile() {
+ return reposdir;
+ }
+
public void setReadOnly(boolean readOnly) {
isReadOnly = readOnly;
}
public boolean isReadOnly() {
return isReadOnly;
}
}
|
saces/SchwachkopfEinsteck
|
72eb393cefd45d4452d9ef2869beb903bd1a684a
|
add a 'read only' option, useful for publishing repositories
|
diff --git a/src/plugins/schwachkopfeinsteck/AdminToadlet.java b/src/plugins/schwachkopfeinsteck/AdminToadlet.java
index d45f00e..76f415d 100644
--- a/src/plugins/schwachkopfeinsteck/AdminToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/AdminToadlet.java
@@ -1,147 +1,160 @@
package plugins.schwachkopfeinsteck;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class AdminToadlet extends WebInterfaceToadlet {
private static final String PARAM_PORT = "port";
private static final String PARAM_BINDTO = "bindto";
private static final String PARAM_ALLOWEDHOSTS = "allowedhosts";
+ private static final String PARAM_CACHEDIR = "chachedir";
+ private static final String PARAM_READONLY = "readonly";
+
private static final String CMD_START = "start";
private static final String CMD_STOP = "stop";
private static final String CMD_RESTART = "restart";
- private static final String PARAM_CACHEDIR = "chachedir";
private static final String CMD_APPLY = "apply";
private final AnonymousGitDaemon daemon;
public AdminToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "admin");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!normalizePath(req.getPath()).equals("/")) {
errors.add("The path '"+uri+"' was not found");
}
makePage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makePage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_STOP)) {
daemon.stop();
} else {
String bindTo = request.getPartAsString(PARAM_BINDTO, 50);
int port = request.getIntPart(PARAM_PORT, 9481);
String allowedHosts = request.getPartAsString(PARAM_ALLOWEDHOSTS, 50);
+ String ro = request.getPartAsString(PARAM_READONLY, 50);
if (request.isPartSet(CMD_START)) {
daemon.setAdress(bindTo, port, allowedHosts, false);
+ daemon.setReadOnly(ro.length() > 0);
daemon.start();
} else if (request.isPartSet(CMD_RESTART)) {
daemon.stop();
try {
//sleep 3 sec, give the old bind a chance to vanishâ¦
Thread.sleep(3000);
} catch (InterruptedException e) {
// ignored
}
daemon.setAdress(bindTo, port, allowedHosts, false);
+ daemon.setReadOnly(ro.length() > 0);
daemon.start();
} else {
errors.add("Unknown command.");
}
}
makePage(ctx, errors);
}
private void makePage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin the git server", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, path(), null, null));
errors.clear();
}
makeCommonBox(contentNode);
makeSimpleBox(contentNode);
makeSSHBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCommonBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Common settings", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "commonForm");
boxForm.addChild("#", "GitPlugin uses a local cache to serve from. Congratulation, you have found the reference point for 'backup'.");
boxForm.addChild("br");
boxForm.addChild("#", "Cache dir: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value", "disabled"}, new String[] { "text", PARAM_CACHEDIR, "50", daemon.getCacheDir(), "disabled" });
boxForm.addChild("br");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_APPLY, "Apply", "disabled" });
}
private void makeSimpleBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Simple git server (git://)", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "simpleServerForm");
boxForm.addChild("#", "This is the anonymous git server. No authentication/encryption/accesscontrol at all. Be carefully.");
boxForm.addChild("br");
boxForm.addChild("#", "Port: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_PORT, "7", "9418" });
boxForm.addChild("br");
boxForm.addChild("#", "Bind to: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_BINDTO, "20", "127.0.0.1" });
boxForm.addChild("br");
boxForm.addChild("#", "Allowed hosts: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_ALLOWEDHOSTS, "20", "127.0.0.1" });
boxForm.addChild("br");
+ if (daemon.isReadOnly()) {
+ boxForm.addChild("input", new String[] { "type", "name", "value", "checked" }, new String[] { "checkbox", PARAM_READONLY, "ok", "checked" });
+ } else {
+ boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "checkbox", PARAM_READONLY, "ok" });
+ }
+ boxForm.addChild("#", "\u00a0Read only access");
+ boxForm.addChild("br");
+ boxForm.addChild("br");
+
if (daemon.isRunning()) {
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_START, "Start", "disabled" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_STOP, "Stop" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_RESTART, "Restart" });
} else {
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_START, "Start"});
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_STOP, "Stop", "disabled" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_RESTART, "Restart", "disabled" });
}
}
private void makeSSHBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "SSH git server (git+ssh://)", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "sshServerForm");
boxForm.addChild("#", "Setting up SSH for an 'Just an idea' implementation is far to much. Sorry folks.");
boxForm.addChild("br");
boxForm.addChild("#", "Basic code for SSH (jSch) is in, just send patches ;)");
}
-
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
index dddb3b1..f1d51d8 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java
@@ -1,38 +1,47 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.File;
import freenet.support.Executor;
import freenet.support.incubation.server.AbstractServer;
import freenet.support.incubation.server.AbstractService;
public class AnonymousGitDaemon extends AbstractServer {
private File reposdir;
+ private boolean isReadOnly = true;
public AnonymousGitDaemon(String servername, Executor executor) {
super(servername, executor);
}
@Override
protected AbstractService getService() {
- return new AnonymousGitService();
+ return new AnonymousGitService(isReadOnly());
}
public void setCacheDir(String dir) {
if (reposdir != null) {
// move
} else {
File newDir = new File(dir);
if (!newDir.exists()) {
newDir.mkdirs();
}
reposdir = newDir;
}
}
public String getCacheDir() {
return reposdir.getPath();
}
+ public void setReadOnly(boolean readOnly) {
+ isReadOnly = readOnly;
+ }
+
+ public boolean isReadOnly() {
+ return isReadOnly;
+ }
+
}
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index bd7d446..b049757 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,84 +1,88 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.UploadPack;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
-
- private boolean isReadOnly = false;
+
+ private final boolean isReadOnly;
+
+ public AnonymousGitService(boolean readOnly) {
+ isReadOnly = readOnly;
+ }
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
System.out.print("händle:"+command);
System.out.println(" for:"+reposName);
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Repository db = getRepository(reposName);
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) return;
Repository db = getRepository(reposName);
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
} else {
System.err.println("Unknown command: "+command);
}
System.out.println("x händle request: pfertsch");
}
private Repository getRepository(String reposname) throws IOException {
Repository db;
File path = new File("gitcache/test").getCanonicalFile();
db = new Repository(path);
return db;
}
}
|
saces/SchwachkopfEinsteck
|
eda098e9cd11aa9975675eeff3cac9b08643c9f2
|
some cleanup (imports, comments, minor refactoring)
|
diff --git a/src/plugins/schwachkopfeinsteck/AdminToadlet.java b/src/plugins/schwachkopfeinsteck/AdminToadlet.java
index 2c4ad81..d45f00e 100644
--- a/src/plugins/schwachkopfeinsteck/AdminToadlet.java
+++ b/src/plugins/schwachkopfeinsteck/AdminToadlet.java
@@ -1,149 +1,147 @@
package plugins.schwachkopfeinsteck;
import java.io.IOException;
-import java.net.InetSocketAddress;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.clients.http.PageNode;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterfaceToadlet;
public class AdminToadlet extends WebInterfaceToadlet {
private static final String PARAM_PORT = "port";
private static final String PARAM_BINDTO = "bindto";
private static final String PARAM_ALLOWEDHOSTS = "allowedhosts";
private static final String CMD_START = "start";
private static final String CMD_STOP = "stop";
private static final String CMD_RESTART = "restart";
private static final String PARAM_CACHEDIR = "chachedir";
private static final String CMD_APPLY = "apply";
private final AnonymousGitDaemon daemon;
public AdminToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) {
super(context, GitPlugin.PLUGIN_URI, "admin");
daemon = simpleDaemon;
}
public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!normalizePath(req.getPath()).equals("/")) {
errors.add("The path '"+uri+"' was not found");
}
makePage(ctx, errors);
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
List<String> errors = new LinkedList<String>();
if (!isFormPassword(request)) {
errors.add("Invalid form password");
makePage(ctx, errors);
return;
}
String path = normalizePath(request.getPath());
if (request.isPartSet(CMD_STOP)) {
daemon.stop();
} else {
String bindTo = request.getPartAsString(PARAM_BINDTO, 50);
int port = request.getIntPart(PARAM_PORT, 9481);
String allowedHosts = request.getPartAsString(PARAM_ALLOWEDHOSTS, 50);
if (request.isPartSet(CMD_START)) {
daemon.setAdress(bindTo, port, allowedHosts, false);
daemon.start();
} else if (request.isPartSet(CMD_RESTART)) {
daemon.stop();
try {
- //sleep 3 sec, give the old bind a chanche to vanishâ¦
+ //sleep 3 sec, give the old bind a chance to vanishâ¦
Thread.sleep(3000);
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ // ignored
}
daemon.setAdress(bindTo, port, allowedHosts, false);
daemon.start();
} else {
errors.add("Unknown command.");
}
}
makePage(ctx, errors);
}
private void makePage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException {
PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin the git server", ctx);
HTMLNode outer = pageNode.outer;
HTMLNode contentNode = pageNode.content;
if (errors.size() > 0) {
contentNode.addChild(createErrorBox(errors, path(), null, null));
errors.clear();
}
makeCommonBox(contentNode);
makeSimpleBox(contentNode);
makeSSHBox(contentNode);
writeHTMLReply(ctx, 200, "OK", outer.generate());
}
private void makeCommonBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Common settings", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "commonForm");
boxForm.addChild("#", "GitPlugin uses a local cache to serve from. Congratulation, you have found the reference point for 'backup'.");
boxForm.addChild("br");
boxForm.addChild("#", "Cache dir: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value", "disabled"}, new String[] { "text", PARAM_CACHEDIR, "50", daemon.getCacheDir(), "disabled" });
boxForm.addChild("br");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_APPLY, "Apply", "disabled" });
}
private void makeSimpleBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Simple git server (git://)", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "simpleServerForm");
boxForm.addChild("#", "This is the anonymous git server. No authentication/encryption/accesscontrol at all. Be carefully.");
boxForm.addChild("br");
boxForm.addChild("#", "Port: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_PORT, "7", "9418" });
boxForm.addChild("br");
boxForm.addChild("#", "Bind to: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_BINDTO, "20", "127.0.0.1" });
boxForm.addChild("br");
boxForm.addChild("#", "Allowed hosts: \u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_ALLOWEDHOSTS, "20", "127.0.0.1" });
boxForm.addChild("br");
if (daemon.isRunning()) {
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_START, "Start", "disabled" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_STOP, "Stop" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_RESTART, "Restart" });
} else {
boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_START, "Start"});
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_STOP, "Stop", "disabled" });
boxForm.addChild("#", "\u00a0 ");
boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_RESTART, "Restart", "disabled" });
}
}
private void makeSSHBox(HTMLNode parent) {
HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "SSH git server (git+ssh://)", parent);
HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "sshServerForm");
boxForm.addChild("#", "Setting up SSH for an 'Just an idea' implementation is far to much. Sorry folks.");
boxForm.addChild("br");
boxForm.addChild("#", "Basic code for SSH (jSch) is in, just send patches ;)");
}
}
|
saces/SchwachkopfEinsteck
|
87212d5b7bcb3026f60d60346aec3f79cd323ff4
|
some cleanup (imports, comments, minor refactoring)
|
diff --git a/src/plugins/schwachkopfeinsteck/GitPlugin.java b/src/plugins/schwachkopfeinsteck/GitPlugin.java
index 85d5703..3d0c476 100644
--- a/src/plugins/schwachkopfeinsteck/GitPlugin.java
+++ b/src/plugins/schwachkopfeinsteck/GitPlugin.java
@@ -1,81 +1,78 @@
package plugins.schwachkopfeinsteck;
-import java.net.InetSocketAddress;
-
import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon;
import freenet.l10n.BaseL10n.LANGUAGE;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginRealVersioned;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Logger;
import freenet.support.plugins.helpers1.PluginContext;
import freenet.support.plugins.helpers1.WebInterface;
public class GitPlugin implements FredPlugin, FredPluginL10n, FredPluginThreadless, FredPluginVersioned, FredPluginRealVersioned {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(GitPlugin.class);
}
public static final String PLUGIN_URI = "/GitPlugin";
private static final String PLUGIN_CATEGORY = "Git Tools";
public static final String PLUGIN_TITLE = "Git Plugin";
private PluginContext pluginContext;
private WebInterface webInterface;
private AnonymousGitDaemon simpleDaemon;
public void runPlugin(PluginRespirator pluginRespirator) {
pluginContext = new PluginContext(pluginRespirator);
+
+ // for now a single server only, later versions can do multiple servers
+ // and each can have its own cache/config
simpleDaemon = new AnonymousGitDaemon("huhu", pluginContext.node.executor);
+ simpleDaemon.setCacheDir("./gitcache");
webInterface = new WebInterface(pluginContext);
webInterface.addNavigationCategory(PLUGIN_URI+"/", PLUGIN_CATEGORY, "Git Toolbox", this);
// Visible pages
BrowseToadlet browseToadlet = new BrowseToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(browseToadlet, PLUGIN_CATEGORY, "Browse", "Browse a git repository like GitWeb");
AdminToadlet adminToadlet = new AdminToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(adminToadlet, PLUGIN_CATEGORY, "Admin", "Admin the git server");
RepositoriesToadlet reposToadlet = new RepositoriesToadlet(pluginContext, simpleDaemon);
webInterface.registerVisible(reposToadlet, PLUGIN_CATEGORY, "Repositories", "Create & Delete server's repositories");
-
- InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 9418);
-
- simpleDaemon.setCacheDir("./gitcache");
- //simpleDaemon.start(addr);
}
public void terminate() {
webInterface.kill();
if (simpleDaemon.isRunning())
simpleDaemon.stop();
simpleDaemon = null;
}
public String getString(String key) {
+ // return the key for now, l10n comes later
return key;
}
public void setLanguage(LANGUAGE newLanguage) {
- // TODO Auto-generated method stub
-
+ // ignored for now, l10n comes later
}
public String getVersion() {
return Version.getLongVersionString();
}
public long getRealVersion() {
return Version.getRealVersion();
}
}
|
saces/SchwachkopfEinsteck
|
77557f47b1a50f2ef0aa678c17f1503cb2beb0e6
|
mention a location where to get a prebuild version from
|
diff --git a/README b/README
index 9787fbb..cca188e 100644
--- a/README
+++ b/README
@@ -1,53 +1,53 @@
SchwachkopfEinsteck
===================
'SchwachkopfEinsteck' is german, it just translates to 'GitPlugin' :)
-Prebuilt version:
- Just load it, it should go intuitiveâ¦
+Prebuilt version: http://github.com/saces/SchwachkopfEinsteck/downloads
+ Just load the latest, it should go intuitiveâ¦
Source Version for the impatient:
Clone/update the repository, cd into it, update submodules and type 'ant'.
Grab the plugin from dist/SchwachkopfEinsteck.jar and load itâ¦
get sources (a fresh clone):
get the super project
git clone git://github.com/saces/SchwachkopfEinsteck.git SchwachkopfEinsteck
cd SchwachkopfEinsteck
init and update submodules
git submodule init
git submodule update
update sources:
update the super project
git pull git://github.com/saces/SchwachkopfEinsteck.git
update submodules
git submodule update
build:
cd into the project root and type 'ant'.
The new created plugin will be dist/SchwachkopfEinsteck.jar
configuration:
After loading the plugin visit http://127.0.0.1:8888/GitPlugin/admin or
'Git Tools'->'Admin' in the menu. Adjust the host and port if needed
(usually this should not be necessary) and press 'Start'.
Using It:
warm up round: (testing the anonymous git transport)
create a bare repository in gitcache/test
cd <freenetdir>
mkdir gitcache
cd gitcache
mkdir test
cd test
git --bare init
the repository name ('test') is hardcoded for testing the anonymous git
transport. so any remote repository ends up in the repository you just
created.
git push git://127.0.0.1:9418/ignoredreposname
git pull git://127.0.0.1:9418/ignoredreposname
happy warm up testing ;)
|
saces/SchwachkopfEinsteck
|
c656e9f99eecc17f5c91a17618bd4589c41ba182
|
fix pathname to fit instructions given in README
|
diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
index 62e218f..bd7d446 100644
--- a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
+++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java
@@ -1,84 +1,84 @@
package plugins.schwachkopfeinsteck.daemon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PacketLineIn;
import org.eclipse.jgit.transport.ReceivePack;
import org.eclipse.jgit.transport.UploadPack;
import freenet.support.Logger;
import freenet.support.incubation.server.AbstractService;
public class AnonymousGitService implements AbstractService {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(AnonymousGitService.class);
}
private boolean isReadOnly = false;
public void handle(Socket sock) throws IOException {
InputStream rawIn = new BufferedInputStream(sock.getInputStream());
OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream());
String cmd = new PacketLineIn(rawIn).readStringRaw();
final int nul = cmd.indexOf('\0');
if (nul >= 0) {
// Newer clients hide a "host" header behind this byte.
// Currently we don't use it for anything, so we ignore
// this portion of the command.
cmd = cmd.substring(0, nul);
}
System.out.println("x händle request:"+cmd);
String req[] = cmd.split(" ");
String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0];
String reposName = req[1];
System.out.print("händle:"+command);
System.out.println(" for:"+reposName);
if ("git-upload-pack".equals(command)) {
// the client want to have missing objects
Repository db = getRepository(reposName);
final UploadPack rp = new UploadPack(db);
//rp.setTimeout(Daemon.this.getTimeout());
rp.upload(rawIn, rawOut, null);
} else if ("git-receive-pack".equals(command)) {
// the client send us new objects
if (isReadOnly) return;
Repository db = getRepository(reposName);
final ReceivePack rp = new ReceivePack(db);
final String name = "anonymous";
final String email = name + "@freenet";
rp.setRefLogIdent(new PersonIdent(name, email));
//rp.setTimeout(Daemon.this.getTimeout());
rp.receive(rawIn, rawOut, null);
} else {
System.err.println("Unknown command: "+command);
}
System.out.println("x händle request: pfertsch");
}
private Repository getRepository(String reposname) throws IOException {
Repository db;
- File path = new File("gitcache/test/.git").getCanonicalFile();
+ File path = new File("gitcache/test").getCanonicalFile();
db = new Repository(path);
return db;
}
}
|
saces/SchwachkopfEinsteck
|
187e2a820d4212a5dd1c56e63be5c6723c5ad991
|
add more instructions
|
diff --git a/README b/README
index f78e62f..9787fbb 100644
--- a/README
+++ b/README
@@ -1,25 +1,53 @@
SchwachkopfEinsteck
===================
'SchwachkopfEinsteck' is german, it just translates to 'GitPlugin' :)
Prebuilt version:
Just load it, it should go intuitiveâ¦
Source Version for the impatient:
Clone/update the repository, cd into it, update submodules and type 'ant'.
Grab the plugin from dist/SchwachkopfEinsteck.jar and load itâ¦
get sources (a fresh clone):
get the super project
git clone git://github.com/saces/SchwachkopfEinsteck.git SchwachkopfEinsteck
cd SchwachkopfEinsteck
init and update submodules
git submodule init
git submodule update
update sources:
update the super project
git pull git://github.com/saces/SchwachkopfEinsteck.git
update submodules
git submodule update
+
+build:
+ cd into the project root and type 'ant'.
+ The new created plugin will be dist/SchwachkopfEinsteck.jar
+
+configuration:
+ After loading the plugin visit http://127.0.0.1:8888/GitPlugin/admin or
+ 'Git Tools'->'Admin' in the menu. Adjust the host and port if needed
+ (usually this should not be necessary) and press 'Start'.
+
+Using It:
+
+ warm up round: (testing the anonymous git transport)
+ create a bare repository in gitcache/test
+ cd <freenetdir>
+ mkdir gitcache
+ cd gitcache
+ mkdir test
+ cd test
+ git --bare init
+
+ the repository name ('test') is hardcoded for testing the anonymous git
+ transport. so any remote repository ends up in the repository you just
+ created.
+ git push git://127.0.0.1:9418/ignoredreposname
+ git pull git://127.0.0.1:9418/ignoredreposname
+
+ happy warm up testing ;)
|
saces/SchwachkopfEinsteck
|
f96a4f395a86e58cc1d9817e69f32d2c843fa53a
|
add instructions for submodules
|
diff --git a/README b/README
index dc20135..f78e62f 100644
--- a/README
+++ b/README
@@ -1,13 +1,25 @@
SchwachkopfEinsteck
===================
'SchwachkopfEinsteck' is german, it just translates to 'GitPlugin' :)
Prebuilt version:
Just load it, it should go intuitiveâ¦
Source Version for the impatient:
Clone/update the repository, cd into it, update submodules and type 'ant'.
Grab the plugin from dist/SchwachkopfEinsteck.jar and load itâ¦
+get sources (a fresh clone):
+ get the super project
+ git clone git://github.com/saces/SchwachkopfEinsteck.git SchwachkopfEinsteck
+ cd SchwachkopfEinsteck
+ init and update submodules
+ git submodule init
+ git submodule update
+update sources:
+ update the super project
+ git pull git://github.com/saces/SchwachkopfEinsteck.git
+ update submodules
+ git submodule update
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.