Skip to content

Commit

Permalink
Merge pull request #4 from fbelzunc/JENKINS-24999
Browse files Browse the repository at this point in the history
[Fixed JENKINS-24999] Build triggered by SCM change without activating trigger in the job configuration
  • Loading branch information
ndeloof committed Jan 5, 2015
2 parents a035a1b + d5e9cb6 commit 3e96df0
Show file tree
Hide file tree
Showing 2 changed files with 159 additions and 7 deletions.
164 changes: 158 additions & 6 deletions src/main/java/com/cloudbees/jenkins/plugins/BitBucketTrigger.java
@@ -1,15 +1,26 @@
package com.cloudbees.jenkins.plugins;

import hudson.Extension;
import hudson.Util;
import hudson.console.AnnotatedLargeText;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.Item;
import hudson.plugins.git.GitStatus;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import jenkins.model.Jenkins;
import org.eclipse.jgit.transport.URIish;
import hudson.util.StreamTaskListener;
import org.apache.commons.jelly.XMLOutput;
import org.kohsuke.stapler.DataBoundConstructor;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
Expand All @@ -20,9 +31,148 @@ public class BitBucketTrigger extends Trigger<AbstractProject> {
public BitBucketTrigger() {
}

public void onPost(AbstractProject<?,?> job, String user) {
BitBucketPushCause cause = new BitBucketPushCause(user);
job.scheduleBuild(cause);
/**
* Called when a POST is made.
*/
public void onPost(String pushBy) {
if(!IsLogFileInitialized())
InitializeLogFile();
run(pushBy);
}

private boolean runPolling() {
try {
StreamTaskListener listener = new StreamTaskListener(getLogFile());
try {
PrintStream logger = listener.getLogger();
long start = System.currentTimeMillis();
logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date()));
boolean result = job.poll(listener).hasChanges();
logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start));
if(result)
logger.println("Changes found");
else
logger.println("No changes");
return result;
} catch (Error e) {
e.printStackTrace(listener.error("Failed to record SCM polling"));
LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e);
throw e;
} catch (RuntimeException e) {
e.printStackTrace(listener.error("Failed to record SCM polling"));
LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e);
throw e;
} finally {
listener.close();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e);
}
return false;
}

public void run(String pushBy) {
if (runPolling()) {
String name = " #"+job.getNextBuildNumber();
BitBucketPushCause cause;
try {
cause = new BitBucketPushCause(getLogFile(), pushBy);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to parse the polling log",e);
cause = new BitBucketPushCause(pushBy);
}
if (job.scheduleBuild(cause)) {
LOGGER.info("SCM changes detected in "+ job.getName()+". Triggering "+name);
} else {
LOGGER.info("SCM changes detected in "+ job.getName()+". Job is already in the queue");
}
}
}

/**
* Returns the file that records the last/current polling activity.
*/
public File getLogFile() {
return new File(job.getRootDir(),"bitbucket-polling.log");
}

/**
* Check if "bitbucket-polling.log" already exists to initialize it
*/
public boolean IsLogFileInitialized() {
File file = new File(job.getRootDir(),"bitbucket-polling.log");
return file.exists();
}

/**
* Need to initialize the log file otherwise plugin will not detect changes in the initial commit
*/
public void InitializeLogFile() {
/*File file = new File(job.getRootDir(),"bitbucket-polling.log");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}*/

try {
StreamTaskListener listener = new StreamTaskListener(getLogFile());
try {
PrintStream logger = listener.getLogger();
long start = System.currentTimeMillis();
logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date()));
//boolean result = job.poll(listener).hasChanges();
logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start));
//if(result)
logger.println("Changes found");
// else
// logger.println("No changes");
} catch (Error e) {
e.printStackTrace(listener.error("Failed to record SCM polling"));
LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e);
throw e;
} catch (RuntimeException e) {
e.printStackTrace(listener.error("Failed to record SCM polling"));
LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e);
throw e;
} finally {
listener.close();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e);
}
}

/**
* Action object for {@link Project}. Used to display the polling log.
*/
public final class BitBucketWebHookPollingAction implements Action {
public AbstractProject<?,?> getOwner() {
return job;
}

public String getIconFileName() {
return "clipboard.png";
}

public String getDisplayName() {
return "BitBucket Hook Log";
}

public String getUrlName() {
return "BitBucketPollLog";
}

public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}

/**
* Writes the annotated log to the given output.
*/
public void writeLogTo(XMLOutput out) throws IOException {
new AnnotatedLargeText<BitBucketWebHookPollingAction>(getLogFile(), Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter());
}
}

@Extension
Expand All @@ -38,4 +188,6 @@ public String getDisplayName() {
return "Build when a change is pushed to BitBucket";
}
}

private static final Logger LOGGER = Logger.getLogger(BitBucketTrigger.class.getName());
}
Expand Up @@ -121,7 +121,7 @@ private void processPayload(JSONObject payload) {
BitBucketTrigger trigger = job.getTrigger(BitBucketTrigger.class);
if (trigger!=null) {
if (match(job.getScm(), remote)) {
trigger.onPost(job, user);
trigger.onPost(user);
} else LOGGER.info("job SCM doesn't match remote repo");
} else LOGGER.info("job hasn't BitBucketTrigger set");
}
Expand Down

0 comments on commit 3e96df0

Please sign in to comment.