Delete file based on author name in commit - groovy

My code delete just files which parse to Jenkins name in the file. I would like to delete file based on the author (Jenkins) in the last commit. What is the best solution for that?
def changelogPath = "C:\\test"
def PackID = "test"
def delete(String changelogPath, String PackID) {
String folderPath = "$changelogPath"+ "\\" + "$PackID"
new File(folderPath).eachFile(FileType.FILES) { file ->
if (file.name.contains('Jenkins')) file.delete()
}
delete(changelogPath, PackID)

In order to find all files that have been changed with a certain commit, you need a diff of that commit with its predecessor.
You can let JGit compute a list of DiffEntries like this:
ObjectReader reader = git.getRepository().newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
ObjectId oldTree = git.getRepository().resolve( "HEAD^{tree}" );
oldTreeIter.reset( reader, oldTree );
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
ObjectId newTree = git.getRepository().resolve( "HEAD~1^{tree}" );
newTreeIter.reset( reader, newTree );
DiffFormatter df = new DiffFormatter( new ByteArrayOutputStream() );
df.setRepository( git.getRepository() );
List<DiffEntry> entries = df.scan( oldTreeIter, newTreeIter );
Each DiffEntry has a path that denotes the file which was added, changed, or deleted. The path is relative to the root of the working directory of the repository. Actually, there is an oldPath and newPath, see the JavaDoc which one to use when.
See also here for a general overview of JGit's diff API: http://www.codeaffine.com/2016/06/16/jgit-diff/

Related

Uploading PDF file to Google Drive folder and overwriting existing file

I am developing an app that uploads PDF files to a specific Google Drive folder. The file name includes the current date. The following code is for my DriveServiceHelper.class that is used to create a folder in Google Drive and then upload the PDF files into that folder using its folderID:
public class DriveServiceHelper {
Calendar c = Calendar.getInstance();
Date d = c.getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = df.format(d);
String ps_FolderKey;
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private Drive mDriveService;
public DriveServiceHelper(Drive mDriveService) {
this.mDriveService = mDriveService;
}
public Task<String> createFolder() {
return Tasks.call(mExecutor, () -> {
File folderMetadata = new File();
folderMetadata.setName("Covid Assessment Sheets");
folderMetadata.setMimeType("application/vnd.google-apps.folder");
File myFolder = null;
try {
myFolder = mDriveService.files().create(folderMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + myFolder.getId());
} catch (Exception e) {
e.printStackTrace();
}
if (myFolder == null) {
throw new IOException("Null result when requesting file creation");
}
ps_FolderKey = myFolder.getId();
return ps_FolderKey;
});
}
public Task<String> createFilePDF(String filePath, String folderId) {
return Tasks.call(mExecutor, () -> {
File fileMetaData = new File();
fileMetaData.setName("Covid Assessment # " + currentDate);
fileMetaData.setParents(Collections.singletonList(folderId));
java.io.File file = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/pdf", file);
File myFile = null;
try {
myFile = mDriveService.files().create(fileMetaData, mediaContent).execute();
} catch (Exception e) {
e.printStackTrace();
}
if (myFile == null) {
throw new IOException("Null result when requesting file creation");
}
return myFile.getId();
});
}
}
When uploading the same PDF to a Google Drive folder, I want to overwrite files with the same name, but instead duplicate files are created in the folder as the fileID assigned is different even if file name is the same.
Please help me understand how I should go about this, to automatically overwrite/replace files that already exist with the same name (each file is differentiated by date), and a new PDF file is created if the PDF file does not exist in the folder.
I understand that I might be using the deprecated Drive API, but I was unable to find other solutions online to help me implement what I need. I also came across solutions that include queries to search for existing Google Drive files, but I am not sure I understand how to use it to make it work for me.
Thank you
Google Drive supports multiple files with the same name
Thus, by creating a file with an already existing name, you will not automatically overwrite the old file.
Instead you should do the following:
Use the method Files:list with the query name = 'Covid Assessment Sheets' to find the already existing file(s) with the same name
If desired, you can narrow down the results by also specifying the mimeType and the parent folder (parents)
Retrieve the id of the list result(s)
Use the method Files:delete to delete the existing file
Proceed to create a new file as you are already doing
In Java this would look as following:
FileList result = DriveService.files().list()
.setQ("name = 'Covid Assessment Sheets'");
.setFields("files(id)")
.execute();
List<File> files = result.getFiles();
for (File file : files) {
DriveService.files().delete(file.getId()).execute();
}
An alternative approach would be to update the contents of the already existing file instead of creating a new one.

File search from a folder from FileCabinet in NetStuite returns only five records?

When I am doing the search, the results always contain only five records (in ascending order). I need to get a list of all files in the folder. What am I doing wrong?
FileSearch fileSearch = new FileSearch();
FileSearchBasic fileSearchBasic = new FileSearchBasic();
// Specify the folder in which the search is to be done.
SearchMultiSelectField folderFilter = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true
};
RecordRef[] folder = new RecordRef[1];
folder[0] = new RecordRef
{
// Internal id of the folder where pospay files are stored.
internalId = ns.DataCollection["netSuite:PositivePayFolderInternalId"]
};
folderFilter.searchValue = folder;
fileSearchBasic.folder = folderFilter;
fileSearch.basic = fileSearchBasic;
var result = NSBase.Client.Service.search(fileSearch);
var recordList = result.recordList; // this has ony five results, why?
I found the issue, 'PageSize' was set to 5 in the service client's constructor.

Updating a google spreadsheet table with an excel file

I need to update a table that is shared. The info for this table is first collected into an Excel table files and then uploaded to google drive every day. I found some code that converts the .xls files to a google spreadsheet file, I need to copy the data from this converted file and update the shared one each day. My problem now is that the file I will use for updating the shared spreadsheet will be different eachday, so how can I have the script to get the new file ID eachday. I need these updates to be done automatically each day.
This is the code I have found so far but can't seem to get it to work. First part converts the .xls file to google spreadsheet file that part works but i cant seem to get the function for updating the shared table to work, i cant get the ID of the created file. Would also be nice if a function an be added to the code to to delete the files after they have been converted and the shared table has been updated with them.
function importXLS(){
var files = DriveApp.searchFiles('title contains ".xls"');
var destinationFolderId = "ID of folder with .xls file that is being converted each day";
var existingFileNames = getFilesInFolder(destinationFolderId);
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
try {
if (existingFileNames[name] && (name.indexOf('.xls')>-1)) {
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = { title : name,
key : ID,
'parents':[{"id": destinationFolderId}]
}
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
}
} catch (error) {
console.error("Error with file " + name + ": " + error);
}
}
}
/**
* Get an object of all file names in the specified folder.
* #param {string} folderId
* #returns {Object} files - {filename: true}
*/
function getFilesInFolder(folderId) {
var folder = DriveApp.getFolderById(folderId);
var filesIterator = folder.getFiles();
var files = {};
while (filesIterator.hasNext()) {
var file = filesIterator.next();
files[file.getName()] = true;
}
return files;
}
function CopyContent() {
var ID = importXLS(ID);
var source = SpreadsheetApp.openById(importXLS(ID));//the source needs to be the new file i get eachday
var sheet = source.getSheets()[0];
var destination = SpreadsheetApp.openById("ID of shared table here");
sheet.copyTo(destination);
}
Use Paste Special > Paste values only
The copypastetype to use is PASTE_VALUES
Example from https://developers.google.com/apps-script/reference/spreadsheet/range#copytodestination-copypastetype-transposed
// The code below copies only the values of the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("A:E").copyTo(sheet.getRange("F1"), spreadsheetApp.CopyPasteType.PASTE_VALUES);

Editing exising file in SuiteScript 2.0

I want to load an existing file and append some data, save it back. Tried following in SuiteScript 2.0. But following code still gives me old file content ( only first line when it was created !). Whats wrong?
var fileObj = file.load({
id:'SuiteScripts/MergeVendorResults/'+'MergeResult_'+recordId+'.txt'
});
var oldFileContents = fileObj.getContents();
log.debug("Existing file contents","Old File Contents -> "+oldFileContents);
fileObj.contents = oldFileContents + "\n"+ fileContents;
var id = fileObj.save();
fileObj = file.load({
id: id
});
log.debug("Existing file replaced with contents","File Contents -> "+fileObj.getContents());
You need to create a whole new file object with the concatenated contents and the original file's name and folderId. Then when you save it'll overwrite the original file.

Downloading a depot in perforce

I am a new user of perforce (coming from svn) and am using the gui interface p4v. I want to have a local copy of a folder in someone's depot but am unsure how to do so. I wish to end up with a local copy that is just for me to explore and look around. I do not wish for it be under revision control. Just need it to be as if i downloaded a folder from the internet, free to do whatever with it. How can i accomplish this in p4v?
Once you've synced the files, you can do whatever you want with them. Perforce marks files as read only unless you have them open for edit, so what I would do is sync the depot, copy it to a new location on your HDD, and then mark all the files writable.
Also, if all you want to do is look at the files, you could just sync the depot and open the files. You could even check them out (assuming you have permissions) and just not submit those changes if you wanted to tinker.
This 2 functions will help you start working.
public Repository GetRepository(string i_Workspace, string i_Username, string i_Password, string i_Server)
{
Repository rep;
Server server;
ServerAddress address;
// Create the repository
address = new ServerAddress(i_Server + ":1666");
server = new Server(address);
rep = new Repository(server);
rep.Connection.UserName = i_Username;
Perforce.P4.Options options = new Perforce.P4.Options();
options["Password"] = i_Password;
Environment.SetEnvironmentVariable("P4PASSWD", i_Password);
rep.Connection.Client = new Client();
if (i_Workspace != null && i_Workspace != string.Empty)
{
rep.Connection.Client.Name = i_Workspace;
}
rep.Connection.Connect(options);
rep.Connection.CommandTimeout = System.TimeSpan.Zero;
rep.Connection.Login(i_Password);
return rep;
}
private Client createWorkspace(string i_DepotPath, string i_RootDirectory)
{
string workspaceName = "workspace" + new Random().Next().ToString();
Repository rep = GetRepository(string.Empty);
Client client = new Client();
client.Name = workspaceName;
client.Root = i_RootDirectory;
client.OwnerName = k_DefaultUser;
client.ViewMap = new ViewMap();
client.Options = ClientOption.AllWrite;
client.LineEnd = LineEnd.Local;
client.SubmitOptions = new ClientSubmitOptions(false, SubmitType.SubmitUnchanged);
string depotPath = i_DepotPath + "/...";
String clientPath;
//clientPath = String.Format("//{0}/{1}/...", client.Name, i_DepotPath.Replace("//depot/", string.Empty));
clientPath = "//" + client.Name + "/...";
MapEntry entry = new MapEntry(MapType.Include, new DepotPath(depotPath), new ClientPath(clientPath));
client.ViewMap.Add(entry);
rep.CreateClient(client);
return client;
}

Resources