Howto: fork a Subversion project with Git
This is a short excerpt on how you can use Git to fork a Subversion project.
I assume that:
- you want to maintain your own fork of a project, and intend to follow its evolutions
- you have no commit-access to the upstream Subversion server, or you do not intend to push you changes back.
We will take XStream as a running example.
Import the Subversion project into Git
git svn clone --stdlayout --prefix=svn/ http://svn.codehaus.org/xstream/ xstream-fork
This creates a complete clone of the XStream Subversion repository. Tags and branches will be imported as well (--stdlayout).
Git has local and remote branches. The local ones are those you make modifications too. They generally merge from remote branches, which you can think of as read-only copies of upstream branches.
Git-SVN turns Subversion branches as Git remote branches. The --prefix=svn/ makes it easier to differentiate them from regular Git branches.
What you get
You can check what was imported:
git branch -a * master remotes/svn/pull-parser-merge remotes/svn/tags/XSTREAM_0_2 remotes/svn/tags/XSTREAM_0_3 remotes/svn/tags/XSTREAM_0_4 remotes/svn/tags/XSTREAM_0_5 remotes/svn/tags/XSTREAM_0_6 remotes/svn/tags/XSTREAM_0_6_RC1 remotes/svn/tags/XSTREAM_1_0_1 remotes/svn/tags/XSTREAM_1_0_2 remotes/svn/tags/XSTREAM_1_0_RC1 remotes/svn/tags/XSTREAM_1_1 remotes/svn/tags/XSTREAM_1_1_1 remotes/svn/tags/XSTREAM_1_1_2 remotes/svn/tags/XSTREAM_1_1_3 remotes/svn/tags/XSTREAM_1_2 remotes/svn/tags/XSTREAM_1_2_1 remotes/svn/tags/XSTREAM_1_2_2 remotes/svn/tags/XSTREAM_1_3 remotes/svn/tags/XSTREAM_1_3_1 remotes/svn/trunk remotes/svn/xmlencoder-spike
By default, your master branch tracks svn/trunk. You can easily make a local branch based on something else, such as the xmlencoder-spike branch:
git checkout -b xmlencoder-spike xmlencoder-spike
Another thing is that tags in Subversion are just folders, so Git-SVN imported them as branches. You may transform those into real Git tags:
git tag -m 'Tag for v0.2' -a v0.2 svn/tags/XSTREAM_0_2
Work!
The best practice in Git is to work with feature branches, so each time you need to work on something, you should really spin a branch!
Choose which local branch to fork, such as:
git checkout -b my-cool-feature master
Make your commits along the way, and when your work is ready to be merged:
git checkout master git merge my-cool-feature # Optional, if you don't need the feature branch anynore git branch -d my-cool-feature
For quick one-offs, you may not need feature branches though.
Synchronize!
To update all Git-SVN remote branches:
git svn fetch
To merge onto local branches that track Git-SVN remote branches:
git svn fetch git checkout master git merge svn/trunk git checkout 3.1 git merge svn/branch-3.1
You may also directly fetch and apply the changes if your branch was created from a Git-SVN branch:
git svn rebase
Make a real Git clone repository available
You can't push Subversion remote branches to another repository, so if you need to make your Git fork public somewhere (such as on GitHub), you will need to:
- create tags as mentioned above
- create a local branch for each Subversion branch that you want to republish such as stable branches
- push those tags and local branches to your public repository.
Sending an email on iPhone OS
I have been coding on the iPhone OS recently (for a research prototype). The application is basically capturing some data from the GPS and the accelerometers.
The data is stored in a sqlite database that is accessed through Core Data. From time to time, the user can send the data by email. Doing that is extremely easy with the iPhone OS.
I first added a method for creating a CSV representation of the data:
- (NSMutableString*) csvData { NSError *error = nil; if (![[self fetchedResultsController] performFetch:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } NSMutableString* str = [[NSMutableString alloc] initWithString:@"timestamp,altitude,latitude,longitude,xAcceleration,yAcceleration,zAcceleration\n"]; for (NSManagedObject* entry in self.fetchedResultsController.fetchedObjects) { [str appendFormat:@"%@,%@,%@,%@,%@,%@,%@\n", [entry valueForKey:@"timestamp"], [entry valueForKey:@"altitude"], [entry valueForKey:@"latitude"], [entry valueForKey:@"longitude"], [entry valueForKey:@"xAcceleration"], [entry valueForKey:@"yAcceleration"], [entry valueForKey:@"zAcceleration"]]; } [str autorelease]; return str; }
The data is represented as NSMutableString, from which can later extract a NSData representation from. The actual code is just a walk over the data rows that Core Data manages.
The controller method that sends the email is very simple as it uses the ready-to-go MFMailComposeViewController controller.
- (void)sendMail { if (! [MFMailComposeViewController canSendMail]) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Unsupported operation" message:@"This device is not configured to send emails." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alertView show]; [alertView release]; return; } MFMailComposeViewController* mailController = [[MFMailComposeViewController alloc] init]; [mailController setSubject:@"Entropia Data"]; [mailController setMessageBody:@"This data was captured by Entropia.app" isHTML:NO]; [mailController addAttachmentData:[[self csvData] dataUsingEncoding:NSUTF8StringEncoding] mimeType:@"application/csv" fileName:@"data.csv"]; mailController.mailComposeDelegate = self; [self.navigationController presentModalViewController:mailController animated:YES]; }
The mail composition controller gets some pre-defined data: the subject, a message body and a first attachment which is the CSV data we computed earlier.
When the user either taps for sending the email or canceling it, the mail controller delegate is called. It can perform some checks and cleanups to see if the mail was sent or not, but at the very least you must discard the mail controller and release it. Otherwise, your application will stay blocked on that screen!
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error { [self.navigationController dismissModalViewControllerAnimated:YES]; if (result == MFMailComposeResultFailed) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription] message:[error localizedFailureReason] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alertView show]; [alertView release]; } [controller release]; }
As you can see, the iPhone OS provides a very sound and easy framework
How I use DropBox
On popular request, here is how I use DropBox. In case you had never heard about it, DropBox gives you a "web folder" (a-la Mobile.me) which is synchronized between your different machines. DropBox works on Mac OS X, Windows and Linux. You can use it to share files with friends too (which is useful for sharing... well... Linux distros and Stallman-compliant software).
You can get a 2 GB free account which is way sufficient for most usages, but switching to a paid account is certainly a good idea if you can afford to. I should also mention that the service is rock-solid, and the software clients work seamlessly in the background.
There are a bunch of files that I need to share between my laptops at home and at work, and DropBox is just way better than a USB key or a geeky rsync-based solution (or worse, a Subversion-based one). The only thing is that I never store sensitive informations in my DropBox folder, as this data is to be hosted in the clound, and you never know what may happen to it.
Whenever we need to exchange stuff with friends, we simply drop something into our shared archive. It can't really be any simpler. Another nicety about DropBox is that it stores revisions of your files, so that you can always revert a deletion or switch back to a previous version. It is not as powerful as a true version control system, but it does a fine job as long as you spot where the option is (only in the web interface).
But the true geeky usage that I have is when combined with Git (or any other DVCS of your choice). The power of DVCS lies in the fact that they store the whole history locally and as such, they do not require a server. You can thus store your Git branches in a DropBox folder, or put a symlink in it. This way you get the benefits of both DropBox and Git (or Hg, Bzr, ...): powerful VCS, automatic remote backups and synchronization between workstations.
How about yourself? How do you use DropBox?
Guice it up (or AOP can be made simple sometimes)
I have been knowing about the Google Guice dependency injection container features for quite some time. Guice is a really pleasant DI framework that does its job with brilliant simplicity from a developer point of view (oh yes, and you don't have to describe the classes wiring in a dumb XML file like Spring does).
Guice has more than DI capabilities though, as long as you spice it up with extensions libraries. Today I'll show you the AOP capabilities that Guice offers.
I must admit that I have always been puzzled by this thing called aspect-oriented programming. While the idea of separating actual code from cross-cutting concerns (e.g., security, transactions) makes a lot of sense, one may easily end-up writing spaghetti code.
If you don't believe me, have a look at Spring ROO, I am really curious to know if one can come up with serious arguments for not calling that mess of Java, AspectJ and Spring XML oddities "spaghetti code".
Anyway, AOP flourished rapidly a few years back, as advanced developers, methodologists and event academics all went crazy about it through books, frameworks and claims of the death of OOP. The good news is that for a change, the AOP hype faded away in a flashlight (I whish the same could have been true for those silly things called SOAP and BPEL). However, AOP is still very useful in non-dynamic languages like Java, and reasonable use can make code quite elegant.
Let's get back to Guice, as I will quickly go through some code snippets. I wanted to play with Guice through the trivial use-case of a declaratively access-restricted contacts manager. The code that you will see exhibits AOP and DI features in Guice. As far as the quality is concerned, it will show you the approach, but in an industrial case one would of course need something a bit more elaborated.
First of all, I created a wonderful Person model class:
package app; public class Person { private final String name; private final String email; public Person(String name, String email) { this.name = name; this.email = email; } public String getName() { return name; } public String getEmail() { return email; } @Override public String toString() { return new StringBuffer(name) .append(" <") .append(email) .append(">") .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (!email.equals(person.email)) return false; if (!name.equals(person.name)) return false; return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + email.hashCode(); return result; } }
Disgression: it would have been much more concise in Scala or Groovy.
I then designed a ContactManager interface:
package app; public interface ContactManager { public ContactManager add(Person person); public ContactManager remove(Person person); public Person lookup(String name); }
Note that I made it minimalistically fluent so that add and remove calls could be chained.
I then wanted to design a basic access control mechanism, so that an implementation of ContactManager could declaratively restrict its access to a certain type of user profile, much like what we can do with EJB 3.x (incidentally, good implementations like Glassfish use AOP and bytecode engineering under the hood).
Hence, I designed annotations to let classes and methods specify access-control policies:
package app.auth; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface WithUserProfileVerification { }
and
package app.auth; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RequiresProfile { UserProfile value(); }
along with a user profile enumeration (anonymous user, regular user and administrator):
package app.auth; public enum UserProfile { ANONYMOUS, USER, ADMIN }
Now we are able to define a basic ContactManager implementation with declarative access-control policies:
package demo; import app.ContactManager; import app.Person; import app.auth.RequiresProfile; import static app.auth.UserProfile.ADMIN; import static app.auth.UserProfile.USER; import app.auth.WithUserProfileVerification; import java.util.HashSet; import java.util.Set; @WithUserProfileVerification public class ContactManagerImpl implements ContactManager { private final Set<Person> contacts = new HashSet<Person>(); @RequiresProfile(ADMIN) public ContactManager add(Person person) { contacts.add(person); return this; } @RequiresProfile(ADMIN) public ContactManager remove(Person person) { contacts.remove(person); return this; } @RequiresProfile(USER) public Person lookup(String name) { for (Person person : contacts) { if (person.getName().equals(name)) { return person; } } return null; } }
From this definition, anonymous users cannot do anything, regular users can perform lookups and administrators can add/remove contacts.
This can be summarized by this class diagram:

The next question is of course: how do you make that actually work?
First, let's design a profile checker interface along with a dumb implementation:
package app.auth; public interface UserProfileChecker { public UserProfile getCurrentUserProfile(); public UserProfile login(String login, String password); public UserProfile logout(); }
package demo; import app.auth.UserProfile; import static app.auth.UserProfile.*; import app.auth.UserProfileChecker; public class DumbUserProfileChecker implements UserProfileChecker { private UserProfile userProfile = ANONYMOUS; public UserProfile getCurrentUserProfile() { return userProfile; } public UserProfile login(String login, String password) { if (login.equals("Julien") && password.equals("secret")) { userProfile = ADMIN; } else if (login.equals("Jean-Jacques") && password.equals("1234")) { userProfile = USER; } else { userProfile = ANONYMOUS; } return getCurrentUserProfile(); } public UserProfile logout() { userProfile = ANONYMOUS; return userProfile; } }

Sounds great isn't it?
Still, the link is missing between our contact manager implementation, and this user profile checker.
The idea is to design an aspect for that: each class that uses our declarative access-control policies will have method calls beeing intercepted by the aspect. Here is the code:
package demo; import app.auth.RequiresProfile; import app.auth.UserProfile; import static app.auth.UserProfile.ADMIN; import static app.auth.UserProfile.USER; import app.auth.UserProfileChecker; import com.google.inject.Inject; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class UserProfileInterceptor implements MethodInterceptor { @Inject private UserProfileChecker profileChecker; public Object invoke(MethodInvocation methodInvocation) throws Throwable { UserProfile required = methodInvocation.getMethod().getAnnotation(RequiresProfile.class).value(); UserProfile current = profileChecker.getCurrentUserProfile(); if (insufficientProfile(required, current)) { throw new RuntimeException("The current user profile (" + current + ") is not sufficient: " + required); } else { return methodInvocation.proceed(); } } private boolean insufficientProfile(UserProfile required, UserProfile current) { return (required == ADMIN && current != ADMIN) || (required == USER && (current != USER && current != ADMIN)); } }
The user profile checker will be injected by Guice in the aspect (see the @Inject annotation). The interesting work is performed by the invoke method that looks at the required user profile (through the invoked method annotation) and checks it against the user profile checker. When the profile matches, the method actually gets invoked, otherwise a RuntimeException is raised.
From there what is missing is simply the Guice wiring definitions. Before we look at that, I also designed an aspect for logging method calls (hence, we will inject two aspects):
package demo; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import java.util.logging.Level; import java.util.logging.Logger; public class LoggingInterceptor implements MethodInterceptor { private Logger logger = Logger.getLogger(LoggingInterceptor.class.getName()); public Object invoke(MethodInvocation methodInvocation) throws Throwable { logger.logp( Level.INFO, methodInvocation.getClass().getName(), methodInvocation.getMethod().getName(), "invocation", methodInvocation.getArguments()); Object result = null; try { result = methodInvocation.proceed(); } finally { logger.logp( Level.INFO, methodInvocation.getClass().getName(), methodInvocation.getMethod().getName(), "return", result); return result; } } }

Finally, here is the Main class that has the Guice wiring configuration and a simple use-case:
package demo; import app.ContactManager; import app.Person; import app.auth.RequiresProfile; import app.auth.UserProfileChecker; import app.auth.WithUserProfileVerification; import com.google.inject.*; import static com.google.inject.matcher.Matchers.*; public class Main { public static void main(String[] args) { new Main().execute(); } private Module guiceModule = new AbstractModule() { @Override protected void configure() { bind(ContactManager.class) .to(ContactManagerImpl.class) .in(Singleton.class); bind(UserProfileChecker.class) .to(DumbUserProfileChecker.class) .in(Singleton.class); UserProfileInterceptor userProfileInterceptor = new UserProfileInterceptor(); requestInjection(userProfileInterceptor); bindInterceptor( annotatedWith(WithUserProfileVerification.class), annotatedWith(RequiresProfile.class), userProfileInterceptor); bindInterceptor( subclassesOf(ContactManager.class), any(), new LoggingInterceptor()); } }; private Injector injector = Guice.createInjector(guiceModule); private void execute() { ContactManager contacts = injector.getInstance(ContactManager.class); UserProfileChecker profileChecker = injector.getInstance(UserProfileChecker.class); profileChecker.login("Julien", "secret"); contacts.add(new Person("Julien Ponge", "julien.ponge@gmail.com")); contacts.add(new Person("Jean-Jacques", "jean.jacques@gmail.com")); profileChecker.logout(); profileChecker.login("Jean-Jacques", "1234"); System.out.println(contacts.lookup("Julien Ponge")); } }

You can easily modify the execute method call to check that access-control is enforced (e.g., have an anonymous user attempt to add an entry and see that an exception is raised).
The wiring defined in the module configuration is straightforward. One should only pay attention to the requestInjection(userProfileInterceptor) call. Indeed, aspects are not managed by the DI container. As we request an injection in the corresponding class, this call will make it on-demand.
As we saw in this small showcase, Google Guice is a very compelling DI framework with simple and efficient AOP capabilities.
Don't you think so?




