public virtual void FailingPathsShouldNotResultInOKReturnValue() { FilePath folder1 = new FilePath(db.WorkTree, "folder1"); FileUtils.Mkdir(folder1); FilePath file = new FilePath(folder1, "file1.txt"); Write(file, "folder1--file1.txt"); file = new FilePath(folder1, "file2.txt"); Write(file, "folder1--file2.txt"); Git git = new Git(db); git.Add().AddFilepattern(folder1.GetName()).Call(); RevCommit @base = git.Commit().SetMessage("adding folder").Call(); RecursiveDelete(folder1); git.Rm().AddFilepattern("folder1/file1.txt").AddFilepattern("folder1/file2.txt"). Call(); RevCommit other = git.Commit().SetMessage("removing folders on 'other'").Call(); git.Checkout().SetName(@base.Name).Call(); file = new FilePath(db.WorkTree, "unrelated.txt"); Write(file, "unrelated"); git.Add().AddFilepattern("unrelated").Call(); RevCommit head = git.Commit().SetMessage("Adding another file").Call(); // Untracked file to cause failing path for delete() of folder1 file = new FilePath(folder1, "file3.txt"); Write(file, "folder1--file3.txt"); ResolveMerger merger = new ResolveMerger(db, false); merger.SetCommitNames(new string[] { "BASE", "HEAD", "other" }); merger.SetWorkingTreeIterator(new FileTreeIterator(db)); bool ok = merger.Merge(head.Id, other.Id); NUnit.Framework.Assert.IsFalse(merger.GetFailingPaths().IsEmpty()); NUnit.Framework.Assert.IsFalse(ok); }
/// <summary>Create a new lock for a pack file.</summary> /// <remarks>Create a new lock for a pack file.</remarks> /// <param name="packFile">location of the <code>pack-*.pack</code> file.</param> /// <param name="fs">the filesystem abstraction used by the repository.</param> public PackLock(FilePath packFile, FS fs) { FilePath p = packFile.GetParentFile(); string n = packFile.GetName(); keepFile = new FilePath(p, Sharpen.Runtime.Substring(n, 0, n.Length - 5) + ".keep" ); this.fs = fs; }
/// <since>4.1</since> public FileBody(FilePath file, string filename, string mimeType, string charset) : base(mimeType) { if (file == null) { throw new ArgumentException("File may not be null"); } this.file = file; if (filename != null) { this.filename = filename; } else { this.filename = file.GetName(); } this.charset = charset; }
public override bool Accept(FilePath f) { if (f.IsDirectory()) { return true; } string name = f.GetName(); int i = name.LastIndexOf('.'); if (i > 0 && i < name.Length - 1) { string ext = Sharpen.Runtime.Substring(name, i + 1).ToLower(); if (ext.Equals("js")) { return true; } } return false; }
/// <summary>Add a single existing pack to the list of available pack files.</summary> /// <remarks>Add a single existing pack to the list of available pack files.</remarks> /// <param name="pack">path of the pack file to open.</param> /// <param name="idx">path of the corresponding index file.</param> /// <returns>the pack that was opened and added to the database.</returns> /// <exception cref="System.IO.IOException"> /// index file could not be opened, read, or is not recognized as /// a Git pack file index. /// </exception> internal override PackFile OpenPack(FilePath pack, FilePath idx) { string p = pack.GetName(); string i = idx.GetName(); if (p.Length != 50 || !p.StartsWith("pack-") || !p.EndsWith(".pack")) { throw new IOException(MessageFormat.Format(JGitText.Get().notAValidPack, pack)); } if (i.Length != 49 || !i.StartsWith("pack-") || !i.EndsWith(".idx")) { throw new IOException(MessageFormat.Format(JGitText.Get().notAValidPack, idx)); } if (!Sharpen.Runtime.Substring(p, 0, 45).Equals(Sharpen.Runtime.Substring(i, 0, 45 ))) { throw new IOException(MessageFormat.Format(JGitText.Get().packDoesNotMatchIndex, pack)); } PackFile res = new PackFile(idx, pack); InsertPack(res); return res; }
/// <summary> /// Updates the file in the working tree with content and mode from an entry /// in the index. /// </summary> /// <remarks> /// Updates the file in the working tree with content and mode from an entry /// in the index. The new content is first written to a new temporary file in /// the same directory as the real file. Then that new file is renamed to the /// final filename. /// <p> /// TODO: this method works directly on File IO, we may need another /// abstraction (like WorkingTreeIterator). This way we could tell e.g. /// Eclipse that Files in the workspace got changed /// </p> /// </remarks> /// <param name="repo"></param> /// <param name="f"> /// the file to be modified. The parent directory for this file /// has to exist already /// </param> /// <param name="entry">the entry containing new mode and content</param> /// <param name="or">object reader to use for checkout</param> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> public static void CheckoutEntry(Repository repo, FilePath f, DirCacheEntry entry , ObjectReader or) { ObjectLoader ol = or.Open(entry.GetObjectId()); FilePath parentDir = f.GetParentFile(); FilePath tmpFile = FilePath.CreateTempFile("._" + f.GetName(), null, parentDir); WorkingTreeOptions opt = repo.GetConfig().Get(WorkingTreeOptions.KEY); FileOutputStream rawChannel = new FileOutputStream(tmpFile); OutputStream channel; if (opt.GetAutoCRLF() == CoreConfig.AutoCRLF.TRUE) { channel = new AutoCRLFOutputStream(rawChannel); } else { channel = rawChannel; } try { ol.CopyTo(channel); } finally { channel.Close(); } FS fs = repo.FileSystem; if (opt.IsFileMode() && fs.SupportsExecute()) { if (FileMode.EXECUTABLE_FILE.Equals(entry.RawMode)) { if (!fs.CanExecute(tmpFile)) { fs.SetExecute(tmpFile, true); } } else { if (fs.CanExecute(tmpFile)) { fs.SetExecute(tmpFile, false); } } } if (!tmpFile.RenameTo(f)) { // tried to rename which failed. Let' delete the target file and try // again FileUtils.Delete(f); if (!tmpFile.RenameTo(f)) { throw new IOException(MessageFormat.Format(JGitText.Get().couldNotWriteFile, tmpFile .GetPath(), f.GetPath())); } } entry.LastModified = f.LastModified(); if (opt.GetAutoCRLF() != CoreConfig.AutoCRLF.FALSE) { entry.SetLength(f.Length()); } else { // AutoCRLF wants on-disk-size entry.SetLength((int)ol.GetSize()); } }
/// <summary>Create a new lock for any file.</summary> /// <remarks>Create a new lock for any file.</remarks> /// <param name="f">the file that will be locked.</param> /// <param name="fs"> /// the file system abstraction which will be necessary to perform /// certain file system operations. /// </param> public LockFile(FilePath f, FS fs) { @ref = f; lck = new FilePath(@ref.GetParentFile(), @ref.GetName() + SUFFIX); this.fs = fs; }
public bool Accept(FilePath f) { return f.GetName().EndsWith(JsTestsTest.jstestsExtension); }
public virtual void TestMergeRemovingFoldersWithoutFastForward() { FilePath folder1 = new FilePath(db.WorkTree, "folder1"); FilePath folder2 = new FilePath(db.WorkTree, "folder2"); FileUtils.Mkdir(folder1); FileUtils.Mkdir(folder2); FilePath file = new FilePath(folder1, "file1.txt"); Write(file, "folder1--file1.txt"); file = new FilePath(folder1, "file2.txt"); Write(file, "folder1--file2.txt"); file = new FilePath(folder2, "file1.txt"); Write(file, "folder--file1.txt"); file = new FilePath(folder2, "file2.txt"); Write(file, "folder2--file2.txt"); Git git = new Git(db); git.Add().AddFilepattern(folder1.GetName()).AddFilepattern(folder2.GetName()).Call (); RevCommit @base = git.Commit().SetMessage("adding folders").Call(); RecursiveDelete(folder1); RecursiveDelete(folder2); git.Rm().AddFilepattern("folder1/file1.txt").AddFilepattern("folder1/file2.txt"). AddFilepattern("folder2/file1.txt").AddFilepattern("folder2/file2.txt").Call(); RevCommit other = git.Commit().SetMessage("removing folders on 'branch'").Call(); git.Checkout().SetName(@base.Name).Call(); file = new FilePath(folder2, "file3.txt"); Write(file, "folder2--file3.txt"); git.Add().AddFilepattern(folder2.GetName()).Call(); git.Commit().SetMessage("adding another file").Call(); MergeCommandResult result = git.Merge().Include(other.Id).SetStrategy(MergeStrategy .RESOLVE).Call(); NUnit.Framework.Assert.AreEqual(MergeStatus.MERGED, result.GetMergeStatus()); NUnit.Framework.Assert.IsFalse(folder1.Exists()); }
/// <exception cref="System.IO.IOException"></exception> public override void VisitEntry(TreeEntry m, GitIndex.Entry i, FilePath f) { // TODO remove this once we support submodules if (f.GetName().Equals(".gitmodules")) { throw new NotSupportedException(JGitText.Get().submodulesNotSupported); } if (m == null) { this._enclosing.index.Remove(this._enclosing.root, f); return; } bool needsCheckout = false; if (i == null) { needsCheckout = true; } else { if (i.GetObjectId().Equals(m.GetId())) { if (i.IsModified(this._enclosing.root, true)) { needsCheckout = true; } } else { needsCheckout = true; } } if (needsCheckout) { GitIndex.Entry newEntry = this._enclosing.index.AddEntry(m); this._enclosing.index.CheckoutEntry(this._enclosing.root, newEntry); } }
private static string BaseName(FilePath tmpPack) { string name = tmpPack.GetName(); return Sharpen.Runtime.Substring(name, 0, name.LastIndexOf('.')); }
/// <summary>Create a new pack indexer utility.</summary> /// <remarks>Create a new pack indexer utility.</remarks> /// <param name="db"></param> /// <param name="src"> /// stream to read the pack data from. If the stream is buffered /// use /// <see cref="BUFFER_SIZE">BUFFER_SIZE</see> /// as the buffer size for the stream. /// </param> /// <param name="dstBase"></param> /// <exception cref="System.IO.IOException">the output packfile could not be created. /// </exception> public IndexPack(Repository db, InputStream src, FilePath dstBase) { repo = db; objectDatabase = db.ObjectDatabase.NewCachedDatabase(); @in = src; inflater = new IndexPack.InflaterStream(this); readCurs = objectDatabase.NewReader(); buf = new byte[BUFFER_SIZE]; readBuffer = new byte[BUFFER_SIZE]; objectDigest = Constants.NewMessageDigest(); tempObjectId = new MutableObjectId(); packDigest = Constants.NewMessageDigest(); if (dstBase != null) { FilePath dir = dstBase.GetParentFile(); string nam = dstBase.GetName(); dstPack = new FilePath(dir, nam + ".pack"); dstIdx = new FilePath(dir, nam + ".idx"); packOut = new RandomAccessFile(dstPack, "rw"); packOut.SetLength(0); } else { dstPack = null; dstIdx = null; } }
// move "@Parameters" to this method to test a single doctest /// <exception cref="System.IO.IOException"></exception> public static ICollection<object[]> SingleDoctest() { IList<object[]> result = new List<object[]>(); FilePath f = new FilePath(baseDirectory, "Counter.doctest"); string contents = LoadFile(f); result.Add(new object[] { f.GetName(), contents, -1 }); return result; }
public bool Accept(FilePath f) { return f.GetName().EndsWith(Rhino.Tests.DoctestsTest.doctestsExtension); }
/// <exception cref="System.IO.IOException"></exception> private static byte[] GetBytesFromFile(FilePath file) { InputStream @is = new FileInputStream(file); // Get the size of the file long length = file.Length(); // Create the byte array to hold the data byte[] bytes = new byte[(int)length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.Length && (numRead = @is.Read(bytes, offset, bytes.Length - offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.Length) { throw new IOException("Could not completely read file " + file.GetName()); } // Close the input stream and return bytes @is.Close(); return bytes; }
public bool Accept(FilePath pathname) { return pathname.IsDirectory() && !pathname.GetName().Equals("CVS"); }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="NGit.Api.Errors.JGitInternalException"></exception> /// <exception cref="NGit.Api.Errors.GitAPIException"></exception> public virtual void SetupRepository() { // create initial commit git = new Git(db); initialCommit = git.Commit().SetMessage("initial commit").Call(); // create nested file FilePath dir = new FilePath(db.WorkTree, "dir"); FileUtils.Mkdir(dir); FilePath nestedFile = new FilePath(dir, "b.txt"); FileUtils.CreateNewFile(nestedFile); PrintWriter nesterFileWriter = new PrintWriter(nestedFile); nesterFileWriter.Write("content"); nesterFileWriter.Flush(); // create file indexFile = new FilePath(db.WorkTree, "a.txt"); FileUtils.CreateNewFile(indexFile); PrintWriter writer = new PrintWriter(indexFile); writer.Write("content"); writer.Flush(); // add file and commit it git.Add().AddFilepattern("dir").AddFilepattern("a.txt").Call(); secondCommit = git.Commit().SetMessage("adding a.txt and dir/b.txt").Call(); prestage = DirCache.Read(db.GetIndexFile(), db.FileSystem).GetEntry(indexFile.GetName ()); // modify file and add to index writer.Write("new content"); writer.Close(); nesterFileWriter.Write("new content"); nesterFileWriter.Close(); git.Add().AddFilepattern("a.txt").AddFilepattern("dir").Call(); // create a file not added to the index untrackedFile = new FilePath(db.WorkTree, "notAddedToIndex.txt"); FileUtils.CreateNewFile(untrackedFile); PrintWriter writer2 = new PrintWriter(untrackedFile); writer2.Write("content"); writer2.Close(); }
/// <exception cref="System.Exception"></exception> public static void Run(ShellContextFactory shellContextFactory, FilePath jsFile, ShellTest.Parameters parameters, ShellTest.Status status) { Global global = new Global(); MemoryStream @out = new MemoryStream(); TextWriter p = new TextWriter(@out); global.SetOut(p); global.SetErr(p); global.DefineFunctionProperties(new string[] { "options" }, typeof(ShellTest), ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY); // test suite expects keywords to be disallowed as identifiers shellContextFactory.SetAllowReservedKeywords(false); ShellTest.TestState testState = new ShellTest.TestState(); if (jsFile.GetName().EndsWith("-n.js")) { status.SetNegative(); } Exception[] thrown = new Exception[] { null }; Sharpen.Thread t = new Sharpen.Thread(new _Runnable_274(shellContextFactory, thrown, testState, status, jsFile, global), jsFile.GetPath()); t.SetDaemon(true); t.Start(); t.Join(parameters.GetTimeoutMilliseconds()); lock (testState) { if (!testState.finished) { CallStop(t); status.TimedOut(); } } int expectedExitCode = 0; p.Flush(); status.OutputWas(Sharpen.Runtime.GetStringForBytes(@out.ToArray())); BufferedReader r = new BufferedReader(new StreamReader(new MemoryStream(@out.ToArray()))); string failures = string.Empty; for (; ; ) { string s = r.ReadLine(); if (s == null) { break; } if (s.IndexOf("FAILED!") != -1) { failures += s + '\n'; } int expex = s.IndexOf("EXPECT EXIT CODE "); if (expex != -1) { expectedExitCode = s[expex + "EXPECT EXIT CODE ".Length] - '0'; } } if (thrown[0] != null) { status.Threw(thrown[0]); } status.ExitCodesWere(expectedExitCode, testState.exitCode); if (failures != string.Empty) { status.Failed(failures); } }
/// <summary>Guess the proper path for a Git repository.</summary> /// <remarks> /// Guess the proper path for a Git repository. /// <p> /// The method performs some basic guessing to locate the repository. /// Searched paths are: /// <ol> /// <li> /// <code>directory</code> /// // assume exact match</li> /// <li> /// <code>directory</code> /// + "/.git" // assume working directory</li> /// <li> /// <code>directory</code> /// + ".git" // assume bare</li> /// </ol> /// </remarks> /// <param name="directory">location to guess from. Several permutations are tried.</param> /// <param name="fs"> /// the file system abstraction which will be necessary to /// perform certain file system operations. /// </param> /// <returns> /// the actual directory location if a better match is found; /// null if there is no suitable match. /// </returns> public static FilePath Resolve(FilePath directory, FS fs) { if (IsGitRepository(directory, fs)) { return directory; } if (IsGitRepository(new FilePath(directory, Constants.DOT_GIT), fs)) { return new FilePath(directory, Constants.DOT_GIT); } string name = directory.GetName(); FilePath parent = directory.GetParentFile(); if (IsGitRepository(new FilePath(parent, name + Constants.DOT_GIT_EXT), fs)) { return new FilePath(parent, name + Constants.DOT_GIT_EXT); } return null; }
public bool Accept(FilePath pathname) { return pathname.GetName().EndsWith(".js") && !pathname.GetName().Equals("shell.js") && !pathname.GetName().Equals("browser.js") && !pathname.GetName().Equals("template.js"); }
/// <summary>Compile JavaScript source.</summary> /// <remarks>Compile JavaScript source.</remarks> public virtual void ProcessSource(string[] filenames) { for (int i = 0; i != filenames.Length; ++i) { string filename = filenames[i]; if (!filename.EndsWith(".js")) { AddError("msg.extension.not.js", filename); return; } FilePath f = new FilePath(filename); string source = ReadSource(f); if (source == null) { return; } string mainClassName = targetName; if (mainClassName == null) { string name = f.GetName(); string nojs = Sharpen.Runtime.Substring(name, 0, name.Length - 3); mainClassName = GetClassName(nojs); } if (targetPackage.Length != 0) { mainClassName = targetPackage + "." + mainClassName; } object[] compiled = compiler.CompileToClassFiles(source, filename, 1, mainClassName); if (compiled == null || compiled.Length == 0) { return; } FilePath targetTopDir = null; if (destinationDir != null) { targetTopDir = new FilePath(destinationDir); } else { string parent = f.GetParent(); if (parent != null) { targetTopDir = new FilePath(parent); } } for (int j = 0; j != compiled.Length; j += 2) { string className = (string)compiled[j]; byte[] bytes = (byte[])compiled[j + 1]; FilePath outfile = GetOutputFile(targetTopDir, className); try { FileOutputStream os = new FileOutputStream(outfile); try { os.Write(bytes); } finally { os.Close(); } } catch (IOException ioe) { AddFormatedError(ioe.ToString()); } } } }
/// <summary>An application entry point.</summary> /// <remarks> /// An application entry point. Takes the name of one or more files as arguments and prints the contents of all /// metadata directories to <code>System.out</code>. /// <p/> /// If <code>-thumb</code> is passed, then any thumbnail data will be written to a file with name of the /// input file having <code>.thumb.jpg</code> appended. /// <p/> /// If <code>-wiki</code> is passed, then output will be in a format suitable for Google Code's wiki. /// <p/> /// If <code>-hex</code> is passed, then the ID of each tag will be displayed in hexadecimal. /// </remarks> /// <param name="args">the command line arguments</param> /// <exception cref="Com.Drew.Metadata.MetadataException"/> /// <exception cref="System.IO.IOException"/> public static void Main(string[] args) { ICollection<string> argList = new AList<string>(Arrays.AsList(args)); bool thumbRequested = argList.Remove("-thumb"); bool wikiFormat = argList.Remove("-wiki"); bool showHex = argList.Remove("-hex"); if (argList.Count < 1) { string version = typeof(Com.Drew.Imaging.ImageMetadataReader).Assembly.GetImplementationVersion(); System.Console.Out.Println("metadata-extractor version " + version); System.Console.Out.Println(); System.Console.Out.Println(Sharpen.Extensions.StringFormat("Usage: java -jar metadata-extractor-%s.jar <filename> [<filename>] [-thumb] [-wiki] [-hex]", version == null ? "a.b.c" : version)); System.Environment.Exit(1); } foreach (string filePath in argList) { long startTime = Runtime.NanoTime(); FilePath file = new FilePath(filePath); if (!wikiFormat && argList.Count > 1) { System.Console.Out.Printf("\n***** PROCESSING: %s\n%n", filePath); } Com.Drew.Metadata.Metadata metadata = null; try { metadata = Com.Drew.Imaging.ImageMetadataReader.ReadMetadata(file); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e, System.Console.Error); System.Environment.Exit(1); } long took = Runtime.NanoTime() - startTime; if (!wikiFormat) { System.Console.Out.Printf("Processed %.3f MB file in %.2f ms%n%n", file.Length() / (1024d * 1024), took / 1000000d); } if (wikiFormat) { string fileName = file.GetName(); string urlName = StringUtil.UrlEncode(fileName); ExifIFD0Directory exifIFD0Directory = metadata.GetDirectory<ExifIFD0Directory>(); string make = exifIFD0Directory == null ? string.Empty : StringUtil.EscapeForWiki(exifIFD0Directory.GetString(ExifIFD0Directory.TagMake)); string model = exifIFD0Directory == null ? string.Empty : StringUtil.EscapeForWiki(exifIFD0Directory.GetString(ExifIFD0Directory.TagModel)); System.Console.Out.Println(); System.Console.Out.Println("-----"); System.Console.Out.Println(); System.Console.Out.Printf("= %s - %s =%n", make, model); System.Console.Out.Println(); System.Console.Out.Printf("<a href=\"http://sample-images.metadata-extractor.googlecode.com/git/%s\">%n", urlName); System.Console.Out.Printf("<img src=\"http://sample-images.metadata-extractor.googlecode.com/git/%s\" width=\"300\"/><br/>%n", urlName); System.Console.Out.Println(StringUtil.EscapeForWiki(fileName)); System.Console.Out.Println("</a>"); System.Console.Out.Println(); System.Console.Out.Println("|| *Directory* || *Tag Id* || *Tag Name* || *Extracted Value* ||"); } // iterate over the metadata and print to System.out foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { string directoryName = directory.GetName(); foreach (Tag tag in directory.GetTags()) { string tagName = tag.GetTagName(); string description = tag.GetDescription(); // truncate the description if it's too long if (description != null && description.Length > 1024) { description = Sharpen.Runtime.Substring(description, 0, 1024) + "..."; } if (wikiFormat) { System.Console.Out.Printf("||%s||0x%s||%s||%s||%n", StringUtil.EscapeForWiki(directoryName), Sharpen.Extensions.ToHexString(tag.GetTagType()), StringUtil.EscapeForWiki(tagName), StringUtil.EscapeForWiki(description)); } else { if (showHex) { System.Console.Out.Printf("[%s - %s] %s = %s%n", directoryName, tag.GetTagTypeHex(), tagName, description); } else { System.Console.Out.Printf("[%s] %s = %s%n", directoryName, tagName, description); } } } // print out any errors foreach (string error in directory.GetErrors()) { System.Console.Error.Println("ERROR: " + error); } } if (args.Length > 1 && thumbRequested) { ExifThumbnailDirectory directory_1 = metadata.GetDirectory<ExifThumbnailDirectory>(); if (directory_1 != null && directory_1.HasThumbnailData()) { System.Console.Out.Println("Writing thumbnail..."); directory_1.WriteThumbnail(Sharpen.Extensions.Trim(args[0]) + ".thumb.jpg"); } else { System.Console.Out.Println("No thumbnail data exists in this image"); } } } }
/// <summary>Get the lock file corresponding to the given file.</summary> /// <remarks>Get the lock file corresponding to the given file.</remarks> /// <param name="file"></param> /// <returns>lock file</returns> internal static FilePath GetLockFile(FilePath file) { return new FilePath(file.GetParentFile(), file.GetName() + SUFFIX); }
internal JsTestCase(FilePath jsFile, int optimizationLevel) : base(jsFile.GetName() + (optimizationLevel == 1 ? "-compiled" : "-interpreted")) { this.jsFile = jsFile; this.optimizationLevel = optimizationLevel; }