Skip to content

Commit

Permalink
New version of GitHub App with single commit and update from repository
Browse files Browse the repository at this point in the history
  • Loading branch information
ldubost committed Dec 22, 2011
1 parent c0eae65 commit 0cf68e1
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 150 deletions.
3 changes: 2 additions & 1 deletion src/main/resources/GitHubCode/GitHubConfigSheet.xml
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ function tsuggest(field) {
#set($status = $cmap.get($page))
## encode the language of the document after the document name, after a dot. Will be processed on commit
<li>$status.status <input type="checkbox" name="page" value="${status.fullname}.$!{status.language}" /> ${page}
<input type="hidden" name="${status.fullname}.$!{status.language}_sha" value="${status.githubsha}" />
#if($status.status!="N")
[[$msg.get("github.configsheet.viewdiff")>>${doc.fullName}?action=compare&page=${status.fullname}&githublanguage=${status.language}&spaces=$!{spaces}&githubsha=${status.githubsha}||target=_blank]]
#end
Expand All @@ -155,7 +156,7 @@ $githubgroovy.exportPages($doc.name, $pagelist)
#elseif($request.update)
#set($pagelist = $xwiki.arrayList)
#foreach($page in $request.getParameterValues("page"))
#set($ok = $pagelist.add($page))
#set($ok = $pagelist.add({ "page" : $page, "sha" : $request.get("${page}_sha")}))
#end
#set($list = $githubgroovy.updatePages($pagelist))

Expand Down
216 changes: 70 additions & 146 deletions src/main/resources/GitHubCode/GitHubGroovy.xml
Original file line number Diff line number Diff line change
Expand Up @@ -210,11 +210,6 @@ public class GitHubGroovy {
return c.trim().replaceAll("[\r]","");
}

public commitFile(pagedoc, message) {
def c = getXML(pagedoc);
return setFileContent(pagedoc.getSpace(), pagedoc.getName(), pagedoc.getLanguage(), c, message)
}

public commitFiles(pagelist, message) {
def newSpaces = new ArrayList();
def newPages = new ArrayList();
Expand Down Expand Up @@ -278,15 +273,10 @@ public class GitHubGroovy {
def ref = dservice.getReference(repository, "refs/heads/master");
def sha = ref.getObject().getSha()
def tree = dservice.getTree(repository, sha, true);
ArrayList<TreeEntry> treeEntries = new ArrayList<TreeEntry>();

try {
for (space in pagesBySpace.keySet()) {
if (newSpaces.contains(space)) {
// need to create the space
// editor.addDir(space, null, -1);
} else {
}

// loop on each page
for (pagedoc in pagesBySpace.get(space)) {
pagename2 = pagedoc.getFullName();
Expand Down Expand Up @@ -316,41 +306,12 @@ public class GitHubGroovy {
blobTreeEntry.setType("blob");
blobTreeEntry.setMode("100644");
blobTreeEntry.setSha(blobSha);

ArrayList<TreeEntry> treeEntries = new ArrayList<TreeEntry>();
treeEntries.add(blobTreeEntry);

Tree currentTree = dservice.getCommit(repository, ref.getObject().getSha()).getTree();
Tree blobTree = dservice.createTree(repository, treeEntries, currentTree.getSha());
debug("Create tree: " + blobTree + " in path " + reppath + filePath);

CommitUser commitUser = new CommitUser();
commitUser.setName("Ludovic Dubost");
commitUser.setEmail("ludovic@xwiki.com");
commitUser.setDate(new Date());

Commit commit = new Commit();
// commit.setAuthor(commitUser);
// commit.setCommitter(commitUser);
commit.setMessage("test commit");
commit.setTree(blobTree);
commit.setParents(Collections.singletonList(new Commit().setSha(ref.getObject().getSha())));

def newCommit = dservice.createCommit(repository, commit);
debug("Created commit: " + newCommit);

TypedResource object = new TypedResource();
object.setType("commit").setSha(newCommit.getSha());
ref.setObject(object);
dservice.editReference(repository, ref, false);

if (newPages.contains(filePath)) {
// adding the page
} else {
def oldData = currentPageData.get(filePath);

// updating page

// updating status to check for changes
committedPages.add(getStatusPath(pagedoc));
def pageStatus = status.get(getStatusPath(pagedoc));
Expand All @@ -367,11 +328,27 @@ public class GitHubGroovy {
debug("error preparing commit on page ${pagename2}: " + e.getMessage());
return null;

} finally {

} finally {
}

// now real commit
Tree currentTree = dservice.getCommit(repository, ref.getObject().getSha()).getTree();
Tree blobTree = dservice.createTree(repository, treeEntries, currentTree.getSha());
debug("Create tree: " + blobTree);

Commit commit = new Commit();
commit.setMessage(message);
commit.setTree(blobTree);
commit.setParents(Collections.singletonList(new Commit().setSha(ref.getObject().getSha())));

def newCommit = dservice.createCommit(repository, commit);
debug("Created commit: " + newCommit);

TypedResource object = new TypedResource();
object.setType("commit").setSha(newCommit.getSha());
ref.setObject(object);
dservice.editReference(repository, ref, false);

// get the commit revision number and store it
// we need to save the status
def rev = ""
Expand All @@ -382,66 +359,6 @@ public class GitHubGroovy {
return commitInfo;
}

public setFileContent(String space, String page, String language, String xml, String message) {
setFileContent(space, page, language, xml, message, null, true);
}

public setFileContent(String space, String page, String language, String xml, String message, boolean createDir) {
// get page
def filePath = space + "/" + page;
if (language!=null&&language!="")
filePath += "." + language;
filePath += ".xml"


def c = getFileContentAsString(space, page, language);
def changed = false;
if (c==null || !c.equals(xml))
changed = true;

if (changed) {
def editor = repository.getCommitEditor(message, null);
def commitInfo = null;

try {
if (c==null) {
// page does not exist we need to add it
debug("Ready to add file ${filePath} with createDir ${createDir}")
addFile(editor, space, filePath, xml.getBytes(), createDir, true, true)
} else {
// content is different we can commit
// page does not exist we need to add it
debug("Ready to update file ${filePath}")
modifyFile(editor, space, filePath, c.getBytes(), xml.getBytes())
}
} catch (Throwable e) {
e.printStackTrace();
debug("error preparing commit: " + e.getMessage());
return null;
} finally {
/*
* This is the final point in all editor handling. Only now all that new
* information previously described with the editor's methods is sent to
* the server for committing. As a result the server sends the new
* commit information.
*/
try {
commitInfo = editor.closeEdit();
} catch (Throwable e) {
e.printStackTrace();
debug("error calling closeEdit: " + e.getMessage());
return null;
}
}
return commitInfo;
} else {
// content is the same. do not commit
debug("content is the same. do not commit");
return null;
}
}


public getChangedPages(String spaces) {
return getChangedPages(spaces, "");
}
Expand Down Expand Up @@ -471,7 +388,9 @@ public class GitHubGroovy {

// debug("Checking page ${page} version ${pagedoc.getVersion()} pageStatus ${pageStatus}")

if (pageStatus.xwikihash=="") {
if (entry==null && !pagedoc.isNew()) {
pageStatus.status = "A";
} else if (pageStatus.xwikihash=="") {
def githubsha = (entry==null) ? "" : entry.githubsha;
if (githubsha=="")
pageStatus.status = "A";
Expand Down Expand Up @@ -539,14 +458,24 @@ public class GitHubGroovy {
}
}

debug("ChangedMap: " + changedMap);

if (spaceList!=null) {
for (entry in githubEntries.keySet()) {
def i1 = entry.indexOf("/");
def i2 = entry.indexOf(".xml");
def spaceName = (i1==-1) ? entry : entry.substring(0, i1);
def pageName = (i2==-1) ? entry : entry.substring(i1+1, i2);
if (spaceList.contains(spaceName)&&!samePages.contains(entry)&&!changedMap.keySet().contains(spaceName + "." + pageName)) {
changedMap.put(spaceName + "." + pageName, [ "status" : "N", "xwikiversion" : "", "githubversion" : githubEntries.get(entry).githubversion ])
for (filePath in githubEntries.keySet()) {
def entry = githubEntries.get(filePath);
def i1 = filePath.indexOf("/");
def i2 = filePath.indexOf(".xml");
def spaceName = (i1==-1) ? filePath : filePath.substring(0, i1);
def page = (i2==-1) ? filePath : filePath.substring(i1+1, i2);
def language = "";
def pageName = page;
if (page.contains(".")) {
def i3 = page.indexOf(".");
language = page.substring(i3+1);
pageName = page.substring(0, i3);
}
if (spaceList.contains(spaceName)&&!samePages.contains(filePath)&&!changedMap.keySet().contains(spaceName + "." + page)) {
changedMap.put(spaceName + "." + pageName, [ "fullname" : "${spaceName}.${pageName}", "language" : language, "status" : "N", "xwikiversion" : "", "githubsha" : entry.githubsha ])
}
}
}
Expand All @@ -559,7 +488,12 @@ public class GitHubGroovy {
def changedMap = new TreeMap();
def githubEntries = getEntries();

for (page in pageList) {
for (pageobj in pageList) {
def page = pageobj.page;
def sha = pageobj.sha;

debug("Ready to update: ${page} ${sha}");

// separate the language particle at the end of the page name from the page fullname. The pagename is of form <docfullname>.<doclanguage>
def languageSeparator = page.lastIndexOf('.');
if (languageSeparator < 0) {
Expand All @@ -573,36 +507,23 @@ public class GitHubGroovy {
pagedoc = pagedoc.getTranslatedDocument(lang);
}
def wikicontent = getXML(pagedoc);
def githubcontent = getFileContentAsString(pagedoc.getSpace(), pagedoc.getName(), pagedoc.getLanguage())
def githubversion = "";
if (!wikicontent.equals(githubcontent)) {
def filePath = getFilePath(pagedoc);
def pageStatus = getPageStatus(getStatusPath(pagedoc));
if (pageStatus==null) {
pageStatus = [ "xwikiversion" : pagedoc.getVersion(), "xwikihash" : "", "githubversion" : "" ];
}
pageStatus.filePath = filePath;
pageStatus.page = pagefullname;
pageStatus.status = "";

// debug("Checking page ${page} version ${pagedoc.getVersion()} pageStatus ${pageStatus}")
def needUpdate = false
def entry = githubEntries.get(filePath);
githubversion = (entry==null) ? "" : entry.githubversion;
def filePath = getFilePath(pagedoc);
def entry = githubEntries.get(filePath);
def githubversion = (entry==null) ? "" : entry.githubversion;
def githubcontent = (entry==null) ? "" : entry.githubcontent;

debug("Ready to update: ${filePath}");

if (!wikicontent.equals(githubcontent) && githubcontent!=null && githubcontent!="") {
def pageStatus = getPageStatus(getStatusPath(pagedoc));
if (pageStatus==null) {
pageStatus = [ "xwikiversion" : pagedoc.getVersion(), "xwikihash" : "", "githubversion" : "" ];
}
pageStatus.filePath = filePath;
pageStatus.page = pagefullname;
pageStatus.status = "";

if (pageStatus.xwikihash=="") {
if (githubversion!="")
needUpdate = true;
} else if (pagedoc.getVersion().equals(pageStatus.xwikiversion)) {
needUpdate = true;
} else {
if (githubversion!="")
needUpdate = true
else if(pageStatus.githubversion!=githubversion)
needUpdate = true;
}

if (needUpdate) {
// updating XWiki document from GitHub
changedMap.put(pagefullname, pageStatus);
def archive = pagedoc.document.getDocumentArchive(context.getContext());
Expand Down Expand Up @@ -663,7 +584,6 @@ public class GitHubGroovy {
pageStatus.xwikihash = "${newwikicontent.hashCode()}";
pageStatus.githubversion = githubversion;
}
}
}
// saveStatus if changed
saveStatus();
Expand Down Expand Up @@ -743,14 +663,18 @@ public class GitHubGroovy {
def sha = dservice.getReference(repository, "refs/heads/master").getObject().getSha()
for (treeEntry in dservice.getTree(repository, sha, true).tree) {
def entryPath = treeEntry.getPath();
debug("Checking path: ${entryPath}");
if (entryPath!=null && entryPath.startsWith(reppath)) {
def filePath = treeEntry.path.substring(reppath.length());
def blob = dservice.getBlob(repository, treeEntry.sha);
def githubcontent = new String(Base64.decodeBase64(blob.content.getBytes())).replaceAll("[\r]","").trim();
def githubhash = (githubcontent==null) ? "" : githubcontent.hashCode();
def githubversion = 0;
entries.put(filePath, [ "githubversion" : githubversion, "githubsha" : treeEntry.sha, "githubhash" : "${githubhash}", "githubcontent" : githubcontent ]);
debug("Adding: ${filePath}");
debug("Got filePath: ${filePath}");
if (filePath.contains("/")) {
def blob = dservice.getBlob(repository, treeEntry.sha);
def githubcontent = new String(Base64.decodeBase64(blob.content.getBytes())).replaceAll("[\r]","").trim();
def githubhash = (githubcontent==null) ? "" : githubcontent.hashCode();
def githubversion = 0;
entries.put(filePath, [ "githubversion" : githubversion, "githubsha" : treeEntry.sha, "githubhash" : "${githubhash}", "githubcontent" : githubcontent ]);
debug("Adding: ${filePath}");
}
}
}
return entries;
Expand Down
67 changes: 67 additions & 0 deletions src/main/resources/GitHubCode/Translations.fr.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<xwikidoc>
<web>GitHubCode</web>
<name>Translations</name>
<language>fr</language>
<defaultLanguage>en</defaultLanguage>
<translation>1</translation>
<parent></parent>
<creator>XWiki.Admin</creator>
<author>XWiki.Admin</author>
<customClass></customClass>
<contentAuthor>XWiki.Admin</contentAuthor>
<creationDate>1262300400000</creationDate>
<date>1262300400000</date>
<contentUpdateDate>1262300400000</contentUpdateDate>
<version>1.1</version>
<title>Application SVN</title>
<template></template>
<defaultTemplate></defaultTemplate>
<validationScript></validationScript>
<comment></comment>
<minorEdit>false</minorEdit>
<syntaxId>xwiki/2.0</syntaxId>
<hidden>false</hidden>
<content>github.title=Application GitHub
github.description=Bienvenue sur l'application GitHub. Vous pouvez configurer votre module GitHub pour connecter votre wiki et commiter votre code XWiki sur GitHub.
github.currentconfigs.title=Configurations GitHub disponibles
github.currentconfigs.noconfigs=Il n'y a pas de configuration GitHub
github.createnewconfig=Créer une nouvelle configuration GitHub
github.createnewimport.error.titlemissing=Un titre est necessaire pour une configuration GitHub
github.configsheet.title=Configuration GitHub
github.configsheet.compare.title=Differences pour
github.configsheet.debug=Debug
github.configsheet.commitmessage=Message du commit
github.configsheet.listpages=Liste des pages à committer
github.configsheet.commitall=Commiter
github.configsheet.updateall=Mettre à jour
github.configsheet.exportall=Exporter
github.configsheet.commit=Commiter
github.configsheet.viewdiff=Voir les différences
github.configsheet.committingpages=En cours de commit des pages suivantes
github.configsheet.committsuccessfull=Commit réalisé avec succès
github.configsheet.backtolist=Retour à la liste des pages
github.configsheet.backtocustom=Retour à la liste custom
github.configsheet.confirmcommittingpage=Veuillez confirmer le commit des pages suivantes
github.configsheet.custom.spacelist=Liste des espaces (separés par des virgules)
github.configsheet.custom.space=Espace
github.configsheet.customlist=Liste custom des pages
github.configsheet.pagesupdated=Les pages suivantes ont été mise-à-jour à partir de GitHub
GitHubCode.GitHubConfigClass_repository_user=Espace GitHub
GitHubCode.GitHubConfigClass_repository_user_tooltip=Espace GitHub ou est le "repository"
GitHubCode.GitHubConfigClass_repository_name=Repository GitHub
GitHubCode.GitHubConfigClass_repository_name_tooltip=Nom du repository du project GitHub
GitHubCode.GitHubConfigClass_repository_path=Sous-repertoires GitHub
GitHubCode.GitHubConfigClass_repository_path_tooltip=chemin relatif du sous-repertoire (src/main/resources/)
GitHubCode.GitHubConfigClass_username=Utilisateur
GitHubCode.GitHubConfigClass_username_tooltip=Utilisateur de connection à GitHub
GitHubCode.GitHubConfigClass_password=Mot de passe
GitHubCode.GitHubConfigClass_password_tooltip=Mot de passe de connection à GitHub
GitHubCode.GitHubConfigClass_defaultspace=Liste des espaces par défaut
GitHubCode.GitHubConfigClass_defaultspace_tooltip=Liste des espaces à verifier
GitHubCode.GitHubConfigClass_savedlist=Liste Sauvegardée
GitHubCode.GitHubConfigClass_savedlist_tooltip=Liste de page sauvegardée listant les pages à commiter
GitHubCode.GitHubConfigClass_defaultdate=Date par défaut
GitHubCode.GitHubConfigClass_defaultdate_tooltip=Date à utiliser pour toutes les pages commités
GitHubCode.GitHubConfigClass_defaultuser=Utilisateur par défaut
GitHubCode.GitHubConfigClass_defaultuser_tooltip=Utilisateur à utiliser pour toutes les pages commités</content></xwikidoc>
Loading

0 comments on commit 0cf68e1

Please sign in to comment.