diff --git a/.gitignore b/.gitignore
index 6c9e3630..11549e10 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,6 +27,8 @@ aclocal.m4
autom4te.cache/
bin/
obj/
+/bin/
+SparkleShare/Mac/bin
install-sh
libtool
ltmain.sh
diff --git a/Makefile.am b/Makefile.am
index 1ca9d1da..b4293c03 100755
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,4 +1,4 @@
-basedirs = build help SmartIrc4net SparkleLib data po
+basedirs = build help SparkleLib data po
SUBDIRS = $(basedirs) $(GUISUBDIRS)
DIST_SUBDIRS = $(basedirs) SparkleShare
diff --git a/NEWS b/NEWS
index 6b8eba0b..3adfa0d2 100755
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,25 @@
+0.6.0 for Linux and Mac (Sun Dec 25 2011):
+
+ Hylke:
+ - Several fixes for annoying bugs and crashes
+ - Fix freeze on quit on Mac
+ - Show project and history size in the event log
+
+
+0.4.2 for Linux and Mac (Fri Dec 2 2011):
+ Hylke: Fix crash trying to add a project
+
+
+0.4.1 for Linux and Mac (Tue Nov 29 2011):
+ Hylke: Just some small tweaks and fixes:
+
+ - Bundle git with the Mac application
+ - Warn about potential global gitignore files
+ - Remove SmartIrc4Net
+ - Build system fixes
+ - Code cleanups
+
+
0.4.0 for Linux and Mac (Sun Nov 12 2011):
Hylke: It has been a while since the last release. Since so many
things changed, and it being (softly) incompatible with 0.2, I decided
diff --git a/README b/README
deleted file mode 100644
index 8dfd1a40..00000000
--- a/README
+++ /dev/null
@@ -1,145 +0,0 @@
-# SparkleShare
-
-SparkleShare is a collaboration and sharing tool that is designed to keep
-things simple and to stay out of your way. It allows you to instantly sync
-with any Git repository you have access to.
-
-SparkleShare currently works on Linux and Mac. A Windows port and mobile
-device support are planned for the future.
-
-
-# License
-
-SparkleShare is free software and licensed under the GNU GPLv3 or later. You
-are welcome to change and redistribute it under certain conditions. For more
-information see the LICENSE file or visit http://www.gnu.org/licenses/gpl-3.0.html
-
-
-# Run on Linux
-
-Requirements:
-
- - git >= 1.7.0
- - gtk-sharp2
- - gvfs
- - intltool
- - libnotify
- - mono-core >= 2.8
- - notify-sharp
- - nautilus-python
- - openssh
- - pygtk
- - webkitgtk
- - webkit-sharp
-
-Run the service, either click the SparkleShare launcher or:
-
- $ sparkleshare start
-
-You can stop the service via the graphical interface or by typing:
-
- $ sparkleshare stop
-
-For help:
-
- $ sparkleshare --help
-
-Note:
-
- SparkleShare creates its own RSA keypair in ~/config/sparkleshare/ and uses
- that for authentication. Please mind this if you're planning to set up your
- own server by hand.
-
-
-# Build on Linux
-
-Installing the build dependencies on Debian or Ubuntu:
-
- $ sudo apt-get install gtk-sharp2 mono-runtime mono-devel monodevelop \
- libndesk-dbus1.0-cil-dev nant libnotify-cil-dev libgtk2.0-cil-dev mono-gmcs \
- libwebkit-cil-dev intltool libtool python-nautilus libndesk-dbus-glib1.0-cil-dev
-
-For Ubuntu libappindicator support, run the following before building:
-
- $ sudo apt-get install libappindicator0.1-cil-dev
-
-On Fedora:
-
- $ sudo yum install gtk-sharp2-devel mono-core mono-devel monodevelop \
- ndesk-dbus-devel ndesk-dbus-glib-devel nautilus-python-devel nant \
- notify-sharp-devel webkit-sharp-devel webkitgtk-devel libtool intltool \
- gnome-doc-utils
-
-You can build and install SparkleShare like this:
-
- $ ./configure --prefix=/usr (or ./autogen.sh if you build from the repository)
- $ make
- $ sudo make install
-
-Note:
-
- Use '--prefix=/usr' if you want the Nautilus extension to work.
-
-
-# Run on Mac
-
-Just double-click the SparkleShare bundle.
-
-
-# Build on Mac
-
-Install Xcode, the Mono Framework, MonoDevelop and the MonoMac plugin (you can find it in MonoDevelop => Add-in Manager).
-
-You may need to adjust some environment variables to let the build environment tools find mono:
-
- $ export PATH=/Library/Frameworks/Mono.framework/Versions/Current/bin:$PATH
- $ export PKG_CONFIG=/Library/Frameworks/Mono.framework/Versions/Current/bin/pkg-config
- $ export PKG_CONFIG_PATH=/Library/Frameworks/Mono.framework/Versions/Current/lib/pkgconfig
-
-Install git, automake, and intltool using MacPorts:
-
- $ sudo port install git-core automake intltool
-
-Start the first part of the build:
-
- $ ./autogen.sh --enable-gtkui=no
- $ make
-
-Now that you have compiled the libraries, open 'SparkleShare/Mac/SparkleShare.sln' in
-MonoDevelop and start the build.
-
-To create the SparkleShare.app, make sure the project is focused and select Project from the menu bar
-and click "Create Mac Installer...". Make sure to select "Don't link assemblies".
-
-Save the SparkleShare.app somewhere. Paste the contents of
-the following file in SparkleShare.app/Contents/MonoBundle/config:
-https://raw.github.com/gist/1aeffa61bac73fc08eca/0c0f09ef9e36864c35f34fd5e8bf4f99886be193/gistfile1.txt
-
-Copy /Library/Frameworks/Mono.framework/Versions/Current/lib/libintl.dylib
-to SparkleShare.app/Contents/Resources
-
-Now you should have a working bundle that you can run.
-
-
-# Info
-
-Official website:
-http://www.sparkleshare.org/
-
-Source code:
-http://github.com/SparkleShare/
-
-IRC Channel:
-#sparkleshare on irc.gnome.org
-
-Wiki:
-http://github.com/hbons/SparkleShare/wiki/
-
-Report issues:
-http://github.com/hbons/SparkleShare/issues/
-
-Translation project:
-http://www.transifex.net/projects/p/sparkleshare/
-
-
-Now have fun and create cool things together! :)
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..1f35cbd5
--- /dev/null
+++ b/README.md
@@ -0,0 +1,162 @@
+# SparkleShare
+
+SparkleShare is a collaboration and sharing tool that is designed to keep
+things simple and to stay out of your way. It allows you to instantly sync
+with any Git repository you have access to.
+
+SparkleShare currently works on Linux and Mac. A Windows port and mobile
+device support are planned for the future.
+
+[![Flattr this git repo](http://api.flattr.com/button/flattr-badge-large.png)](https://flattr.com/thing/21770/SparkleShare-Sharing-work-made-easy)
+
+
+## License
+
+SparkleShare is free software and licensed under the GNU GPLv3 or later. You
+are welcome to change and redistribute it under certain conditions. For more
+information see the LICENSE file or visit http://www.gnu.org/licenses/gpl-3.0.html
+
+
+## Run on Linux
+
+Requirements:
+
+ - git >= 1.7.0
+ - gtk-sharp2
+ - gvfs
+ - intltool
+ - libnotify
+ - mono-core >= 2.8
+ - notify-sharp
+ - nautilus-python
+ - openssh
+ - pygtk
+ - webkitgtk
+ - webkit-sharp
+
+Run the service, either click the SparkleShare launcher or:
+
+```bash
+$ sparkleshare start
+```
+
+You can stop the service via the graphical interface or by typing:
+
+```bash
+$ sparkleshare stop
+```
+
+For help:
+
+```bash
+$ sparkleshare --help
+```
+
+**Note:**
+
+ SparkleShare creates its own RSA keypair in `~/config/sparkleshare/` and uses
+ that for authentication. Please mind this if you're planning to set up your
+ own server by hand.
+
+
+## Build on Linux
+
+### Install build dependencies
+
+#### Debian or Ubuntu (apt):
+
+```bash
+$ sudo apt-get install gtk-sharp2 mono-runtime mono-devel monodevelop \
+ libndesk-dbus1.0-cil-dev nant libnotify-cil-dev libgtk2.0-cil-dev mono-mcs mono-gmcs \
+ libwebkit-cil-dev intltool libtool python-nautilus libndesk-dbus-glib1.0-cil-dev
+```
+
+#### Fedora (yum):
+
+```bash
+$ sudo yum install gtk-sharp2-devel mono-core mono-devel monodevelop \
+ ndesk-dbus-devel ndesk-dbus-glib-devel nautilus-python-devel nant \
+ notify-sharp-devel webkit-sharp-devel webkitgtk-devel libtool intltool \
+ gnome-doc-utils
+```
+
+For Ubuntu `libappindicator` support, install the following package:
+
+```bash
+$ sudo apt-get install libappindicator0.1-cil-dev
+```
+
+You can then build and install SparkleShare like this:
+
+```bash
+$ ./configure --prefix=/usr (or ./autogen.sh if you build from the repository)
+$ make
+$ sudo make install
+```
+
+**Note:** Use `--prefix=/usr` if you want the Nautilus extension to work.
+
+
+## Run on Mac
+
+Just double-click the SparkleShare bundle.
+
+
+## Build on Mac
+
+Install Xcode, the Mono Framework, MonoDevelop and the MonoMac plugin
+(you can find it in MonoDevelop => Add-in Manager).
+
+You may need to adjust some environment variables to let the build environment tools find mono:
+
+```bash
+$ export PATH=/Library/Frameworks/Mono.framework/Versions/Current/bin:$PATH
+$ export PKG_CONFIG=/Library/Frameworks/Mono.framework/Versions/Current/bin/pkg-config
+$ export PKG_CONFIG_PATH=/Library/Frameworks/Mono.framework/Versions/Current/lib/pkgconfig
+```
+
+Install git, automake, and intltool using MacPorts:
+
+```bash
+$ sudo port install git-core automake intltool
+```
+
+Start the first part of the build:
+
+```bash
+$ ./autogen.sh --enable-gtkui=no
+$ make
+```
+
+Now that you have compiled the libraries, open `SparkleShare/Mac/SparkleShare.sln` in
+MonoDevelop and start the build.
+
+To create the SparkleShare.app, make sure the project is focused and select Project from the menu bar
+and click "Create Mac Installer...". Make sure to select "Don't link assemblies".
+
+Save the SparkleShare.app somewhere. Paste the contents of
+the following file in `SparkleShare.app/Contents/MonoBundle/config`:
+
+```
+https://raw.github.com/gist/1aeffa61bac73fc08eca/0c0f09ef9e36864c35f34fd5e8bf4f99886be193/gistfile1.txt
+```
+
+Copy `/Library/Frameworks/Mono.framework/Versions/Current/lib/libintl.dylib` to `SparkleShare.app/Contents/Resources`
+
+
+Now you should have a working bundle that you can run.
+
+
+## Info
+
+|||
+|-----------------------------------:|:--------------------------|
+| **Official website**: | http://www.sparkleshare.org/ |
+| **Source code**: | http://github.com/SparkleShare/ |
+| **IRC Channel**: | #sparkleshare on irc.gnome.org |
+| **Wiki**: | http://github.com/hbons/SparkleShare/wiki/ |
+| **Report issues**: | http://github.com/hbons/SparkleShare/issues/ |
+| **Translation project**: | http://www.transifex.net/projects/p/sparkleshare/ |
+
+
+Now have fun and create cool things together! :)
diff --git a/SmartIrc4net b/SmartIrc4net
deleted file mode 160000
index 036e2233..00000000
--- a/SmartIrc4net
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 036e2233aea9bd3b4a30f8c5136daff0187eb5ec
diff --git a/SparkleLib/Git/SparkleFetcherGit.cs b/SparkleLib/Git/SparkleFetcherGit.cs
index d7086d7c..5b0e0098 100755
--- a/SparkleLib/Git/SparkleFetcherGit.cs
+++ b/SparkleLib/Git/SparkleFetcherGit.cs
@@ -90,10 +90,13 @@ namespace SparkleLib {
this.git.StartInfo.RedirectStandardError = true;
this.git.Start ();
-
+
double percentage = 1.0;
Regex progress_regex = new Regex (@"([0-9]+)%", RegexOptions.Compiled);
-
+
+ DateTime last_change = DateTime.Now;
+ TimeSpan change_interval = new TimeSpan (0, 0, 0, 1);
+
while (!this.git.StandardError.EndOfStream) {
string line = this.git.StandardError.ReadLine ();
Match match = progress_regex.Match (line);
@@ -107,7 +110,7 @@ namespace SparkleLib {
// the "Receiving objects" stage which we count as the last 80%
if (line.Contains ("|"))
// "Receiving objects" stage
- number = (number / 100 * 75 + 20);
+ number = (number / 100 * 80 + 20);
else
// "Compressing objects" stage
number = (number / 100 * 20);
@@ -115,20 +118,21 @@ namespace SparkleLib {
if (number >= percentage) {
percentage = number;
-
- // FIXME: for some reason it doesn't go above 95%
- base.OnProgressChanged (percentage);
+
+ if (DateTime.Compare (last_change, DateTime.Now.Subtract (change_interval)) < 0) {
+ base.OnProgressChanged (percentage);
+ last_change = DateTime.Now;
+ }
}
-
- System.Threading.Thread.Sleep (100);
}
this.git.WaitForExit ();
-
SparkleHelpers.DebugInfo ("Git", "Exit code " + this.git.ExitCode.ToString ());
+
if (this.git.ExitCode != 0) {
return false;
+
} else {
InstallConfiguration ();
InstallExcludeRules ();
@@ -137,9 +141,33 @@ namespace SparkleLib {
}
+ public override string [] Warnings {
+ get {
+ SparkleGit git = new SparkleGit (SparkleConfig.DefaultConfig.TmpPath,
+ "config --global core.excludesfile");
+
+ git.Start ();
+
+ // Reading the standard output HAS to go before
+ // WaitForExit, or it will hang forever on output > 4096 bytes
+ string output = git.StandardOutput.ReadToEnd ().Trim ();
+ git.WaitForExit ();
+
+ if (string.IsNullOrEmpty (output)) {
+ return null;
+
+ } else {
+ return new string [] {
+ string.Format ("You seem to have configured a system ‘gitignore’ file. " +
+ "This may interfere with SparkleShare.\n({0})", output)
+ };
+ }
+ }
+ }
+
public override void Stop ()
{
- if (this.git != null) {
+ if (this.git != null && !this.git.HasExited) {
this.git.Kill ();
this.git.Dispose ();
}
@@ -179,22 +207,11 @@ namespace SparkleLib {
// Add a .gitignore file to the repo
private void InstallExcludeRules ()
{
- string exclude_rules_file_path = SparkleHelpers.CombineMore (
- this.target_folder, ".git", "info", "exclude");
+ DirectoryInfo info = Directory.CreateDirectory (SparkleHelpers.CombineMore (
+ this.target_folder, ".git", "info"));
- string directory = Path.GetDirectoryName(exclude_rules_file_path);
-
- if (directory == null)
- {
- return;
- }
-
- if (!Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
-
- TextWriter writer = new StreamWriter (exclude_rules_file_path);
+ string exlude_rules_file_path = Path.Combine (info.FullName, "exclude");
+ TextWriter writer = new StreamWriter (exlude_rules_file_path);
// gedit and emacs
writer.WriteLine ("*~");
@@ -226,7 +243,7 @@ namespace SparkleLib {
writer.WriteLine ("Thumbs.db");
writer.WriteLine ("Desktop.ini");
- // MS Office
+ // MS Office
writer.WriteLine ("~*.tmp");
writer.WriteLine ("~*.TMP");
writer.WriteLine ("*~*.tmp");
@@ -257,6 +274,7 @@ namespace SparkleLib {
}
}
+
public class SparkleGit : Process {
public SparkleGit (string path, string args) : base ()
diff --git a/SparkleLib/Git/SparkleRepoGit.cs b/SparkleLib/Git/SparkleRepoGit.cs
index c00d84bb..e2eda251 100644
--- a/SparkleLib/Git/SparkleRepoGit.cs
+++ b/SparkleLib/Git/SparkleRepoGit.cs
@@ -26,15 +26,8 @@ namespace SparkleLib {
public class SparkleRepoGit : SparkleRepoBase {
- private string exlude_rules_file_path;
- private string ExclusionBlock = "#Temporary Exclusions";
-
public SparkleRepoGit (string path, SparkleBackend backend) :
- base (path, backend) {
- // Set exclude file path
- exlude_rules_file_path = SparkleHelpers.CombineMore (
- LocalPath, ".git", "info", "exclude");
- }
+ base (path, backend) { }
private string identifier = null;
@@ -66,6 +59,34 @@ namespace SparkleLib {
}
+ public override List ExcludePaths {
+ get {
+ List rules = new List ();
+ rules.Add (Path.DirectorySeparatorChar + ".git");
+
+ return rules;
+ }
+ }
+
+
+ public override double Size {
+ get {
+ return CalculateSize (
+ new DirectoryInfo (LocalPath)
+ );
+ }
+ }
+
+
+ public override double HistorySize {
+ get {
+ return CalculateSize (
+ new DirectoryInfo (Path.Combine (LocalPath, ".git"))
+ );
+ }
+ }
+
+
public override string [] UnsyncedFilePaths {
get {
List file_paths = new List ();
@@ -144,16 +165,73 @@ namespace SparkleLib {
public override bool SyncUp ()
{
- Add ();
+ if (AnyDifferences) {
+ Add ();
- string message = FormatCommitMessage ();
- Commit (message);
+ string message = FormatCommitMessage ();
+ Commit (message);
+ }
- SparkleGit git = new SparkleGit (LocalPath, "push origin master");
+
+ SparkleGit git = new SparkleGit (LocalPath,
+ "push --progress " + // Redirects progress stats to standarderror
+ "origin master");
+
+ git.StartInfo.RedirectStandardError = true;
git.Start ();
- git.StandardOutput.ReadToEnd ();
+
+ double percentage = 1.0;
+ Regex progress_regex = new Regex (@"([0-9]+)%", RegexOptions.Compiled);
+
+ DateTime last_change = DateTime.Now;
+ TimeSpan change_interval = new TimeSpan (0, 0, 0, 1);
+
+ while (!git.StandardError.EndOfStream) {
+ string line = git.StandardError.ReadLine ();
+ Match match = progress_regex.Match (line);
+ string speed = "";
+ double number = 0.0;
+
+ if (match.Success) {
+ number = double.Parse (match.Groups [1].Value);
+
+ // The pushing progress consists of two stages: the "Compressing
+ // objects" stage which we count as 20% of the total progress, and
+ // the "Writing objects" stage which we count as the last 80%
+ if (line.StartsWith ("Compressing")) {
+ // "Compressing objects" stage
+ number = (number / 100 * 20);
+
+ } else {
+ // "Writing objects" stage
+ number = (number / 100 * 80 + 20);
+
+ if (line.Contains ("|")) {
+ speed = line.Substring (line.IndexOf ("|") + 1).Trim ();
+ speed = speed.Replace (", done.", "").Trim ();
+ speed = speed.Replace ("i", "");
+ speed = speed.Replace ("KB/s", "ᴋʙ/s");
+ speed = speed.Replace ("MB/s", "ᴍʙ/s");
+ }
+ }
+ }
+
+ if (number >= percentage) {
+ percentage = number;
+
+ if (percentage == 100.0)
+ percentage = 99.0;
+
+ if (DateTime.Compare (last_change, DateTime.Now.Subtract (change_interval)) < 0) {
+ base.OnSyncProgressChanged (percentage, speed);
+ last_change = DateTime.Now;
+ }
+ }
+ }
+
git.WaitForExit ();
+
if (git.ExitCode == 0)
return true;
else
@@ -163,10 +241,63 @@ namespace SparkleLib {
public override bool SyncDown ()
{
- SparkleGit git = new SparkleGit (LocalPath, "fetch -v");
+ SparkleGit git = new SparkleGit (LocalPath, "fetch --progress");
+
+ git.StartInfo.RedirectStandardError = true;
git.Start ();
+
+ double percentage = 1.0;
+ Regex progress_regex = new Regex (@"([0-9]+)%", RegexOptions.Compiled);
+
+ DateTime last_change = DateTime.Now;
+ TimeSpan change_interval = new TimeSpan (0, 0, 0, 1);
+
+ while (!git.StandardError.EndOfStream) {
+ string line = git.StandardError.ReadLine ();
+ Match match = progress_regex.Match (line);
+ string speed = "";
+ double number = 0.0;
+
+ if (match.Success) {
+ number = double.Parse (match.Groups [1].Value);
+
+ // The fetching progress consists of two stages: the "Compressing
+ // objects" stage which we count as 20% of the total progress, and
+ // the "Receiving objects" stage which we count as the last 80%
+ if (line.StartsWith ("Compressing")) {
+ // "Compressing objects" stage
+ number = (number / 100 * 20);
+
+ } else {
+ // "Writing objects" stage
+ number = (number / 100 * 80 + 20);
+
+ if (line.Contains ("|")) {
+ speed = line.Substring (line.IndexOf ("|") + 1).Trim ();
+ speed = speed.Replace (", done.", "").Trim ();
+ speed = speed.Replace ("i", "");
+ speed = speed.Replace ("KB/s", "ᴋʙ/s");
+ speed = speed.Replace ("MB/s", "ᴍʙ/s");
+ }
+ }
+ }
+
+ if (number >= percentage) {
+ percentage = number;
+
+ if (percentage == 100.0)
+ percentage = 99.0;
+
+ if (DateTime.Compare (last_change, DateTime.Now.Subtract (change_interval)) < 0) {
+ base.OnSyncProgressChanged (percentage, speed);
+ last_change = DateTime.Now;
+ }
+ }
+ }
+
git.WaitForExit ();
+
if (git.ExitCode == 0) {
Rebase ();
return true;
@@ -216,6 +347,7 @@ namespace SparkleLib {
if (value) {
if (!File.Exists (unsynced_file_path))
File.Create (unsynced_file_path).Close ();
+
} else {
File.Delete (unsynced_file_path);
}
@@ -233,177 +365,16 @@ namespace SparkleLib {
SparkleHelpers.DebugInfo ("Git", "[" + Name + "] Changes staged");
}
- // Add a new file to be ignored
- public override bool AddExclusionRule (FileSystemEventArgs args) {
-
- string RelativePath = SparkleHelpers.DiffPaths(args.FullPath, LocalPath);
-
- List exclusions;
- try {
- exclusions = ReadExclusionRules();
- }
- catch {
- return false;
- }
-
- // Look for the local exclusions section
- bool added = false;
- for(int i = 0; i < exclusions.Count; i++) {
- string entry = exclusions[i];
- if(entry.Equals(ExclusionBlock)) {
- // add a new exclusion rule containing a file path
- exclusions.Insert(i + 1, RelativePath);
- added = true;
- break;
- }
- }
-
- /*
- * For compability to existing repos:
- * Add a "#Temporary Exclusions"-Block to the
- * ignore file in order to recognize this
- * exclude rules later on
- */
- if(!added) {
- exclusions.Add(ExclusionBlock);
- exclusions.Add(RelativePath);
- }
-
- // Write exceptions list back to file
- return WriteExclusionRules(exclusions);
- }
-
- // Check whether a specific rule exists in the exclusion file
- public override bool ExclusionRuleExists(FileSystemEventArgs args) {
- string RelativePath = SparkleHelpers.DiffPaths(args.FullPath, LocalPath);
-
- List exclusions;
- try {
- // Read rules from temporary block only
- exclusions = ReadExclusionRules(true);
-
- foreach(string entry in exclusions) {
- if(entry.Equals(RelativePath)) {
- return true;
- }
- }
- } catch {
- SparkleHelpers.DebugInfo("Error", "Cannot determine whether an exclusion rule for " +
- args.FullPath + " already exists or not.");
- return false;
- }
-
- return false;
- }
-
- // Remove file from exclusion list when they are readable again
- public override bool RemoveExclusionRule(FileSystemEventArgs args) {
- string RelativePath = SparkleHelpers.DiffPaths(args.FullPath, LocalPath);
-
- List exclusions;
- try {
- exclusions = ReadExclusionRules();
-
- /*
- * Removing a rule should only apply to rules in the "Temporary Exclusion"-block.
- * Therefore we first read until reaching the block and then remove the rule.
- *
- * We cannot use ReadExclusionRules(true) here since we write all lines back
- * to the file. This would result in a crippled exclusion file.
- */
- bool BlockReached = false;
- foreach(string entry in exclusions) {
- if(entry.Equals(ExclusionBlock)) {
- BlockReached = true;
- }
-
- // Remove this rule
- if(BlockReached && entry.Equals(RelativePath)) {
- exclusions.Remove(entry);
- break;
- }
- }
-
- return WriteExclusionRules(exclusions);
- } catch {
- SparkleHelpers.DebugInfo("Error", "Unable to remove exclusion rule for entry " + RelativePath);
- return false;
- }
- }
-
- // Reads the exclusion rules file into a string list
- private List ReadExclusionRules() {
-
- List exclusions = new List();
- TextReader reader = new StreamReader (exlude_rules_file_path);;
-
- try {
- while(reader.Peek() > -1) {
- exclusions.Add(reader.ReadLine().TrimEnd());
- }
- }
- catch (IOException e) {
- SparkleHelpers.DebugInfo("Error", "Reading from exclusion file failed: " + e.Message);
- return new List();
- }
- finally {
- if(reader != null) {
- reader.Close();
- }
- }
-
- return exclusions;
- }
-
- // Reads rules only from temporary exclusion block
- private List ReadExclusionRules(bool TempOnly) {
- if(TempOnly) {
- bool ForceRead = false;
- List exclusions = new List();
- foreach(string entry in ReadExclusionRules()) {
- if(ForceRead || entry.Equals(ExclusionBlock)) {
- exclusions.Add(entry);
- ForceRead = true;
- }
- }
-
- return exclusions;
- }
-
- return ReadExclusionRules();
- }
-
- // Writes the exclusion rules file with a given string list
- private bool WriteExclusionRules(List lines) {
-
- TextWriter writer = new StreamWriter (exlude_rules_file_path);
-
- try {
- foreach(string line in lines) {
- writer.WriteLine(line.TrimEnd());
- }
- } catch(IOException e) {
- SparkleHelpers.DebugInfo("Error", "Writing into exclusion file failed: " + e.Message);
- return false;
- }
- finally {
- if(writer != null) {
- writer.Close();
- }
- }
-
- return true;
- }
// Removes unneeded objects
- private void CollectGarbage ()
+/* private void CollectGarbage ()
{
SparkleGit git = new SparkleGit (LocalPath, "gc");
git.Start ();
git.WaitForExit ();
SparkleHelpers.DebugInfo ("Git", "[" + Name + "] Garbage collected.");
- }
+ } */
// Commits the made changes
@@ -486,11 +457,6 @@ namespace SparkleLib {
string output = git_status.StandardOutput.ReadToEnd ().TrimEnd ();
git_status.WaitForExit ();
- if (String.IsNullOrEmpty (output)) {
- // no conflict any more.
- return;
- }
-
string [] lines = output.Split ("\n".ToCharArray ());
foreach (string line in lines) {
@@ -571,13 +537,10 @@ namespace SparkleLib {
List change_sets = new List ();
- SparkleGit git_log = new SparkleGit (LocalPath, "log -" + count + " --raw -M --date=iso");
- if ((SparkleBackend.Platform == PlatformID.Unix ||
- SparkleBackend.Platform == PlatformID.MacOSX)) {
- // this causes an IOException on windows
- Console.OutputEncoding = System.Text.Encoding.Unicode;
- }
+ // Console.InputEncoding = System.Text.Encoding.Unicode;
+ Console.OutputEncoding = System.Text.Encoding.Unicode;
+ SparkleGit git_log = new SparkleGit (LocalPath, "log -" + count + " --raw -M --date=iso");
git_log.Start ();
// Reading the standard output HAS to go before
@@ -709,8 +672,12 @@ namespace SparkleLib {
FillEmptyDirectories (child_path);
}
- if (Directory.GetFiles (path).Length == 0 && !path.Equals (LocalPath))
+ if (Directory.GetFiles (path).Length == 0 &&
+ Directory.GetDirectories (path).Length == 0 &&
+ !path.Equals (LocalPath)) {
+
File.Create (Path.Combine (path, ".empty")).Close ();
+ }
}
@@ -752,6 +719,10 @@ namespace SparkleLib {
foreach (string added in Added) {
file_name = added.Trim ("\"".ToCharArray ());
+
+ if (file_name.EndsWith (".empty"))
+ file_name = file_name.Substring (0, file_name.Length - 6);
+
message += "+ ‘" + file_name + "’" + n;
count++;
@@ -761,6 +732,10 @@ namespace SparkleLib {
foreach (string modified in Modified) {
file_name = modified.Trim ("\"".ToCharArray ());
+
+ if (file_name.EndsWith (".empty"))
+ file_name = file_name.Substring (0, file_name.Length - 6);
+
message += "/ ‘" + file_name + "’" + n;
count++;
@@ -770,6 +745,10 @@ namespace SparkleLib {
foreach (string removed in Removed) {
file_name = removed.Trim ("\"".ToCharArray ());
+
+ if (file_name.EndsWith (".empty"))
+ file_name = file_name.Substring (0, file_name.Length - 6);
+
message += "- ‘" + file_name + "’" + n;
count++;
@@ -796,5 +775,38 @@ namespace SparkleLib {
base.CreateInitialChangeSet ();
SyncUp ();
}
+
+
+ // Recursively gets a folder's size in bytes
+ public override double CalculateSize (DirectoryInfo parent)
+ {
+ if (!Directory.Exists (parent.ToString ()))
+ return 0;
+
+ double size = 0;
+
+ // Ignore the temporary 'rebase-apply' and '.tmp' directories. This prevents potential
+ // crashes when files are being queried whilst the files have already been deleted.
+ if (parent.Name.Equals ("rebase-apply") ||
+ parent.Name.Equals (".tmp"))
+ return 0;
+
+ try {
+ foreach (FileInfo file in parent.GetFiles()) {
+ if (!file.Exists)
+ return 0;
+
+ size += file.Length;
+ }
+
+ foreach (DirectoryInfo directory in parent.GetDirectories ())
+ size += CalculateSize (directory);
+
+ } catch (Exception) {
+ return 0;
+ }
+
+ return size;
+ }
}
}
diff --git a/SparkleLib/Hg/SparkleFetcherHg.cs b/SparkleLib/Hg/SparkleFetcherHg.cs
deleted file mode 100755
index d89a3243..00000000
--- a/SparkleLib/Hg/SparkleFetcherHg.cs
+++ /dev/null
@@ -1,172 +0,0 @@
-// SparkleShare, a collaboration and sharing tool.
-// Copyright (C) 2010 Hylke Bons
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program. If not, see .
-
-
-using System;
-using System.IO;
-using System.Diagnostics;
-using System.Xml;
-
-namespace SparkleLib {
-
- // Sets up a fetcher that can get remote folders
- public class SparkleFetcherHg : SparkleFetcherBase {
-
- public SparkleFetcherHg (string server, string remote_folder, string target_folder) :
- base (server, remote_folder, target_folder) { }
-
-
- public override bool Fetch ()
- {
- SparkleHg hg = new SparkleHg (SparklePaths.SparkleTmpPath,
- "clone \"" + base.remote_url + "\" " + "\"" + base.target_folder + "\"");
-
- hg.Start ();
- hg.WaitForExit ();
-
- SparkleHelpers.DebugInfo ("Hg", "Exit code " + hg.ExitCode.ToString ());
-
- if (hg.ExitCode != 0) {
- return false;
- } else {
- InstallConfiguration ();
- InstallExcludeRules ();
- return true;
- }
- }
-
-
- // Install the user's name and email and some config into
- // the newly cloned repository
- private void InstallConfiguration ()
- {
- string global_config_file_path = Path.Combine (SparklePaths.SparkleConfigPath, "config.xml");
-
- if (!File.Exists (global_config_file_path))
- return;
-
- string repo_config_file_path = SparkleHelpers.CombineMore (base.target_folder, ".hg", "hgrc");
- string config = String.Join (Environment.NewLine, File.ReadAllLines (repo_config_file_path));
-
- // Add user info
- string n = Environment.NewLine;
- XmlDocument xml = new XmlDocument();
- xml.Load (global_config_file_path);
-
- XmlNode node_name = xml.SelectSingleNode ("//user/name/text()");
- XmlNode node_email = xml.SelectSingleNode ("//user/email/text()");
-
- // TODO this ignore duplicate names (FolderName (2))
- string ignore_file_path = base.target_folder.Replace (SparklePaths.SparkleTmpPath,
- SparklePaths.SparklePath);
-
- ignore_file_path = SparkleHelpers.CombineMore (ignore_file_path, ".hg", "hgignore");
-
- config += n +
- "[ui]" + n +
- "username = " + node_name.Value + " <" + node_email.Value + ">" + n +
- "ignore = " + ignore_file_path + n;
-
- // Write the config to the file
- TextWriter writer = new StreamWriter (repo_config_file_path);
- writer.WriteLine (config);
- writer.Close ();
-
- string style_file_path = SparkleHelpers.CombineMore (base.target_folder, ".hg", "log.style");
-
- string style = "changeset = \"{file_mods}{file_adds}{file_dels}\"" + n +
- "file_add = \"A {file_add}\\n\"" + n +
- "file_mod = \"M {file_mod}\\n\"" + n +
- "file_del = \"D {file_del}\\n\"" + n;
-
- writer = new StreamWriter (style_file_path);
- writer.WriteLine (style);
- writer.Close ();
-
- SparkleHelpers.DebugInfo ("Config", "Added configuration to '" + repo_config_file_path + "'");
- }
-
-
- // Add a .gitignore file to the repo
- private void InstallExcludeRules ()
- {
- string exlude_rules_file_path = SparkleHelpers.CombineMore (
- this.target_folder, ".hg", "hgignore");
-
- TextWriter writer = new StreamWriter (exlude_rules_file_path);
-
- writer.WriteLine ("syntax: glob");
-
- // gedit and emacs
- writer.WriteLine ("*~");
-
- // vi(m)
- writer.WriteLine (".*.sw[a-z]");
- writer.WriteLine ("*.un~");
- writer.WriteLine ("*.swp");
- writer.WriteLine ("*.swo");
-
- // KDE
- writer.WriteLine (".directory");
-
- // Mac OSX
- writer.WriteLine (".DS_Store");
- writer.WriteLine ("Icon?");
- writer.WriteLine ("._*");
- writer.WriteLine (".Spotlight-V100");
- writer.WriteLine (".Trashes");
-
- // Mac OSX
- writer.WriteLine ("*(Autosaved).graffle");
-
- // Windows
- writer.WriteLine ("Thumbs.db");
- writer.WriteLine ("Desktop.ini");
-
- // CVS
- writer.WriteLine ("*/CVS/*");
- writer.WriteLine (".cvsignore");
- writer.WriteLine ("*/.cvsignore");
-
- // Subversion
- writer.WriteLine ("/.svn/*");
- writer.WriteLine ("*/.svn/*");
-
- writer.Close ();
- }
- }
-
-
- public class SparkleHg : Process {
-
- public SparkleHg (string path, string args) : base ()
- {
- EnableRaisingEvents = true;
- StartInfo.FileName = "/opt/local/bin/hg";
- StartInfo.Arguments = args;
- StartInfo.RedirectStandardOutput = true;
- StartInfo.UseShellExecute = false;
- StartInfo.WorkingDirectory = path;
- }
-
-
- new public void Start ()
- {
- SparkleHelpers.DebugInfo ("Cmd", StartInfo.FileName + " " + StartInfo.Arguments);
- base.Start ();
- }
- }
-}
diff --git a/SparkleLib/Hg/SparkleRepoHg.cs b/SparkleLib/Hg/SparkleRepoHg.cs
deleted file mode 100755
index f65c3435..00000000
--- a/SparkleLib/Hg/SparkleRepoHg.cs
+++ /dev/null
@@ -1,487 +0,0 @@
-// SparkleShare, a collaboration and sharing tool.
-// Copyright (C) 2010 Hylke Bons
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program. If not, see .
-
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Text.RegularExpressions;
-
-namespace SparkleLib {
-
- public class SparkleRepoHg : SparkleRepoBase {
-
- private string exlude_rules_file_path;
- private string ExclusionBlock = "#Temporary Exclusions";
-
- public SparkleRepoHg (string path, SparkleBackend backend) :
- base (path, backend) {
- // Set exclude file path
- exlude_rules_file_path = SparkleHelpers.CombineMore (
- LocalPath, ".hg", "hgignore");
- }
-
-
- public override string Identifier {
- get {
- SparkleHg hg = new SparkleHg (LocalPath, "log -r : --limit 1 --template \"{node}\"");
- hg.Start ();
- hg.WaitForExit ();
-
- return hg.StandardOutput.ReadToEnd ();
- }
- }
-
-
- public override string CurrentRevision {
- get {
- SparkleHg hg = new SparkleHg (LocalPath, "log --limit 1 --template \"{node}\"");
- hg.Start ();
- hg.WaitForExit ();
-
- string hash = hg.StandardOutput.ReadToEnd ().Trim ();
- if (hash.Length > 0)
- return hash;
- else
- return null;
- }
- }
-
-
- public override bool CheckForRemoteChanges ()
- {
- return true; // Mercurial doesn't have a way to check for the remote hash
- }
-
-
- public override bool SyncUp ()
- {
- Add ();
-
- string message = FormatCommitMessage ();
- Commit (message);
-
- SparkleHg hg = new SparkleHg (LocalPath, "push");
-
- hg.Start ();
- hg.WaitForExit ();
-
- if (hg.ExitCode == 0) {
- return true;
- } else {
- return false;
- }
- }
-
-
- public override bool SyncDown ()
- {
- SparkleHg hg = new SparkleHg (LocalPath, "pull");
-
- hg.Start ();
- hg.WaitForExit ();
-
- if (hg.ExitCode == 0) {
- Merge ();
- return true;
- } else {
- return false;
- }
- }
-
-
- public override bool AnyDifferences {
- get {
- SparkleHg hg = new SparkleHg (LocalPath, "status");
- hg.Start ();
- hg.WaitForExit ();
-
- string output = hg.StandardOutput.ReadToEnd ().TrimEnd ();
- string [] lines = output.Split ("\n".ToCharArray ());
-
- foreach (string line in lines) {
- if (line.Length > 1 && !line [1].Equals (" "))
- return true;
- }
-
- return false;
- }
- }
-
-
- public override bool HasUnsyncedChanges {
- get {
- string unsynced_file_path = SparkleHelpers.CombineMore (LocalPath,
- ".hg", "has_unsynced_changes");
-
- return File.Exists (unsynced_file_path);
- }
-
- set {
- string unsynced_file_path = SparkleHelpers.CombineMore (LocalPath,
- ".hg", "has_unsynced_changes");
-
- if (value) {
- if (!File.Exists (unsynced_file_path))
- File.Create (unsynced_file_path).Close ();
- } else {
- File.Delete (unsynced_file_path);
- }
- }
- }
-
-
- // Stages the made changes
- private void Add ()
- {
- SparkleHg hg = new SparkleHg (LocalPath, "addremove --quiet");
- hg.Start ();
- hg.WaitForExit ();
-
- SparkleHelpers.DebugInfo ("Hg", "[" + Name + "] Changes staged");
- }
-
- // Add a new file to be ignored
- public override bool AddExclusionRule (FileSystemEventArgs args) {
-
- string RelativePath = SparkleHelpers.DiffPaths(args.FullPath, LocalPath);
-
- List exclusions;
- try {
- exclusions = ReadExclusionRules();
- }
- catch {
- return false;
- }
-
- // Look for the local exclusions section
- bool added = false;
- for(int i = 0; i < exclusions.Count; i++) {
- string entry = exclusions[i];
- if(entry.Equals(ExclusionBlock)) {
- // add a new exclusion rule containing a file path
- exclusions.Insert(i + 1, RelativePath);
- added = true;
- break;
- }
- }
-
- /*
- * For compability to existing repos:
- * Add a "#Temporary Exclusions"-Block to the
- * ignore file in order to recognize this
- * exclude rules later on
- */
- if(!added) {
- exclusions.Add(ExclusionBlock);
- exclusions.Add(RelativePath);
- }
-
- // Write exceptions list back to file
- return WriteExclusionRules(exclusions);
- }
-
- // Check whether a specific rule exists in the exclusion file
- public override bool ExclusionRuleExists(FileSystemEventArgs args) {
- string RelativePath = SparkleHelpers.DiffPaths(args.FullPath, LocalPath);
-
- List exclusions;
- try {
- // Read rules from temporary block only
- exclusions = ReadExclusionRules(true);
-
- foreach(string entry in exclusions) {
- if(entry.Equals(RelativePath)) {
- return true;
- }
- }
- } catch {
- SparkleHelpers.DebugInfo("Error", "Cannot determine whether an exclusion rule for " +
- args.FullPath + " already exists or not.");
- return false;
- }
-
- return false;
- }
-
- // Remove file from exclusion list when they are readable again
- public override bool RemoveExclusionRule(FileSystemEventArgs args) {
- string RelativePath = SparkleHelpers.DiffPaths(args.FullPath, LocalPath);
-
- List exclusions;
- try {
- exclusions = ReadExclusionRules();
-
- /*
- * Removing a rule should only apply to rules in the "Temporary Exclusion"-block.
- * Therefore we first read until reaching the block and then remove the rule.
- *
- * We cannot use ReadExclusionRules(true) here since we write all lines back
- * to the file. This would result in a crippled exclusion file.
- */
- bool BlockReached = false;
- foreach(string entry in exclusions) {
- if(entry.Equals(ExclusionBlock)) {
- BlockReached = true;
- }
-
- // Remove this rule
- if(BlockReached && entry.Equals(RelativePath)) {
- exclusions.Remove(entry);
- break;
- }
- }
-
- return WriteExclusionRules(exclusions);
- } catch {
- SparkleHelpers.DebugInfo("Error", "Unable to remove exclusion rule for entry " + RelativePath);
- return false;
- }
- }
-
- // Reads the exclusion rules file into a string list
- private List ReadExclusionRules() {
-
- List exclusions = new List();
- TextReader reader = new StreamReader (exlude_rules_file_path);;
-
- try {
- while(reader.Peek() > -1) {
- exclusions.Add(reader.ReadLine().TrimEnd());
- }
- }
- catch (IOException e) {
- SparkleHelpers.DebugInfo("Error", "Reading from exclusion file failed: " + e.Message);
- return new List();
- }
- finally {
- if(reader != null) {
- reader.Close();
- }
- }
-
- return exclusions;
- }
-
- // Reads rules only from temporary exclusion block
- private List ReadExclusionRules(bool TempOnly) {
- if(TempOnly) {
- bool ForceRead = false;
- List exclusions = new List();
- foreach(string entry in ReadExclusionRules()) {
- if(ForceRead || entry.Equals(ExclusionBlock)) {
- exclusions.Add(entry);
- ForceRead = true;
- }
- }
-
- return exclusions;
- }
-
- return ReadExclusionRules();
- }
-
- // Writes the exclusion rules file with a given string list
- private bool WriteExclusionRules(List lines) {
-
- TextWriter writer = new StreamWriter (exlude_rules_file_path);
-
- try {
- foreach(string line in lines) {
- writer.WriteLine(line.TrimEnd());
- }
- } catch(IOException e) {
- SparkleHelpers.DebugInfo("Error", "Writing into exclusion file failed: " + e.Message);
- return false;
- }
- finally {
- if(writer != null) {
- writer.Close();
- }
- }
-
- return true;
- }
-
- // Commits the made changes
- private void Commit (string message)
- {
- if (!AnyDifferences)
- return;
-
- SparkleHg hg = new SparkleHg (LocalPath, "commit -m '" + message + "'");
- hg.Start ();
- hg.WaitForExit ();
-
- SparkleHelpers.DebugInfo ("Commit", "[" + Name + "] " + message);
- }
-
-
- // Merges the fetched changes
- private void Merge ()
- {
- DisableWatching ();
-
- if (AnyDifferences) {
- Add ();
-
- string commit_message = FormatCommitMessage ();
- Commit (commit_message);
- }
-
- SparkleHg hg = new SparkleHg (LocalPath, "update");
-
- hg.Start ();
- hg.WaitForExit ();
-
- EnableWatching ();
- }
-
-
- // Returns a list of the latest change sets
- public override List GetChangeSets (int count)
- {
- if (count < 1)
- count = 30;
-
- List change_sets = new List ();
-
- SparkleHg hg_log = new SparkleHg (LocalPath, "log --limit " + count + " --style changelog --verbose --stat");
- Console.OutputEncoding = System.Text.Encoding.Unicode;
- hg_log.Start ();
-
- // Reading the standard output HAS to go before
- // WaitForExit, or it will hang forever on output > 4096 bytes
- string output = hg_log.StandardOutput.ReadToEnd ();
- hg_log.WaitForExit ();
-
- string [] lines = output.Split ("\n".ToCharArray ());
- List entries = new List ();
-
- int j = 0;
- string entry = "", last_entry = "";
- foreach (string line in lines) {
- if (line.StartsWith ("2") && line.EndsWith (")") && j > 0) {
- entries.Add (entry);
- entry = "";
- }
-
- entry += line + "\n";
- j++;
-
- last_entry = entry;
- }
-
- entries.Add (last_entry);
-
- Regex regex = new Regex (@"([0-9]{4})-([0-9]{2})-([0-9]{2}).*([0-9]{2}):([0-9]{2}).*.([0-9]{4})" +
- "(.+)<(.+)>.*.([a-z0-9]{12})", RegexOptions.Compiled);
-
- foreach (string log_entry in entries) {
-
- bool is_merge_commit = false;
-
- Match match = regex.Match (log_entry);
-
- if (!match.Success)
- continue;
-
- SparkleChangeSet change_set = new SparkleChangeSet () {
- Revision = match.Groups [9].Value,
- IsMagical = is_merge_commit
- };
-
- change_set.User.Name = match.Groups [7].Value.Trim ();
- change_set.User.Email = match.Groups [8].Value;
-
-
- change_set.Timestamp = new DateTime (int.Parse (match.Groups [1].Value),
- int.Parse (match.Groups [2].Value), int.Parse (match.Groups [3].Value),
- int.Parse (match.Groups [4].Value), int.Parse (match.Groups [5].Value), 0);
-
- string [] entry_lines = log_entry.Split ("\n".ToCharArray ());
-
- foreach (string entry_line in entry_lines) {
- if (!entry_line.StartsWith ("\t* "))
- continue;
-
- if (entry_line.EndsWith ("new file.")) {
- string files = entry_line.Substring (3, entry_line.Length - 13);
- string [] added_files = files.Split (",".ToCharArray ());
-
- foreach (string added_file in added_files) {
- string file = added_file.TrimEnd (": ".ToCharArray ());
- change_set.Added.Add (file);
- }
-
- } else if (entry_line.EndsWith ("deleted file.")) {
- string files = entry_line.Substring (3, entry_line.Length - 17);
- string [] deleted_files = files.Split (",".ToCharArray ());
-
- foreach (string deleted_file in deleted_files) {
- string file = deleted_file.TrimEnd (": ".ToCharArray ());
- change_set.Deleted.Add (file);
- }
-
- } else if (!"".Equals (entry_line.Trim ())){
- string files = entry_line.Substring (3);
- files = files.TrimEnd (":".ToCharArray());
- string [] edited_files = files.Split (",".ToCharArray ());
-
- foreach (string edited_file in edited_files) {
- if (!change_set.Added.Contains (edited_file) &&
- !change_set.Deleted.Contains (edited_file)) {
-
- change_set.Edited.Add (edited_file);
- }
- }
- }
- }
-
- change_sets.Add (change_set);
- }
-
- return change_sets;
- }
-
-
- // Creates a pretty commit message based on what has changed
- private string FormatCommitMessage () // TODO
- {
- return "SparkleShare Hg";
- }
-
-
- public override void CreateInitialChangeSet ()
- {
- base.CreateInitialChangeSet ();
- Add ();
-
- string message = FormatCommitMessage ();
- Commit (message);
- }
-
-
- public override bool UsesNotificationCenter
- {
- get {
- string file_path = SparkleHelpers.CombineMore (LocalPath, ".hg", "disable_notification_center");
- return !File.Exists (file_path);
- }
- }
- }
-}
diff --git a/SparkleLib/Makefile.am b/SparkleLib/Makefile.am
index 6356372a..b696aa1b 100755
--- a/SparkleLib/Makefile.am
+++ b/SparkleLib/Makefile.am
@@ -1,12 +1,6 @@
ASSEMBLY = SparkleLib
TARGET = library
-if HAVE_SMARTIRC4NET
-LINK = $(REF_SPARKLELIB) $(LINK_SMARTIRC4NET_SYSTEM)
-else
-LINK = $(REF_SPARKLELIB) $(LINK_SMARTIRC4NET_LOCAL)
-endif
-
SOURCES = \
Defines.cs \
Git/SparkleFetcherGit.cs \
@@ -17,17 +11,11 @@ SOURCES = \
SparkleFetcherBase.cs \
SparkleHelpers.cs \
SparkleListenerBase.cs \
- SparkleListenerIrc.cs \
SparkleListenerTcp.cs \
- SparkleOptions.cs \
SparkleRepoBase.cs \
SparkleWatcher.cs
-SMARTIRC4NET_FILES_EXPANDED = $(foreach file, $(SMARTIRC4NET_FILES), $(top_builddir)/$(file))
-
-EXTRA_BUNDLE = $(SMARTIRC4NET_FILES_EXPANDED)
-
install-data-hook:
for ASM in $(EXTRA_BUNDLE); do \
$(INSTALL) -m 0755 $$ASM $(DESTDIR)$(moduledir); \
diff --git a/SparkleLib/SparkleChangeSet.cs b/SparkleLib/SparkleChangeSet.cs
index 5496e44e..a24faaaa 100755
--- a/SparkleLib/SparkleChangeSet.cs
+++ b/SparkleLib/SparkleChangeSet.cs
@@ -102,7 +102,7 @@ namespace SparkleLib {
public class SparkleFolder {
public string Name;
- // TODO: Uri
+ public Uri RemoteAddress;
public string FullPath {
get {
diff --git a/SparkleLib/SparkleConfig.cs b/SparkleLib/SparkleConfig.cs
index 1fd3fece..f9f57548 100755
--- a/SparkleLib/SparkleConfig.cs
+++ b/SparkleLib/SparkleConfig.cs
@@ -19,10 +19,7 @@ using System;
using System.IO;
using System.Collections.Generic;
using System.Xml;
-
-#if __MonoCS__
-using Mono.Unix;
-#endif
+using System.Security.Principal;
namespace SparkleLib {
@@ -33,12 +30,14 @@ namespace SparkleLib {
"sparkleshare");
public static SparkleConfig DefaultConfig = new SparkleConfig (ConfigPath, "config.xml");
-
-
public string FullPath;
- public string HomePath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
- public string TmpPath;
+ public string HomePath {
+ get {
+ return Environment.GetFolderPath (Environment.SpecialFolder.Personal);
+ }
+ }
+
public string FoldersPath {
get {
@@ -49,11 +48,16 @@ namespace SparkleLib {
}
}
+ public string TmpPath {
+ get {
+ return Path.Combine (FoldersPath, ".tmp");
+ }
+ }
+
public SparkleConfig (string config_path, string config_file_name)
{
FullPath = System.IO.Path.Combine (config_path, config_file_name);
- TmpPath = Path.Combine (FoldersPath, ".tmp");
if (!Directory.Exists (config_path)) {
Directory.CreateDirectory (config_path);
@@ -99,13 +103,13 @@ namespace SparkleLib {
if (SparkleBackend.Platform == PlatformID.Unix ||
SparkleBackend.Platform == PlatformID.MacOSX) {
-#if __MonoCS__
- user_name = new UnixUserInfo (UnixEnvironment.UserName).RealName;
+
+ user_name = Environment.UserName;
if (string.IsNullOrEmpty (user_name))
- user_name = UnixEnvironment.UserName;
+ user_name = "";
else
- user_name = user_name.TrimEnd (",".ToCharArray());
-#endif
+ user_name = user_name.TrimEnd (",".ToCharArray ());
+
} else {
user_name = Environment.UserName;
}
@@ -148,10 +152,59 @@ namespace SparkleLib {
email_node.InnerText = user.Email;
this.Save ();
+
+ ConfigureSSH ();
}
}
+ private void ConfigureSSH ()
+ {
+ if (User.Email.Equals ("Unknown"))
+ return;
+
+ string path = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
+
+ if (!(SparkleBackend.Platform == PlatformID.Unix ||
+ SparkleBackend.Platform == PlatformID.MacOSX)) {
+
+ path = Environment.ExpandEnvironmentVariables ("%HOMEDRIVE%%HOMEPATH%");
+ }
+
+ string ssh_config_path = Path.Combine (path, ".ssh");
+ string ssh_config_file_path = SparkleHelpers.CombineMore (path, ".ssh", "config");
+ string ssh_config = "IdentityFile " +
+ Path.Combine (SparkleConfig.ConfigPath, "sparkleshare." + User.Email + ".key");
+
+ if (!Directory.Exists (ssh_config_path))
+ Directory.CreateDirectory (ssh_config_path);
+
+ if (File.Exists (ssh_config_file_path)) {
+ string current_config = File.ReadAllText (ssh_config_file_path);
+ if (current_config.Contains (ssh_config))
+ return;
+
+ if (current_config.EndsWith ("\n\n"))
+ ssh_config = "# SparkleShare's key\n" + ssh_config;
+ else if (current_config.EndsWith ("\n"))
+ ssh_config = "\n# SparkleShare's key\n" + ssh_config;
+ else
+ ssh_config = "\n\n# SparkleShare's key\n" + ssh_config;
+
+ TextWriter writer = File.AppendText (ssh_config_file_path);
+ writer.Write (ssh_config + "\n");
+ writer.Close ();
+
+ } else {
+ File.WriteAllText (ssh_config_file_path, ssh_config);
+ }
+
+ Chmod644 (ssh_config_file_path);
+
+ SparkleHelpers.DebugInfo ("Config", "Added key to " + ssh_config_file_path);
+ }
+
+
public List Folders {
get {
List folders = new List ();
@@ -348,6 +401,16 @@ namespace SparkleLib {
this.Save (FullPath);
SparkleHelpers.DebugInfo ("Config", "Updated \"" + FullPath + "\"");
}
+
+
+ private void Chmod644 (string file_path)
+ {
+ // Hack to be able to set the permissions on a file
+ // that OpenSSH still likes without resorting to Mono.Unix
+ FileInfo file_info = new FileInfo (file_path);
+ file_info.Attributes = FileAttributes.ReadOnly;
+ file_info.Attributes = FileAttributes.Normal;
+ }
}
diff --git a/SparkleLib/SparkleFetcherBase.cs b/SparkleLib/SparkleFetcherBase.cs
index 0ab93307..da69976d 100755
--- a/SparkleLib/SparkleFetcherBase.cs
+++ b/SparkleLib/SparkleFetcherBase.cs
@@ -18,20 +18,17 @@
using System;
using System.IO;
using System.Diagnostics;
+using System.Security.AccessControl;
using System.Text.RegularExpressions;
using System.Threading;
-#if __MonoCS__
-using Mono.Unix;
-#endif
-
namespace SparkleLib {
// Sets up a fetcher that can get remote folders
public abstract class SparkleFetcherBase {
public delegate void StartedEventHandler ();
- public delegate void FinishedEventHandler ();
+ public delegate void FinishedEventHandler (string [] warnings);
public delegate void FailedEventHandler ();
public delegate void ProgressChangedEventHandler (double percentage);
@@ -54,7 +51,7 @@ namespace SparkleLib {
public abstract bool Fetch ();
-
+ public abstract string [] Warnings { get; }
// Clones the remote repository
public void Start ()
@@ -85,7 +82,7 @@ namespace SparkleLib {
EnableHostKeyCheckingForHost (host);
if (Finished != null)
- Finished ();
+ Finished (Warnings);
} else {
SparkleHelpers.DebugInfo ("Fetcher", "Failed");
@@ -159,13 +156,8 @@ namespace SparkleLib {
File.WriteAllText (ssh_config_file_path, ssh_config);
}
-#if __MonoCS__
- UnixFileSystemInfo file_info = new UnixFileInfo (ssh_config_file_path);
- file_info.FileAccessPermissions = (FileAccessPermissions.UserRead |
- FileAccessPermissions.UserWrite);
-#endif
-
- SparkleHelpers.DebugInfo ("Fetcher", "Disabled host key checking " + host);
+ Chmod644 (ssh_config_file_path);
+ SparkleHelpers.DebugInfo ("Fetcher", "Disabled host key checking for " + host);
}
@@ -173,8 +165,8 @@ namespace SparkleLib {
{
string path = SparkleConfig.DefaultConfig.HomePath;
- if (!(SparkleBackend.Platform == PlatformID.Unix ||
- SparkleBackend.Platform == PlatformID.MacOSX)) {
+ if (SparkleBackend.Platform != PlatformID.Unix &&
+ SparkleBackend.Platform != PlatformID.MacOSX) {
path = Environment.ExpandEnvironmentVariables ("%HOMEDRIVE%%HOMEPATH%");
}
@@ -211,12 +203,7 @@ namespace SparkleLib {
} else {
File.WriteAllText (ssh_config_file_path, new_ssh_config.Trim ());
-
-#if __MonoCS__
- UnixFileSystemInfo file_info = new UnixFileInfo (ssh_config_file_path);
- file_info.FileAccessPermissions = (FileAccessPermissions.UserRead |
- FileAccessPermissions.UserWrite);
-#endif
+ Chmod644 (ssh_config_file_path);
}
}
@@ -234,5 +221,15 @@ namespace SparkleLib {
else
return null;
}
+
+
+ private void Chmod644 (string file_path)
+ {
+ // Hack to be able to set the permissions on a file
+ // that OpenSSH still likes without resorting to Mono.Unix
+ FileInfo file_info = new FileInfo (file_path);
+ file_info.Attributes = FileAttributes.ReadOnly;
+ file_info.Attributes = FileAttributes.Normal;
+ }
}
}
diff --git a/SparkleLib/SparkleLib.csproj b/SparkleLib/SparkleLib.csproj
index 8e18cd24..a0ac9494 100755
--- a/SparkleLib/SparkleLib.csproj
+++ b/SparkleLib/SparkleLib.csproj
@@ -31,10 +31,6 @@
-
- False
- ..\bin\Meebey.SmartIrc4net.dll
-
diff --git a/SparkleLib/SparkleListenerBase.cs b/SparkleLib/SparkleListenerBase.cs
index bba5b171..1770c04a 100755
--- a/SparkleLib/SparkleListenerBase.cs
+++ b/SparkleLib/SparkleListenerBase.cs
@@ -75,9 +75,6 @@ namespace SparkleLib {
case "tcp":
listeners.Add (new SparkleListenerTcp (announce_uri, folder_identifier));
break;
- case "irc":
- listeners.Add (new SparkleListenerIrc (announce_uri, folder_identifier));
- break;
default:
listeners.Add (new SparkleListenerTcp (announce_uri, folder_identifier));
break;
diff --git a/SparkleLib/SparkleListenerIrc.cs b/SparkleLib/SparkleListenerIrc.cs
deleted file mode 100644
index ff8821fe..00000000
--- a/SparkleLib/SparkleListenerIrc.cs
+++ /dev/null
@@ -1,221 +0,0 @@
-// SparkleShare, a collaboration and sharing tool.
-// Copyright (C) 2010 Hylke Bons
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program. If not, see .
-
-
-using System;
-using System.Text;
-using System.Threading;
-using System.Security.Cryptography;
-
-using Meebey.SmartIrc4net;
-
-namespace SparkleLib {
-
- public class SparkleListenerIrc : SparkleListenerBase {
-
- private Thread thread;
- private IrcClient client;
- private string nick;
- private string announcements_password;
- private bool allow_passwordless_join;
-
-
- public SparkleListenerIrc (Uri server, string folder_identifier) :
- base (server, folder_identifier)
- {
- // Try to get a uniqueish nickname
- this.nick = SHA1 (DateTime.Now.ToString ("ffffff") + "sparkles");
-
- // Most irc servers don't allow nicknames starting
- // with a number, so prefix an alphabetic character
- this.nick = "s" + this.nick.Substring (0, 7);
-
- // Optional password to make the channel access more safe
- this.announcements_password =
- SparkleConfig.DefaultConfig.GetConfigOption ("announcements_password");
-
- // Option to allow access to channel when no password is defined
- try {
- string option = SparkleConfig.DefaultConfig.GetConfigOption ("allow_passwordless_join");
- this.allow_passwordless_join = (option == null || Convert.ToBoolean (option));
- } catch (Exception) {
- this.allow_passwordless_join = true;
- }
-
- base.channels.Add ("#" + folder_identifier);
-
- this.client = new IrcClient () {
- PingTimeout = 180,
- PingInterval = 60
- };
-
- string proxy = Environment.GetEnvironmentVariable ("http_proxy");
- Uri proxy_uri = null;
- if (!String.IsNullOrEmpty (proxy) &&
- Uri.TryCreate (proxy, UriKind.Absolute, out proxy_uri)) {
-
-#if __MonoCS__
- if (proxy_uri.Scheme == "http") {
- this.client.ProxyType = ProxyType.Http;
- this.client.ProxyHost = proxy_uri.Host;
- this.client.ProxyPort = proxy_uri.Port;
- }
-#endif
- }
-
- this.client.OnConnected += delegate {
- base.is_connecting = false;
- OnConnected ();
- };
-
- this.client.OnDisconnected += delegate {
- base.is_connecting = false;
- OnDisconnected ();
- };
-
- this.client.OnError += delegate {
- base.is_connecting = false;
- OnDisconnected ();
- };
-
- this.client.OnChannelMessage += delegate (object o, IrcEventArgs args) {
- string message = args.Data.Message.Trim ();
- string folder_id = args.Data.Channel.Substring (1); // remove the starting hash
- OnAnnouncement (new SparkleAnnouncement (folder_id, message));
- };
- }
-
-
- public override bool IsConnected {
- get {
- return this.client.IsConnected;
- }
- }
-
-
- // Starts a new thread and listens to the channel
- public override void Connect ()
- {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Connecting to " + Server);
-
- base.is_connecting = true;
-
- this.thread = new Thread (
- new ThreadStart (delegate {
- try {
- // Connect, login, and join the channel
- int port = base.server.Port;
-
- if (port < 0)
- port = 6667;
-
- this.client.Connect (base.server.Host, port);
- this.client.Login (this.nick, this.nick, 8, this.nick);
-
- foreach (string channel in base.channels) {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Joining channel " + channel);
-
- if (!string.IsNullOrEmpty (this.announcements_password)) {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Password set to access the channel");
- this.client.RfcJoin (channel, this.announcements_password);
- this.client.RfcMode (channel, "+k " + this.announcements_password);
-
- } else {
- if (this.allow_passwordless_join) {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Accessing unprotected channel, change the setting to not access");
- this.client.RfcJoin (channel);
-
- } else {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Unprotected channel, change the setting to access");
- base.is_connecting = false;
- OnDisconnected ();
- throw new ConnectionException ("Unprotected channel, change the setting to access");
- }
- }
-
- this.client.RfcMode (channel, "+s");
- }
-
- // List to the channel, this blocks the thread
- this.client.Listen ();
-
- // Disconnect when we time out
- this.client.Disconnect ();
-
- } catch (ConnectionException e) {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Could not connect to " + Server + ": " + e.Message);
- }
- })
- );
-
- this.thread.Start ();
- }
-
-
- public override void AlsoListenTo (string folder_identifier)
- {
- string channel = "#" + folder_identifier;
- if (!base.channels.Contains (channel)) {
- base.channels.Add (channel);
-
- if (IsConnected) {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Joining channel " + channel);
- if (this.announcements_password != null) {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Password set to access the channel");
- this.client.RfcJoin (channel, this.announcements_password);
- this.client.RfcMode (channel, "+k " + this.announcements_password);
- } else {
- if (allow_passwordless_join) {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Accessing a dangerous channel change the setting to not access");
- this.client.RfcJoin (channel);
- } else {
- SparkleHelpers.DebugInfo ("ListenerIrc", "Dangerous channel, change the setting to access");
- }
- }
- this.client.RfcMode (channel, "+s");
- }
- }
- }
-
-
- public override void Announce (SparkleAnnouncement announcement)
- {
- string channel = "#" + announcement.FolderIdentifier;
- this.client.SendMessage (SendType.Message, channel, announcement.Message);
-
- // Also announce to ourselves for debugging purposes
- // base.OnAnnouncement (announcement);
- }
-
-
- public override void Dispose ()
- {
- this.thread.Abort ();
- this.thread.Join ();
- base.Dispose ();
- }
-
-
- // Creates a SHA-1 hash of input
- private string SHA1 (string s)
- {
- SHA1 sha1 = new SHA1CryptoServiceProvider ();
- Byte[] bytes = ASCIIEncoding.Default.GetBytes (s);
- Byte[] encoded_bytes = sha1.ComputeHash (bytes);
- return BitConverter.ToString (encoded_bytes).ToLower ().Replace ("-", "");
- }
- }
-}
diff --git a/SparkleLib/SparklePath.cs b/SparkleLib/SparklePath.cs
deleted file mode 100644
index 6529008a..00000000
--- a/SparkleLib/SparklePath.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// SparkleShare, a collaboration and sharing tool.
-// Copyright (C) 2010 Hylke Bons
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program. If not, see .
-
-
-using System;
-using System.IO;
-
-namespace SparkleLib {
-
- public static class SparklePaths {
-
- public static string HomePath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
- public static string SparklePath = Path.Combine (HomePath ,"SparkleShare");
- public static string SparkleTmpPath = Path.Combine (SparklePath, ".tmp");
- public static string SparkleConfigPath = Path.Combine (Environment.GetFolderPath (
- Environment.SpecialFolder.ApplicationData), "sparkleshare");
- public static string SparkleLocalIconPath = Path.Combine (SparkleConfigPath, "icons");
-
- public static string SparkleInstallPath = Path.Combine (Defines.PREFIX, "sparkleshare");
- public static string SparkleIconPath = SparkleHelpers.CombineMore (Defines.DATAROOTDIR, "sparkleshare", "icons");
-
- }
-}
-
diff --git a/SparkleLib/SparkleRepoBase.cs b/SparkleLib/SparkleRepoBase.cs
index 86aa8779..05fad586 100755
--- a/SparkleLib/SparkleRepoBase.cs
+++ b/SparkleLib/SparkleRepoBase.cs
@@ -44,11 +44,13 @@ namespace SparkleLib {
private TimeSpan poll_interval;
private System.Timers.Timer local_timer = new System.Timers.Timer () { Interval = 0.25 * 1000 };
private System.Timers.Timer remote_timer = new System.Timers.Timer () { Interval = 10 * 1000 };
- private DateTime last_poll = DateTime.Now;
- private List sizebuffer = new List ();
- private bool has_changed = false;
- private Object change_lock = new Object ();
- private Object watch_lock = new Object ();
+ private DateTime last_poll = DateTime.Now;
+ private List sizebuffer = new List ();
+ private bool has_changed = false;
+ private Object change_lock = new Object ();
+ private Object watch_lock = new Object ();
+ private double progress_percentage = 0.0;
+ private string progress_speed = "";
protected SparkleListenerBase listener;
protected SyncStatus status;
@@ -64,19 +66,23 @@ namespace SparkleLib {
public abstract string CurrentRevision { get; }
public abstract bool SyncUp ();
public abstract bool SyncDown ();
+ public abstract double CalculateSize (DirectoryInfo parent);
public abstract bool HasUnsyncedChanges { get; set; }
+ public abstract List ExcludePaths { get; }
+
+ public abstract double Size { get; }
+ public abstract double HistorySize { get; }
- public abstract bool AddExclusionRule (FileSystemEventArgs args);
- public abstract bool RemoveExclusionRule (FileSystemEventArgs args);
- public abstract bool ExclusionRuleExists (FileSystemEventArgs args);
-
public delegate void SyncStatusChangedEventHandler (SyncStatus new_status);
public event SyncStatusChangedEventHandler SyncStatusChanged;
+ public delegate void SyncProgressChangedEventHandler (double percentage, string speed);
+ public event SyncProgressChangedEventHandler SyncProgressChanged;
+
public delegate void NewChangeSetEventHandler (SparkleChangeSet change_set);
public event NewChangeSetEventHandler NewChangeSet;
- public delegate void NewNoteEventHandler (string user_name, string user_email);
+ public delegate void NewNoteEventHandler (SparkleUser user);
public event NewNoteEventHandler NewNote;
public delegate void ConflictResolvedEventHandler ();
@@ -108,8 +114,6 @@ namespace SparkleLib {
};
this.remote_timer.Elapsed += delegate {
- string identifier = Identifier;
-
bool time_to_poll = (DateTime.Compare (this.last_poll,
DateTime.Now.Subtract (this.poll_interval)) < 0);
@@ -122,7 +126,7 @@ namespace SparkleLib {
// In the unlikely case that we haven't synced up our
// changes or the server was down, sync up again
- if (HasUnsyncedChanges)
+ if (HasUnsyncedChanges && !IsSyncing && this.server_online)
SyncUpBase ();
};
@@ -157,6 +161,20 @@ namespace SparkleLib {
}
+ public double ProgressPercentage {
+ get {
+ return this.progress_percentage;
+ }
+ }
+
+
+ public string ProgressSpeed {
+ get {
+ return this.progress_speed;
+ }
+ }
+
+
public virtual string [] UnsyncedFilePaths {
get {
return new string [0];
@@ -186,7 +204,7 @@ namespace SparkleLib {
}
- public virtual bool CheckForRemoteChanges () // HasRemoteChanges { get; } ?
+ public virtual bool CheckForRemoteChanges () // TODO: HasRemoteChanges { get; }
{
return true;
}
@@ -223,11 +241,8 @@ namespace SparkleLib {
public void Dispose ()
{
this.remote_timer.Dispose ();
- this.remote_timer = null;
this.local_timer.Dispose ();
- this.local_timer = null;
this.listener.Dispose ();
- this.listener = null;
}
@@ -301,7 +316,7 @@ namespace SparkleLib {
}
- private bool IsSyncing {
+ public bool IsSyncing {
get {
return (Status == SyncStatus.SyncUp ||
Status == SyncStatus.SyncDown ||
@@ -318,7 +333,7 @@ namespace SparkleLib {
this.sizebuffer.RemoveAt (0);
DirectoryInfo dir_info = new DirectoryInfo (LocalPath);
- this.sizebuffer.Add (CalculateFolderSize (dir_info));
+ this.sizebuffer.Add (CalculateSize (dir_info));
if (this.sizebuffer.Count >= 4 &&
this.sizebuffer [0].Equals (this.sizebuffer [1]) &&
@@ -347,42 +362,13 @@ namespace SparkleLib {
if (!this.watcher.EnableRaisingEvents)
return;
- if (args.FullPath.Contains (Path.DirectorySeparatorChar + ".") &&
- !args.FullPath.Contains (Path.DirectorySeparatorChar + ".notes"))
- return;
+ string relative_path = args.FullPath.Replace (LocalPath, "");
- /*
- * Check whether the file which triggered the action
- * is readable so that git can actually commit it
- */
- try {
- if(File.Exists(args.FullPath)) {
- FileStream file = File.OpenRead(args.FullPath);
- file.Close();
- }
- } catch {
- if(!ExclusionRuleExists(args)) {
- SparkleHelpers.DebugInfo("Warning", "File " + args.FullPath + " is not readable. Adding to ignore list.");
- AddExclusionRule(args);
- }
-
- return;
- }
-
- /*
- * Remove rule if file is readable but there is still
- * an exclusion rule set
- */
- if(ExclusionRuleExists(args)) {
- SparkleHelpers.DebugInfo("Info", "Removing exclusion rule for " + args.Name);
- RemoveExclusionRule(args);
-
- // If a file was former unreadable but has now been (re)moved, skip the process.
- if(!File.Exists(args.FullPath)) {
+ foreach (string exclude_path in ExcludePaths) {
+ if (relative_path.Contains (exclude_path))
return;
- }
}
-
+
WatcherChangeTypes wct = args.ChangeType;
if (AnyDifferences) {
@@ -402,8 +388,7 @@ namespace SparkleLib {
SparkleHelpers.DebugInfo ("Event", "[" + Name + "] " + wct.ToString () + " '" + args.Name + "'");
SparkleHelpers.DebugInfo ("Event", "[" + Name + "] Changes found, checking if settled.");
- if (this.remote_timer != null)
- this.remote_timer.Stop ();
+ this.remote_timer.Stop ();
lock (this.change_lock) {
this.has_changed = true;
@@ -452,8 +437,7 @@ namespace SparkleLib {
{
try {
DisableWatching ();
- if (this.remote_timer != null)
- this.remote_timer.Stop ();
+ this.remote_timer.Stop ();
SparkleHelpers.DebugInfo ("SyncUp", "[" + Name + "] Initiated");
@@ -468,34 +452,37 @@ namespace SparkleLib {
if (SyncStatusChanged != null)
SyncStatusChanged (SyncStatus.Idle);
- if (this.listener != null)
- this.listener.AnnounceBase (new SparkleAnnouncement(Identifier, CurrentRevision));
+ this.listener.AnnounceBase (new SparkleAnnouncement (Identifier, CurrentRevision));
} else {
SparkleHelpers.DebugInfo ("SyncUp", "[" + Name + "] Error");
HasUnsyncedChanges = true;
SyncDownBase ();
+ DisableWatching ();
- if (SyncUp ()) {
+ if (this.server_online && SyncUp ()) {
HasUnsyncedChanges = false;
if (SyncStatusChanged != null)
SyncStatusChanged (SyncStatus.Idle);
- if (this.listener != null)
- this.listener.AnnounceBase (new SparkleAnnouncement (Identifier, CurrentRevision));
+ this.listener.AnnounceBase (new SparkleAnnouncement (Identifier, CurrentRevision));
} else {
+ this.server_online = false;
+
if (SyncStatusChanged != null)
SyncStatusChanged (SyncStatus.Error);
}
}
} finally {
- if (this.remote_timer != null)
- this.remote_timer.Start ();
+ this.remote_timer.Start ();
EnableWatching ();
+
+ this.progress_percentage = 0.0;
+ this.progress_speed = "";
}
}
@@ -503,8 +490,7 @@ namespace SparkleLib {
private void SyncDownBase ()
{
SparkleHelpers.DebugInfo ("SyncDown", "[" + Name + "] Initiated");
- if (this.remote_timer != null)
- this.remote_timer.Stop ();
+ this.remote_timer.Stop ();
DisableWatching ();
if (SyncStatusChanged != null)
@@ -529,7 +515,7 @@ namespace SparkleLib {
foreach (string added in change_set.Added) {
if (added.Contains (".notes")) {
if (NewNote != null)
- NewNote (change_set.User.Name, change_set.User.Email);
+ NewNote (change_set.User);
note_added = true;
break;
@@ -560,28 +546,28 @@ namespace SparkleLib {
if (SyncStatusChanged != null)
SyncStatusChanged (SyncStatus.Idle);
- if (this.remote_timer != null)
- this.remote_timer.Start ();
+ this.remote_timer.Start ();
EnableWatching ();
+
+ this.progress_percentage = 0.0;
+ this.progress_speed = "";
}
public void DisableWatching ()
{
- lock (watch_lock) {
+ lock (this.watch_lock) {
this.watcher.EnableRaisingEvents = false;
- if (this.local_timer != null)
- this.local_timer.Stop ();
+ this.local_timer.Stop ();
}
}
public void EnableWatching ()
{
- lock (watch_lock) {
+ lock (this.watch_lock) {
this.watcher.EnableRaisingEvents = true;
- if (this.local_timer != null)
- this.local_timer.Start ();
+ this.local_timer.Start ();
}
}
@@ -635,30 +621,15 @@ namespace SparkleLib {
}
- // Recursively gets a folder's size in bytes
- private double CalculateFolderSize (DirectoryInfo parent)
+ protected void OnSyncProgressChanged (double progress_percentage, string progress_speed)
{
- if (!System.IO.Directory.Exists (parent.ToString ()))
- return 0;
+ // Console.WriteLine ("OnProgressChanged: " + progress_percentage + " " + progress_speed);
- double size = 0;
+ this.progress_percentage = progress_percentage;
+ this.progress_speed = progress_speed;
- // Ignore the temporary 'rebase-apply' directory. This prevents potential
- // crashes when files are being queried whilst the files have already been deleted.
- if (parent.Name.Equals ("rebase-apply"))
- return 0;
-
- foreach (FileInfo file in parent.GetFiles ()) {
- if (!file.Exists)
- return 0;
-
- size += file.Length;
- }
-
- foreach (DirectoryInfo directory in parent.GetDirectories())
- size += CalculateFolderSize (directory);
-
- return size;
+ if (SyncProgressChanged != null)
+ SyncProgressChanged (progress_percentage, progress_speed);
}
diff --git a/SparkleLib/SparkleWatcher.cs b/SparkleLib/SparkleWatcher.cs
index ae0ec573..f1c477fd 100755
--- a/SparkleLib/SparkleWatcher.cs
+++ b/SparkleLib/SparkleWatcher.cs
@@ -51,7 +51,6 @@ namespace SparkleLib {
if (ChangeEvent != null)
ChangeEvent (args);
};
-
}
}
}
diff --git a/SparkleShare/Mac/Info.plist b/SparkleShare/Mac/Info.plist
index 97d1ab96..4867455e 100755
--- a/SparkleShare/Mac/Info.plist
+++ b/SparkleShare/Mac/Info.plist
@@ -8,9 +8,11 @@
org.sparkleshare.sparkleshare
CFBundleName
SparkleShare
+ CFBundleVersion
+ 1
LSMinimumSystemVersion
10.6
- CFBundleVersion
+ LSUIElement
1
NSMainNibFile
MainMenu
diff --git a/SparkleShare/Mac/Makefile.am b/SparkleShare/Mac/Makefile.am
index c7df923a..6beab296 100755
--- a/SparkleShare/Mac/Makefile.am
+++ b/SparkleShare/Mac/Makefile.am
@@ -6,7 +6,6 @@ EXTRA_DIST = \
MainMenu.xib \
MainMenu.xib.designer.cs \
SparkleAbout.cs \
- SparkleAlert.cs \
SparkleBadger.cs \
SparkleBubbles.cs \
SparkleController.cs \
diff --git a/SparkleShare/Mac/SparkleAbout.cs b/SparkleShare/Mac/SparkleAbout.cs
index 64a3fc93..27d5715b 100755
--- a/SparkleShare/Mac/SparkleAbout.cs
+++ b/SparkleShare/Mac/SparkleAbout.cs
@@ -57,6 +57,8 @@ namespace SparkleShare {
OrderFrontRegardless ();
MakeKeyAndOrderFront (this);
+ Program.UI.UpdateDockIconVisibility ();
+
Controller.NewVersionEvent += delegate (string new_version) {
InvokeOnMainThread (delegate {
UpdatesTextField.StringValue = "A newer version (" + new_version + ") is available!";
@@ -161,6 +163,8 @@ namespace SparkleShare {
public override bool WindowShouldClose (NSObject sender)
{
(sender as SparkleAbout).OrderOut (this);
+ Program.UI.UpdateDockIconVisibility ();
+
return false;
}
}
diff --git a/SparkleShare/Mac/SparkleAlert.cs b/SparkleShare/Mac/SparkleAlert.cs
deleted file mode 100755
index c74d3600..00000000
--- a/SparkleShare/Mac/SparkleAlert.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-// SparkleShare, a collaboration and sharing tool.
-// Copyright (C) 2010 Hylke Bons
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program. If not, see .
-
-
-using System;
-using System.Collections.Generic;
-using System.Drawing;
-using System.IO;
-
-using MonoMac.Foundation;
-using MonoMac.AppKit;
-using MonoMac.ObjCRuntime;
-using MonoMac.WebKit;
-
-namespace SparkleShare {
-
- public class SparkleAlert : NSAlert {
-
- public SparkleAlert () : base ()
- {
- MessageText = "SparkleShare couldn't find Git on your system. Do you want to download it?";
- InformativeText = "Git is required to run SparkleShare.";
-
- Icon = NSImage.ImageNamed ("sparkleshare.icns");
-
- AddButton ("Download");
- AddButton ("Cancel");
-
- Buttons [0].Activated += delegate {
- NSUrl url = new NSUrl ("http://code.google.com/p/git-osx-installer/downloads/list");
- NSWorkspace.SharedWorkspace.OpenUrl (url);
- Environment.Exit (0);
- };
-
- Buttons [1].Activated += delegate {
- Environment.Exit (-1);
- };
- }
- }
-}
diff --git a/SparkleShare/Mac/SparkleController.cs b/SparkleShare/Mac/SparkleController.cs
index f8a503f8..3b4f0e4b 100755
--- a/SparkleShare/Mac/SparkleController.cs
+++ b/SparkleShare/Mac/SparkleController.cs
@@ -41,6 +41,21 @@ namespace SparkleShare {
public SparkleController () : base ()
{
+ string content_path =
+ Directory.GetParent (System.AppDomain.CurrentDomain.BaseDirectory)
+ .ToString ();
+
+ string app_path = Directory.GetParent (content_path).ToString ();
+ string growl_path = Path.Combine (app_path, "Frameworks", "Growl.framework", "Growl");
+
+ // Needed for Growl
+ Dlfcn.dlopen (growl_path, 0);
+ NSApplication.Init ();
+
+ // Let's use the bundled git first
+ SparkleBackend.DefaultBackend.Path =
+ Path.Combine (NSBundle.MainBundle.ResourcePath,
+ "git", "bin", "git");
}
@@ -189,11 +204,10 @@ namespace SparkleShare {
}
- new public void Quit ()
+ public override void OpenFile (string url)
{
- this.watcher.Dispose ();
- NSApplication.SharedApplication.Terminate (new NSObject ());
- base.Quit ();
+ url = url.Replace ("%20", " ");
+ NSWorkspace.SharedWorkspace.OpenFile (url);
}
}
}
diff --git a/SparkleShare/Mac/SparkleEventLog.cs b/SparkleShare/Mac/SparkleEventLog.cs
index 27674b43..38af8234 100755
--- a/SparkleShare/Mac/SparkleEventLog.cs
+++ b/SparkleShare/Mac/SparkleEventLog.cs
@@ -18,7 +18,6 @@
using System;
using System.Drawing;
using System.IO;
-using System.Text.RegularExpressions;
using System.Threading;
using MonoMac.Foundation;
@@ -36,14 +35,17 @@ namespace SparkleShare {
PolicyDelegate = new SparkleWebPolicyDelegate ()
};
- private NSBox Separator = new NSBox (new RectangleF (0, 579, 480, 1)) {
+ private NSBox separator = new NSBox (new RectangleF (0, 579, 480, 1)) {
BorderColor = NSColor.LightGray,
BoxType = NSBoxType.NSBoxCustom
};
private NSPopUpButton popup_button;
private NSProgressIndicator progress_indicator;
-
+ private NSTextField size_label;
+ private NSTextField size_label_value;
+ private NSTextField history_label;
+ private NSTextField history_label_value;
public SparkleEventLog (IntPtr handle) : base (handle) { }
@@ -65,7 +67,54 @@ namespace SparkleShare {
HasShadow = true;
BackingType = NSBackingStore.Buffered;
- ContentView.AddSubview (Separator);
+
+ this.size_label = new NSTextField () {
+ Alignment = NSTextAlignment.Right,
+ BackgroundColor = NSColor.WindowBackground,
+ Bordered = false,
+ Editable = false,
+ Frame = new RectangleF (0, 588, 60, 20),
+ StringValue = "Size:",
+ Font = SparkleUI.BoldFont
+ };
+
+ this.size_label_value = new NSTextField () {
+ Alignment = NSTextAlignment.Left,
+ BackgroundColor = NSColor.WindowBackground,
+ Bordered = false,
+ Editable = false,
+ Frame = new RectangleF (60, 588, 75, 20),
+ StringValue = Controller.Size,
+ Font = SparkleUI.Font
+ };
+
+
+ this.history_label = new NSTextField () {
+ Alignment = NSTextAlignment.Right,
+ BackgroundColor = NSColor.WindowBackground,
+ Bordered = false,
+ Editable = false,
+ Frame = new RectangleF (130, 588, 60, 20),
+ StringValue = "History:",
+ Font = SparkleUI.BoldFont
+ };
+
+ this.history_label_value = new NSTextField () {
+ Alignment = NSTextAlignment.Left,
+ BackgroundColor = NSColor.WindowBackground,
+ Bordered = false,
+ Editable = false,
+ Frame = new RectangleF (190, 588, 75, 20),
+ StringValue = Controller.HistorySize,
+ Font = SparkleUI.Font
+ };
+
+
+ ContentView.AddSubview (this.size_label);
+ ContentView.AddSubview (this.size_label_value);
+ ContentView.AddSubview (this.history_label);
+ ContentView.AddSubview (this.history_label_value);
+ ContentView.AddSubview (this.separator);
this.progress_indicator = new NSProgressIndicator () {
@@ -81,6 +130,7 @@ namespace SparkleShare {
UpdateChooser (null);
OrderFrontRegardless ();
+ Program.UI.UpdateDockIconVisibility ();
// Hook up the controller events
Controller.UpdateChooserEvent += delegate (string [] folders) {
@@ -103,6 +153,13 @@ namespace SparkleShare {
ContentView.AddSubview (this.progress_indicator);
});
};
+
+ Controller.UpdateSizeInfoEvent += delegate (string size, string history_size) {
+ InvokeOnMainThread (delegate {
+ this.size_label_value.StringValue = size;
+ this.history_label_value.StringValue = history_size;
+ });
+ };
}
@@ -123,7 +180,7 @@ namespace SparkleShare {
this.popup_button.Font = NSFontManager.SharedFontManager.FontWithFamily
("Lucida Grande", NSFontTraitMask.Condensed, 0, NSFont.SmallSystemFontSize);
- this.popup_button.AddItem ("All Folders");
+ this.popup_button.AddItem ("All Projects");
this.popup_button.Menu.AddItem (NSMenuItem.SeparatorItem);
this.popup_button.AddItems (folders);
@@ -184,6 +241,8 @@ namespace SparkleShare {
public override bool WindowShouldClose (NSObject sender)
{
(sender as SparkleEventLog).OrderOut (this);
+ Program.UI.UpdateDockIconVisibility ();
+
return false;
}
}
@@ -194,30 +253,7 @@ namespace SparkleShare {
public override void DecidePolicyForNavigation (WebView web_view, NSDictionary action_info,
NSUrlRequest request, WebFrame frame, NSObject decision_token)
{
- string url = request.Url.ToString ();
-
- if (url.StartsWith (Path.VolumeSeparatorChar.ToString ())) {
- string file_path = request.Url.ToString ();
- file_path = file_path.Replace ("%20", " ");
-
- NSWorkspace.SharedWorkspace.OpenFile (file_path);
-
- } else {
- Regex regex = new Regex (@"(.+)~(.+)~(.+)");
- Match match = regex.Match (url);
-
- if (match.Success) {
- string folder_name = match.Groups [1].Value;
- string revision = match.Groups [2].Value;
- string note = match.Groups [3].Value;
-
- Thread thread = new Thread (new ThreadStart (delegate {
- Program.Controller.AddNoteToFolder (folder_name, revision, note);
- }));
-
- thread.Start ();
- }
- }
+ SparkleEventLogController.LinkClicked (request.Url.ToString ());
}
}
}
diff --git a/SparkleShare/Mac/SparkleMacWatcher.cs b/SparkleShare/Mac/SparkleMacWatcher.cs
index 1acf2627..75123de2 100755
--- a/SparkleShare/Mac/SparkleMacWatcher.cs
+++ b/SparkleShare/Mac/SparkleMacWatcher.cs
@@ -28,8 +28,9 @@ namespace SparkleShare {
public delegate void ChangedEventHandler (string path);
public event ChangedEventHandler Changed;
- private DirectoryInfo last_changed;
+ private FileSystemInfo last_changed;
private Thread thread;
+ private int poll_count = 0;
public SparkleMacWatcher (string path)
@@ -50,7 +51,8 @@ namespace SparkleShare {
Changed (relative_path);
}
- Thread.Sleep (2500);
+ Thread.Sleep (7500);
+ this.poll_count++;
}
}));
@@ -73,7 +75,20 @@ namespace SparkleShare {
}
}
- } catch (Exception) { }
+ if (this.poll_count >= 8) {
+ foreach (FileInfo info in parent.GetFiles ()) {
+ if (!info.FullName.Contains ("/.")) {
+ if (DateTime.Compare (info.LastWriteTime, this.last_changed.LastWriteTime) > 0)
+ this.last_changed = info;
+ }
+ }
+
+ this.poll_count = 0;
+ }
+
+ } catch (Exception) {
+ // Don't care...
+ }
}
diff --git a/SparkleShare/Mac/SparkleSetup.cs b/SparkleShare/Mac/SparkleSetup.cs
index f03cc37b..a884b072 100755
--- a/SparkleShare/Mac/SparkleSetup.cs
+++ b/SparkleShare/Mac/SparkleSetup.cs
@@ -16,11 +16,9 @@
using System;
+using System.Collections.Generic;
using System.Drawing;
using System.IO;
-using System.Timers;
-
-using System.Collections.Generic;
using Mono.Unix;
using MonoMac.Foundation;
@@ -54,7 +52,9 @@ namespace SparkleShare {
private NSTextField PathLabel;
private NSTextField PathHelpLabel;
private NSTextField AddProjectTextField;
- private Timer timer;
+ private NSTextField WarningTextField;
+ private NSImage WarningImage;
+ private NSImageView WarningImageView;
private NSTableView TableView;
private NSScrollView ScrollView;
private NSTableColumn IconColumn;
@@ -64,7 +64,7 @@ namespace SparkleShare {
public SparkleSetup () : base ()
{
- Controller.ChangePageEvent += delegate (PageType type) {
+ Controller.ChangePageEvent += delegate (PageType type, string [] warnings) {
InvokeOnMainThread (delegate {
Reset ();
@@ -72,8 +72,8 @@ namespace SparkleShare {
case PageType.Setup: {
Header = "Welcome to SparkleShare!";
- Description = "Before we can create a SparkleShare folder on this " +
- "computer, we need some information from you.";
+ Description = "We'll need some info to mark your changes in the event log. " +
+ "Don't worry, this stays between you and your peers.";
FullNameLabel = new NSTextField () {
@@ -87,8 +87,9 @@ namespace SparkleShare {
};
FullNameTextField = new NSTextField () {
- Frame = new RectangleF (330, Frame.Height - 238, 196, 22),
- StringValue = Controller.GuessedUserName
+ Frame = new RectangleF (330, Frame.Height - 238, 196, 22),
+ StringValue = Controller.GuessedUserName,
+ Delegate = new SparkleTextFieldDelegate ()
};
EmailLabel = new NSTextField () {
@@ -102,42 +103,45 @@ namespace SparkleShare {
};
EmailTextField = new NSTextField () {
- Frame = new RectangleF (330, Frame.Height - 268, 196, 22),
- StringValue = Controller.GuessedUserEmail
+ Frame = new RectangleF (330, Frame.Height - 268, 196, 22),
+ StringValue = Controller.GuessedUserEmail,
+ Delegate = new SparkleTextFieldDelegate ()
};
- // TODO: Ugly hack, do properly with events
- timer = new Timer () {
- Interval = 50
+
+ (FullNameTextField.Delegate as SparkleTextFieldDelegate).StringValueChanged += delegate {
+ Controller.CheckSetupPage (
+ FullNameTextField.StringValue,
+ EmailTextField.StringValue
+ );
};
+ (EmailTextField.Delegate as SparkleTextFieldDelegate).StringValueChanged += delegate {
+ Controller.CheckSetupPage (
+ FullNameTextField.StringValue,
+ EmailTextField.StringValue
+ );
+ };
+
+
ContinueButton = new NSButton () {
Title = "Continue",
Enabled = false
};
ContinueButton.Activated += delegate {
- timer.Stop ();
- timer = null;
-
string full_name = FullNameTextField.StringValue.Trim ();
string email = EmailTextField.StringValue.Trim ();
Controller.SetupPageCompleted (full_name, email);
};
- timer.Elapsed += delegate {
+ Controller.UpdateSetupContinueButtonEvent += delegate (bool button_enabled) {
InvokeOnMainThread (delegate {
- bool name_is_valid = !FullNameTextField.StringValue.Trim ().Equals ("");
-
- bool email_is_valid = Program.Controller.IsValidEmail (
- EmailTextField.StringValue.Trim ());
-
- ContinueButton.Enabled = (name_is_valid && email_is_valid);
+ ContinueButton.Enabled = button_enabled;
});
};
- timer.Start ();
ContentView.AddSubview (FullNameLabel);
ContentView.AddSubview (FullNameTextField);
@@ -146,6 +150,11 @@ namespace SparkleShare {
Buttons.Add (ContinueButton);
+ Controller.CheckSetupPage (
+ FullNameTextField.StringValue,
+ EmailTextField.StringValue
+ );
+
break;
}
@@ -168,7 +177,8 @@ namespace SparkleShare {
Frame = new RectangleF (190, Frame.Height - 336, 196, 22),
Font = SparkleUI.Font,
StringValue = Controller.PreviousAddress,
- Enabled = (Controller.SelectedPlugin.Address == null)
+ Enabled = (Controller.SelectedPlugin.Address == null),
+ Delegate = new SparkleTextFieldDelegate ()
};
@@ -186,12 +196,12 @@ namespace SparkleShare {
Frame = new RectangleF (190 + 196 + 16, Frame.Height - 336, 196, 22),
StringValue = Controller.PreviousPath,
Enabled = (Controller.SelectedPlugin.Path == null),
- Bezeled = true
+ Delegate = new SparkleTextFieldDelegate ()
};
- AddressTextField.Cell.LineBreakMode = NSLineBreakMode.TruncatingTail;
- PathTextField.Cell.LineBreakMode = NSLineBreakMode.TruncatingTail;
+ AddressTextField.Cell.LineBreakMode = NSLineBreakMode.TruncatingTail;
+ PathTextField.Cell.LineBreakMode = NSLineBreakMode.TruncatingTail;
PathHelpLabel = new NSTextField () {
@@ -210,7 +220,8 @@ namespace SparkleShare {
Frame = new RectangleF (0, 0, 0, 0),
RowHeight = 30,
IntercellSpacing = new SizeF (0, 12),
- HeaderView = null
+ HeaderView = null,
+ Delegate = new SparkleTableViewDelegate ()
};
ScrollView = new NSScrollView () {
@@ -270,33 +281,43 @@ namespace SparkleShare {
});
};
+
TableView.SelectRow (Controller.SelectedPluginIndex, false);
- timer = new Timer () {
- Interval = 50
+ (AddressTextField.Delegate as SparkleTextFieldDelegate).StringValueChanged += delegate {
+ Controller.CheckAddPage (
+ AddressTextField.StringValue,
+ PathTextField.StringValue,
+ TableView.SelectedRow
+ );
};
- // TODO: Use an event
- timer.Elapsed += delegate {
- if (TableView.SelectedRow != Controller.SelectedPluginIndex)
- Controller.SelectedPluginChanged (TableView.SelectedRow);
+ (PathTextField.Delegate as SparkleTextFieldDelegate).StringValueChanged += delegate {
+ Controller.CheckAddPage (
+ AddressTextField.StringValue,
+ PathTextField.StringValue,
+ TableView.SelectedRow
+ );
+ };
+ (TableView.Delegate as SparkleTableViewDelegate).SelectionChanged += delegate {
+ Controller.SelectedPluginChanged (TableView.SelectedRow);
+
+ Controller.CheckAddPage (
+ AddressTextField.StringValue,
+ PathTextField.StringValue,
+ TableView.SelectedRow
+ );
+ };
+
+
+ Controller.UpdateAddProjectButtonEvent += delegate (bool button_enabled) {
InvokeOnMainThread (delegate {
- // TODO: Move checking logic to controller
- if (!string.IsNullOrWhiteSpace (AddressTextField.StringValue) &&
- !string.IsNullOrWhiteSpace (PathTextField.StringValue)) {
-
- SyncButton.Enabled = true;
-
- } else {
- SyncButton.Enabled = false;
- }
+ SyncButton.Enabled = button_enabled;
});
};
- timer.Start ();
-
ContentView.AddSubview (ScrollView);
ContentView.AddSubview (AddressLabel);
@@ -311,9 +332,6 @@ namespace SparkleShare {
};
SyncButton.Activated += delegate {
- timer.Stop ();
- timer = null;
-
Controller.AddPageCompleted (
AddressTextField.StringValue,
PathTextField.StringValue
@@ -334,6 +352,13 @@ namespace SparkleShare {
Buttons.Add (CancelButton);
+ Controller.CheckAddPage (
+ AddressTextField.StringValue,
+ PathTextField.StringValue,
+ TableView.SelectedRow
+ );
+
+
break;
}
@@ -442,6 +467,28 @@ namespace SparkleShare {
"‘" + Controller.SyncingFolder + "’ in " +
"your SparkleShare folder.";
+ if (warnings != null) {
+ WarningImage = NSImage.ImageNamed ("NSCaution");
+ WarningImage.Size = new SizeF (24, 24);
+
+ WarningImageView = new NSImageView () {
+ Image = WarningImage,
+ Frame = new RectangleF (190, Frame.Height - 175, 24, 24)
+ };
+
+ WarningTextField = new NSTextField () {
+ Frame = new RectangleF (230, Frame.Height - 245, 325, 100),
+ StringValue = warnings [0],
+ BackgroundColor = NSColor.WindowBackground,
+ Bordered = false,
+ Editable = false,
+ Font = SparkleUI.Font
+ };
+
+ ContentView.AddSubview (WarningImageView);
+ ContentView.AddSubview (WarningTextField);
+ }
+
FinishButton = new NSButton () {
Title = "Finish"
};
@@ -497,7 +544,7 @@ namespace SparkleShare {
};
string slide_image_path = Path.Combine (NSBundle.MainBundle.ResourcePath,
- "Pixmaps", "tutorial-slide-1.png");
+ "Pixmaps", "tutorial-slide-1-mac.png");
SlideImage = new NSImage (slide_image_path) {
Size = new SizeF (350, 200)
@@ -529,7 +576,7 @@ namespace SparkleShare {
};
string slide_image_path = Path.Combine (NSBundle.MainBundle.ResourcePath,
- "Pixmaps", "tutorial-slide-2.png");
+ "Pixmaps", "tutorial-slide-2-mac.png");
SlideImage = new NSImage (slide_image_path) {
Size = new SizeF (350, 200)
@@ -560,7 +607,7 @@ namespace SparkleShare {
};
string slide_image_path = Path.Combine (NSBundle.MainBundle.ResourcePath,
- "Pixmaps", "tutorial-slide-3.png");
+ "Pixmaps", "tutorial-slide-3-mac.png");
SlideImage = new NSImage (slide_image_path) {
Size = new SizeF (350, 200)
@@ -673,4 +720,39 @@ namespace SparkleShare {
}
}
}
+
+
+ public class SparkleTextFieldDelegate : NSTextFieldDelegate {
+
+ public event StringValueChangedHandler StringValueChanged;
+ public delegate void StringValueChangedHandler ();
+
+
+ public override void Changed (NSNotification notification)
+ {
+ if (StringValueChanged!= null)
+ StringValueChanged ();
+ }
+
+
+ public override string [] GetCompletions (NSControl control, NSTextView text_view,
+ string [] a, MonoMac.Foundation.NSRange range, int b)
+ {
+ return new string [0];
+ }
+ }
+
+
+ public class SparkleTableViewDelegate : NSTableViewDelegate {
+
+ public event SelectionChangedHandler SelectionChanged;
+ public delegate void SelectionChangedHandler ();
+
+
+ public override void SelectionDidChange (NSNotification notification)
+ {
+ if (SelectionChanged != null)
+ SelectionChanged ();
+ }
+ }
}
diff --git a/SparkleShare/Mac/SparkleSetupWindow.cs b/SparkleShare/Mac/SparkleSetupWindow.cs
index d0a6ed79..4aa27f42 100755
--- a/SparkleShare/Mac/SparkleSetupWindow.cs
+++ b/SparkleShare/Mac/SparkleSetupWindow.cs
@@ -87,6 +87,7 @@ namespace SparkleShare {
MakeKeyAndOrderFront (this);
OrderFrontRegardless ();
+ Program.UI.UpdateDockIconVisibility ();
}
@@ -143,8 +144,10 @@ namespace SparkleShare {
public override void PerformClose (NSObject sender)
{
- OrderOut (this);
+ base.OrderOut (this);
NSApplication.SharedApplication.RemoveWindowsItem (this);
+ Program.UI.UpdateDockIconVisibility ();
+
return;
}
diff --git a/SparkleShare/Mac/SparkleShare.csproj b/SparkleShare/Mac/SparkleShare.csproj
index d2f87467..f7b1d6f1 100755
--- a/SparkleShare/Mac/SparkleShare.csproj
+++ b/SparkleShare/Mac/SparkleShare.csproj
@@ -11,7 +11,7 @@
SparkleShare
SparkleShare
v4.0
- 0.2.5
+ 0.6.0
true
@@ -24,7 +24,7 @@
false
-
+
@@ -58,15 +58,11 @@
False
-
- False
- ..\..\bin\Meebey.SmartIrc4net.dll
-
-
+
+
False
..\..\bin\SparkleLib.dll
-
@@ -83,8 +79,6 @@
Program.cs
-
-
@@ -113,6 +107,13 @@
SparklePlugin.cs
+
+ SparkleOptions.cs
+
+
+
+ SparkleInvite.cs
+
@@ -277,6 +278,15 @@
Pixmaps\tutorial-slide-1.png
+
+ Pixmaps\tutorial-slide-1-mac.png
+
+
+ Pixmaps\tutorial-slide-2-mac.png
+
+
+ Pixmaps\tutorial-slide-3-mac.png
+
Pixmaps\tutorial-slide-2.png
diff --git a/SparkleShare/Mac/SparkleShare.sln b/SparkleShare/Mac/SparkleShare.sln
old mode 100755
new mode 100644
index 98e98fe8..d22cce42
--- a/SparkleShare/Mac/SparkleShare.sln
+++ b/SparkleShare/Mac/SparkleShare.sln
@@ -16,6 +16,6 @@ Global
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = SparkleShare.csproj
- version = 0.2.5
+ version = 0.6.0
EndGlobalSection
EndGlobal
diff --git a/SparkleShare/Mac/SparkleStatusIcon.cs b/SparkleShare/Mac/SparkleStatusIcon.cs
index 55563d69..d2d4a9cd 100755
--- a/SparkleShare/Mac/SparkleStatusIcon.cs
+++ b/SparkleShare/Mac/SparkleStatusIcon.cs
@@ -46,6 +46,7 @@ namespace SparkleShare {
private NSMenuItem AboutMenuItem;
private NSMenuItem NotificationsMenuItem;
private NSMenuItem RecentEventsMenuItem;
+ private NSMenuItem QuitMenuItem;
private NSImage [] AnimationFrames;
private NSImage [] AnimationFramesActive;
private NSImage ErrorImage;
@@ -110,7 +111,10 @@ namespace SparkleShare {
case IconState.Syncing:
- StateText = _("Syncing…");
+ StateText = _("Syncing… " +
+ Controller.ProgressPercentage + "% " +
+ Controller.ProgressSpeed);
+
StateMenuItem.Title = StateText;
if (!Animation.Enabled)
@@ -119,6 +123,8 @@ namespace SparkleShare {
break;
case IconState.Error:
+
+ Animation.Stop ();
StateText = _("Not everything is synced");
StateMenuItem.Title = StateText;
@@ -240,7 +246,7 @@ namespace SparkleShare {
RecentEventsMenuItem = new NSMenuItem () {
Title = "Open Recent Events",
- Enabled = true
+ Enabled = (Controller.Folders.Length > 0)
};
if (Controller.Folders.Length > 0) {
@@ -298,10 +304,22 @@ namespace SparkleShare {
});
};
+
+ Menu.AddItem (AboutMenuItem);
+ Menu.AddItem (NSMenuItem.SeparatorItem);
+
+
+ QuitMenuItem = new NSMenuItem () {
+ Title = "Quit",
+ Enabled = true
+ };
-
- Menu.AddItem (AboutMenuItem);
-
+ QuitMenuItem.Activated += delegate {
+ Program.Controller.Quit ();
+ };
+
+ Menu.AddItem (QuitMenuItem);
+
StatusItem.Menu = Menu;
StatusItem.Menu.Update ();
}
diff --git a/SparkleShare/Mac/SparkleUI.cs b/SparkleShare/Mac/SparkleUI.cs
index 94dc621b..642cd6f3 100755
--- a/SparkleShare/Mac/SparkleUI.cs
+++ b/SparkleShare/Mac/SparkleUI.cs
@@ -37,22 +37,11 @@ namespace SparkleShare {
public static SparkleBubbles Bubbles;
public static SparkleAbout About;
public static NSFont Font;
-
- private NSAlert alert;
+ public static NSFont BoldFont;
public SparkleUI ()
{
- string content_path = Directory.GetParent (
- System.AppDomain.CurrentDomain.BaseDirectory).ToString ();
-
- string app_path = Directory.GetParent (content_path).ToString ();
- string growl_path = Path.Combine (app_path, "Frameworks", "Growl.framework", "Growl");
-
- // Needed for Growl
- Dlfcn.dlopen (growl_path, 0);
- NSApplication.Init ();
-
// Use translations
Catalog.Init ("sparkleshare",
Path.Combine (NSBundle.MainBundle.ResourcePath, "Translations"));
@@ -66,17 +55,14 @@ namespace SparkleShare {
NSApplication.SharedApplication.ApplicationIconImage
= NSImage.ImageNamed ("sparkleshare.icns");
- if (!Program.Controller.BackendIsPresent) {
- this.alert = new SparkleAlert ();
- this.alert.RunModal ();
- return;
- }
-
SetFolderIcon ();
Font = NSFontManager.SharedFontManager.FontWithFamily
("Lucida Grande", NSFontTraitMask.Condensed, 0, 13);
+ BoldFont = NSFontManager.SharedFontManager.FontWithFamily
+ ("Lucida Grande", NSFontTraitMask.Bold, 0, 13);
+
StatusIcon = new SparkleStatusIcon ();
Bubbles = new SparkleBubbles ();
@@ -106,6 +92,29 @@ namespace SparkleShare {
}
+ public void UpdateDockIconVisibility ()
+ {
+ if (true) { // TODO: check for open windows
+
+ ShowDockIcon ();
+
+ } else {
+ HideDockIcon ();
+ }
+ }
+
+
+ private void HideDockIcon () {
+ // Currently not supported, here for completeness sake (see Apple's docs)
+ // NSApplication.SharedApplication.ActivationPolicy = NSApplicationActivationPolicy.None;
+ }
+
+
+ private void ShowDockIcon () {
+ NSApplication.SharedApplication.ActivationPolicy = NSApplicationActivationPolicy.Regular;
+ }
+
+
[Export("registrationDictionaryForGrowl")]
NSDictionary RegistrationDictionaryForGrowl ()
{
@@ -122,6 +131,7 @@ namespace SparkleShare {
NSApplication.SharedApplication.DockTile.BadgeLabel = null;
}
+
public override void WillTerminate (NSNotification notification)
{
Program.Controller.Quit ();
diff --git a/SparkleShare/Mac/git/LICENSE b/SparkleShare/Mac/git/LICENSE
new file mode 100644
index 00000000..fe81dd87
--- /dev/null
+++ b/SparkleShare/Mac/git/LICENSE
@@ -0,0 +1,370 @@
+From https://github.com/gitster/git:
+
+////////////////////////////////////////////////////////////////
+
+ GIT - the stupid content tracker
+
+////////////////////////////////////////////////////////////////
+
+"git" can mean anything, depending on your mood.
+
+ - random three-letter combination that is pronounceable, and not
+ actually used by any common UNIX command. The fact that it is a
+ mispronunciation of "get" may or may not be relevant.
+ - stupid. contemptible and despicable. simple. Take your pick from the
+ dictionary of slang.
+ - "global information tracker": you're in a good mood, and it actually
+ works for you. Angels sing, and a light suddenly fills the room.
+ - "goddamn idiotic truckload of sh*t": when it breaks
+
+Git is a fast, scalable, distributed revision control system with an
+unusually rich command set that provides both high-level operations
+and full access to internals.
+
+Git is an Open Source project covered by the GNU General Public License.
+It was originally written by Linus Torvalds with help of a group of
+hackers around the net. It is currently maintained by Junio C Hamano.
+
+////////////////////////////////////////////////////////////////
+
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ , 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
+
diff --git a/SparkleShare/Mac/git/bin/git b/SparkleShare/Mac/git/bin/git
new file mode 100755
index 00000000..0e604ec9
Binary files /dev/null and b/SparkleShare/Mac/git/bin/git differ
diff --git a/SparkleShare/Mac/git/bin/git-cvsserver b/SparkleShare/Mac/git/bin/git-cvsserver
new file mode 100755
index 00000000..cafb11f4
--- /dev/null
+++ b/SparkleShare/Mac/git/bin/git-cvsserver
@@ -0,0 +1,3696 @@
+#!/usr/bin/perl
+use lib (split(/:/, $ENV{GITPERLLIB} || "/usr/local/git/lib/perl5/site_perl"));
+
+####
+#### This application is a CVS emulation layer for git.
+#### It is intended for clients to connect over SSH.
+#### See the documentation for more details.
+####
+#### Copyright The Open University UK - 2006.
+####
+#### Authors: Martyn Smith
+#### Martin Langhoff
+####
+####
+#### Released under the GNU Public License, version 2.
+####
+####
+
+use 5.008;
+use strict;
+use warnings;
+use bytes;
+
+use Fcntl;
+use File::Temp qw/tempdir tempfile/;
+use File::Path qw/rmtree/;
+use File::Basename;
+use Getopt::Long qw(:config require_order no_ignore_case);
+
+my $VERSION = '1.7.6.1';
+
+my $log = GITCVS::log->new();
+my $cfg;
+
+my $DATE_LIST = {
+ Jan => "01",
+ Feb => "02",
+ Mar => "03",
+ Apr => "04",
+ May => "05",
+ Jun => "06",
+ Jul => "07",
+ Aug => "08",
+ Sep => "09",
+ Oct => "10",
+ Nov => "11",
+ Dec => "12",
+};
+
+# Enable autoflush for STDOUT (otherwise the whole thing falls apart)
+$| = 1;
+
+#### Definition and mappings of functions ####
+
+my $methods = {
+ 'Root' => \&req_Root,
+ 'Valid-responses' => \&req_Validresponses,
+ 'valid-requests' => \&req_validrequests,
+ 'Directory' => \&req_Directory,
+ 'Entry' => \&req_Entry,
+ 'Modified' => \&req_Modified,
+ 'Unchanged' => \&req_Unchanged,
+ 'Questionable' => \&req_Questionable,
+ 'Argument' => \&req_Argument,
+ 'Argumentx' => \&req_Argument,
+ 'expand-modules' => \&req_expandmodules,
+ 'add' => \&req_add,
+ 'remove' => \&req_remove,
+ 'co' => \&req_co,
+ 'update' => \&req_update,
+ 'ci' => \&req_ci,
+ 'diff' => \&req_diff,
+ 'log' => \&req_log,
+ 'rlog' => \&req_log,
+ 'tag' => \&req_CATCHALL,
+ 'status' => \&req_status,
+ 'admin' => \&req_CATCHALL,
+ 'history' => \&req_CATCHALL,
+ 'watchers' => \&req_EMPTY,
+ 'editors' => \&req_EMPTY,
+ 'noop' => \&req_EMPTY,
+ 'annotate' => \&req_annotate,
+ 'Global_option' => \&req_Globaloption,
+ #'annotate' => \&req_CATCHALL,
+};
+
+##############################################
+
+
+# $state holds all the bits of information the clients sends us that could
+# potentially be useful when it comes to actually _doing_ something.
+my $state = { prependdir => '' };
+
+# Work is for managing temporary working directory
+my $work =
+ {
+ state => undef, # undef, 1 (empty), 2 (with stuff)
+ workDir => undef,
+ index => undef,
+ emptyDir => undef,
+ tmpDir => undef
+ };
+
+$log->info("--------------- STARTING -----------------");
+
+my $usage =
+ "Usage: git cvsserver [options] [pserver|server] [ ...]\n".
+ " --base-path : Prepend to requested CVSROOT\n".
+ " Can be read from GIT_CVSSERVER_BASE_PATH\n".
+ " --strict-paths : Don't allow recursing into subdirectories\n".
+ " --export-all : Don't check for gitcvs.enabled in config\n".
+ " --version, -V : Print version information and exit\n".
+ " --help, -h, -H : Print usage information and exit\n".
+ "\n".
+ " ... is a list of allowed directories. If no directories\n".
+ "are given, all are allowed. This is an additional restriction, gitcvs\n".
+ "access still needs to be enabled by the gitcvs.enabled config option.\n".
+ "Alternately, one directory may be specified in GIT_CVSSERVER_ROOT.\n";
+
+my @opts = ( 'help|h|H', 'version|V',
+ 'base-path=s', 'strict-paths', 'export-all' );
+GetOptions( $state, @opts )
+ or die $usage;
+
+if ($state->{version}) {
+ print "git-cvsserver version $VERSION\n";
+ exit;
+}
+if ($state->{help}) {
+ print $usage;
+ exit;
+}
+
+my $TEMP_DIR = tempdir( CLEANUP => 1 );
+$log->debug("Temporary directory is '$TEMP_DIR'");
+
+$state->{method} = 'ext';
+if (@ARGV) {
+ if ($ARGV[0] eq 'pserver') {
+ $state->{method} = 'pserver';
+ shift @ARGV;
+ } elsif ($ARGV[0] eq 'server') {
+ shift @ARGV;
+ }
+}
+
+# everything else is a directory
+$state->{allowed_roots} = [ @ARGV ];
+
+# don't export the whole system unless the users requests it
+if ($state->{'export-all'} && !@{$state->{allowed_roots}}) {
+ die "--export-all can only be used together with an explicit whitelist\n";
+}
+
+# Environment handling for running under git-shell
+if (exists $ENV{GIT_CVSSERVER_BASE_PATH}) {
+ if ($state->{'base-path'}) {
+ die "Cannot specify base path both ways.\n";
+ }
+ my $base_path = $ENV{GIT_CVSSERVER_BASE_PATH};
+ $state->{'base-path'} = $base_path;
+ $log->debug("Picked up base path '$base_path' from environment.\n");
+}
+if (exists $ENV{GIT_CVSSERVER_ROOT}) {
+ if (@{$state->{allowed_roots}}) {
+ die "Cannot specify roots both ways: @ARGV\n";
+ }
+ my $allowed_root = $ENV{GIT_CVSSERVER_ROOT};
+ $state->{allowed_roots} = [ $allowed_root ];
+ $log->debug("Picked up allowed root '$allowed_root' from environment.\n");
+}
+
+# if we are called with a pserver argument,
+# deal with the authentication cat before entering the
+# main loop
+if ($state->{method} eq 'pserver') {
+ my $line = ; chomp $line;
+ unless( $line =~ /^BEGIN (AUTH|VERIFICATION) REQUEST$/) {
+ die "E Do not understand $line - expecting BEGIN AUTH REQUEST\n";
+ }
+ my $request = $1;
+ $line = ; chomp $line;
+ unless (req_Root('root', $line)) { # reuse Root
+ print "E Invalid root $line \n";
+ exit 1;
+ }
+ $line = ; chomp $line;
+ my $user = $line;
+ $line = ; chomp $line;
+ my $password = $line;
+
+ if ($user eq 'anonymous') {
+ # "A" will be 1 byte, use length instead in case the
+ # encryption method ever changes (yeah, right!)
+ if (length($password) > 1 ) {
+ print "E Don't supply a password for the `anonymous' user\n";
+ print "I HATE YOU\n";
+ exit 1;
+ }
+
+ # Fall through to LOVE
+ } else {
+ # Trying to authenticate a user
+ if (not exists $cfg->{gitcvs}->{authdb}) {
+ print "E the repo config file needs a [gitcvs] section with an 'authdb' parameter set to the filename of the authentication database\n";
+ print "I HATE YOU\n";
+ exit 1;
+ }
+
+ my $authdb = $cfg->{gitcvs}->{authdb};
+
+ unless (-e $authdb) {
+ print "E The authentication database specified in [gitcvs.authdb] does not exist\n";
+ print "I HATE YOU\n";
+ exit 1;
+ }
+
+ my $auth_ok;
+ open my $passwd, "<", $authdb or die $!;
+ while (<$passwd>) {
+ if (m{^\Q$user\E:(.*)}) {
+ if (crypt($user, descramble($password)) eq $1) {
+ $auth_ok = 1;
+ }
+ };
+ }
+ close $passwd;
+
+ unless ($auth_ok) {
+ print "I HATE YOU\n";
+ exit 1;
+ }
+
+ # Fall through to LOVE
+ }
+
+ # For checking whether the user is anonymous on commit
+ $state->{user} = $user;
+
+ $line = ; chomp $line;
+ unless ($line eq "END $request REQUEST") {
+ die "E Do not understand $line -- expecting END $request REQUEST\n";
+ }
+ print "I LOVE YOU\n";
+ exit if $request eq 'VERIFICATION'; # cvs login
+ # and now back to our regular programme...
+}
+
+# Keep going until the client closes the connection
+while ()
+{
+ chomp;
+
+ # Check to see if we've seen this method, and call appropriate function.
+ if ( /^([\w-]+)(?:\s+(.*))?$/ and defined($methods->{$1}) )
+ {
+ # use the $methods hash to call the appropriate sub for this command
+ #$log->info("Method : $1");
+ &{$methods->{$1}}($1,$2);
+ } else {
+ # log fatal because we don't understand this function. If this happens
+ # we're fairly screwed because we don't know if the client is expecting
+ # a response. If it is, the client will hang, we'll hang, and the whole
+ # thing will be custard.
+ $log->fatal("Don't understand command $_\n");
+ die("Unknown command $_");
+ }
+}
+
+$log->debug("Processing time : user=" . (times)[0] . " system=" . (times)[1]);
+$log->info("--------------- FINISH -----------------");
+
+chdir '/';
+exit 0;
+
+# Magic catchall method.
+# This is the method that will handle all commands we haven't yet
+# implemented. It simply sends a warning to the log file indicating a
+# command that hasn't been implemented has been invoked.
+sub req_CATCHALL
+{
+ my ( $cmd, $data ) = @_;
+ $log->warn("Unhandled command : req_$cmd : $data");
+}
+
+# This method invariably succeeds with an empty response.
+sub req_EMPTY
+{
+ print "ok\n";
+}
+
+# Root pathname \n
+# Response expected: no. Tell the server which CVSROOT to use. Note that
+# pathname is a local directory and not a fully qualified CVSROOT variable.
+# pathname must already exist; if creating a new root, use the init
+# request, not Root. pathname does not include the hostname of the server,
+# how to access the server, etc.; by the time the CVS protocol is in use,
+# connection, authentication, etc., are already taken care of. The Root
+# request must be sent only once, and it must be sent before any requests
+# other than Valid-responses, valid-requests, UseUnchanged, Set or init.
+sub req_Root
+{
+ my ( $cmd, $data ) = @_;
+ $log->debug("req_Root : $data");
+
+ unless ($data =~ m#^/#) {
+ print "error 1 Root must be an absolute pathname\n";
+ return 0;
+ }
+
+ my $cvsroot = $state->{'base-path'} || '';
+ $cvsroot =~ s#/+$##;
+ $cvsroot .= $data;
+
+ if ($state->{CVSROOT}
+ && ($state->{CVSROOT} ne $cvsroot)) {
+ print "error 1 Conflicting roots specified\n";
+ return 0;
+ }
+
+ $state->{CVSROOT} = $cvsroot;
+
+ $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
+
+ if (@{$state->{allowed_roots}}) {
+ my $allowed = 0;
+ foreach my $dir (@{$state->{allowed_roots}}) {
+ next unless $dir =~ m#^/#;
+ $dir =~ s#/+$##;
+ if ($state->{'strict-paths'}) {
+ if ($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) {
+ $allowed = 1;
+ last;
+ }
+ } elsif ($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) {
+ $allowed = 1;
+ last;
+ }
+ }
+
+ unless ($allowed) {
+ print "E $ENV{GIT_DIR} does not seem to be a valid GIT repository\n";
+ print "E \n";
+ print "error 1 $ENV{GIT_DIR} is not a valid repository\n";
+ return 0;
+ }
+ }
+
+ unless (-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') {
+ print "E $ENV{GIT_DIR} does not seem to be a valid GIT repository\n";
+ print "E \n";
+ print "error 1 $ENV{GIT_DIR} is not a valid repository\n";
+ return 0;
+ }
+
+ my @gitvars = `git config -l`;
+ if ($?) {
+ print "E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n";
+ print "E \n";
+ print "error 1 - problem executing git-config\n";
+ return 0;
+ }
+ foreach my $line ( @gitvars )
+ {
+ next unless ( $line =~ /^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/ );
+ unless ($2) {
+ $cfg->{$1}{$3} = $4;
+ } else {
+ $cfg->{$1}{$2}{$3} = $4;
+ }
+ }
+
+ my $enabled = ($cfg->{gitcvs}{$state->{method}}{enabled}
+ || $cfg->{gitcvs}{enabled});
+ unless ($state->{'export-all'} ||
+ ($enabled && $enabled =~ /^\s*(1|true|yes)\s*$/i)) {
+ print "E GITCVS emulation needs to be enabled on this repo\n";
+ print "E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n";
+ print "E \n";
+ print "error 1 GITCVS emulation disabled\n";
+ return 0;
+ }
+
+ my $logfile = $cfg->{gitcvs}{$state->{method}}{logfile} || $cfg->{gitcvs}{logfile};
+ if ( $logfile )
+ {
+ $log->setfile($logfile);
+ } else {
+ $log->nofile();
+ }
+
+ return 1;
+}
+
+# Global_option option \n
+# Response expected: no. Transmit one of the global options `-q', `-Q',
+# `-l', `-t', `-r', or `-n'. option must be one of those strings, no
+# variations (such as combining of options) are allowed. For graceful
+# handling of valid-requests, it is probably better to make new global
+# options separate requests, rather than trying to add them to this
+# request.
+sub req_Globaloption
+{
+ my ( $cmd, $data ) = @_;
+ $log->debug("req_Globaloption : $data");
+ $state->{globaloptions}{$data} = 1;
+}
+
+# Valid-responses request-list \n
+# Response expected: no. Tell the server what responses the client will
+# accept. request-list is a space separated list of tokens.
+sub req_Validresponses
+{
+ my ( $cmd, $data ) = @_;
+ $log->debug("req_Validresponses : $data");
+
+ # TODO : re-enable this, currently it's not particularly useful
+ #$state->{validresponses} = [ split /\s+/, $data ];
+}
+
+# valid-requests \n
+# Response expected: yes. Ask the server to send back a Valid-requests
+# response.
+sub req_validrequests
+{
+ my ( $cmd, $data ) = @_;
+
+ $log->debug("req_validrequests");
+
+ $log->debug("SEND : Valid-requests " . join(" ",keys %$methods));
+ $log->debug("SEND : ok");
+
+ print "Valid-requests " . join(" ",keys %$methods) . "\n";
+ print "ok\n";
+}
+
+# Directory local-directory \n
+# Additional data: repository \n. Response expected: no. Tell the server
+# what directory to use. The repository should be a directory name from a
+# previous server response. Note that this both gives a default for Entry
+# and Modified and also for ci and the other commands; normal usage is to
+# send Directory for each directory in which there will be an Entry or
+# Modified, and then a final Directory for the original directory, then the
+# command. The local-directory is relative to the top level at which the
+# command is occurring (i.e. the last Directory which is sent before the
+# command); to indicate that top level, `.' should be sent for
+# local-directory.
+sub req_Directory
+{
+ my ( $cmd, $data ) = @_;
+
+ my $repository = ;
+ chomp $repository;
+
+
+ $state->{localdir} = $data;
+ $state->{repository} = $repository;
+ $state->{path} = $repository;
+ $state->{path} =~ s/^\Q$state->{CVSROOT}\E\///;
+ $state->{module} = $1 if ($state->{path} =~ s/^(.*?)(\/|$)//);
+ $state->{path} .= "/" if ( $state->{path} =~ /\S/ );
+
+ $state->{directory} = $state->{localdir};
+ $state->{directory} = "" if ( $state->{directory} eq "." );
+ $state->{directory} .= "/" if ( $state->{directory} =~ /\S/ );
+
+ if ( (not defined($state->{prependdir}) or $state->{prependdir} eq '') and $state->{localdir} eq "." and $state->{path} =~ /\S/ )
+ {
+ $log->info("Setting prepend to '$state->{path}'");
+ $state->{prependdir} = $state->{path};
+ foreach my $entry ( keys %{$state->{entries}} )
+ {
+ $state->{entries}{$state->{prependdir} . $entry} = $state->{entries}{$entry};
+ delete $state->{entries}{$entry};
+ }
+ }
+
+ if ( defined ( $state->{prependdir} ) )
+ {
+ $log->debug("Prepending '$state->{prependdir}' to state|directory");
+ $state->{directory} = $state->{prependdir} . $state->{directory}
+ }
+ $log->debug("req_Directory : localdir=$data repository=$repository path=$state->{path} directory=$state->{directory} module=$state->{module}");
+}
+
+# Entry entry-line \n
+# Response expected: no. Tell the server what version of a file is on the
+# local machine. The name in entry-line is a name relative to the directory
+# most recently specified with Directory. If the user is operating on only
+# some files in a directory, Entry requests for only those files need be
+# included. If an Entry request is sent without Modified, Is-modified, or
+# Unchanged, it means the file is lost (does not exist in the working
+# directory). If both Entry and one of Modified, Is-modified, or Unchanged
+# are sent for the same file, Entry must be sent first. For a given file,
+# one can send Modified, Is-modified, or Unchanged, but not more than one
+# of these three.
+sub req_Entry
+{
+ my ( $cmd, $data ) = @_;
+
+ #$log->debug("req_Entry : $data");
+
+ my @data = split(/\//, $data);
+
+ $state->{entries}{$state->{directory}.$data[1]} = {
+ revision => $data[2],
+ conflict => $data[3],
+ options => $data[4],
+ tag_or_date => $data[5],
+ };
+
+ $log->info("Received entry line '$data' => '" . $state->{directory} . $data[1] . "'");
+}
+
+# Questionable filename \n
+# Response expected: no. Additional data: no. Tell the server to check
+# whether filename should be ignored, and if not, next time the server
+# sends responses, send (in a M response) `?' followed by the directory and
+# filename. filename must not contain `/'; it needs to be a file in the
+# directory named by the most recent Directory request.
+sub req_Questionable
+{
+ my ( $cmd, $data ) = @_;
+
+ $log->debug("req_Questionable : $data");
+ $state->{entries}{$state->{directory}.$data}{questionable} = 1;
+}
+
+# add \n
+# Response expected: yes. Add a file or directory. This uses any previous
+# Argument, Directory, Entry, or Modified requests, if they have been sent.
+# The last Directory sent specifies the working directory at the time of
+# the operation. To add a directory, send the directory to be added using
+# Directory and Argument requests.
+sub req_add
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit("add");
+
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
+ $updater->update();
+
+ argsfromdir($updater);
+
+ my $addcount = 0;
+
+ foreach my $filename ( @{$state->{args}} )
+ {
+ $filename = filecleanup($filename);
+
+ my $meta = $updater->getmeta($filename);
+ my $wrev = revparse($filename);
+
+ if ($wrev && $meta && ($wrev < 0))
+ {
+ # previously removed file, add back
+ $log->info("added file $filename was previously removed, send 1.$meta->{revision}");
+
+ print "MT +updated\n";
+ print "MT text U \n";
+ print "MT fname $filename\n";
+ print "MT newline\n";
+ print "MT -updated\n";
+
+ unless ( $state->{globaloptions}{-n} )
+ {
+ my ( $filepart, $dirpart ) = filenamesplit($filename,1);
+
+ print "Created $dirpart\n";
+ print $state->{CVSROOT} . "/$state->{module}/$filename\n";
+
+ # this is an "entries" line
+ my $kopts = kopts_from_path($filename,"sha1",$meta->{filehash});
+ $log->debug("/$filepart/1.$meta->{revision}//$kopts/");
+ print "/$filepart/1.$meta->{revision}//$kopts/\n";
+ # permissions
+ $log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
+ print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
+ # transmit file
+ transmitfile($meta->{filehash});
+ }
+
+ next;
+ }
+
+ unless ( defined ( $state->{entries}{$filename}{modified_filename} ) )
+ {
+ print "E cvs add: nothing known about `$filename'\n";
+ next;
+ }
+ # TODO : check we're not squashing an already existing file
+ if ( defined ( $state->{entries}{$filename}{revision} ) )
+ {
+ print "E cvs add: `$filename' has already been entered\n";
+ next;
+ }
+
+ my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
+
+ print "E cvs add: scheduling file `$filename' for addition\n";
+
+ print "Checked-in $dirpart\n";
+ print "$filename\n";
+ my $kopts = kopts_from_path($filename,"file",
+ $state->{entries}{$filename}{modified_filename});
+ print "/$filepart/0//$kopts/\n";
+
+ my $requestedKopts = $state->{opt}{k};
+ if(defined($requestedKopts))
+ {
+ $requestedKopts = "-k$requestedKopts";
+ }
+ else
+ {
+ $requestedKopts = "";
+ }
+ if( $kopts ne $requestedKopts )
+ {
+ $log->warn("Ignoring requested -k='$requestedKopts'"
+ . " for '$filename'; detected -k='$kopts' instead");
+ #TODO: Also have option to send warning to user?
+ }
+
+ $addcount++;
+ }
+
+ if ( $addcount == 1 )
+ {
+ print "E cvs add: use `cvs commit' to add this file permanently\n";
+ }
+ elsif ( $addcount > 1 )
+ {
+ print "E cvs add: use `cvs commit' to add these files permanently\n";
+ }
+
+ print "ok\n";
+}
+
+# remove \n
+# Response expected: yes. Remove a file. This uses any previous Argument,
+# Directory, Entry, or Modified requests, if they have been sent. The last
+# Directory sent specifies the working directory at the time of the
+# operation. Note that this request does not actually do anything to the
+# repository; the only effect of a successful remove request is to supply
+# the client with a new entries line containing `-' to indicate a removed
+# file. In fact, the client probably could perform this operation without
+# contacting the server, although using remove may cause the server to
+# perform a few more checks. The client sends a subsequent ci request to
+# actually record the removal in the repository.
+sub req_remove
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit("remove");
+
+ # Grab a handle to the SQLite db and do any necessary updates
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
+ $updater->update();
+
+ #$log->debug("add state : " . Dumper($state));
+
+ my $rmcount = 0;
+
+ foreach my $filename ( @{$state->{args}} )
+ {
+ $filename = filecleanup($filename);
+
+ if ( defined ( $state->{entries}{$filename}{unchanged} ) or defined ( $state->{entries}{$filename}{modified_filename} ) )
+ {
+ print "E cvs remove: file `$filename' still in working directory\n";
+ next;
+ }
+
+ my $meta = $updater->getmeta($filename);
+ my $wrev = revparse($filename);
+
+ unless ( defined ( $wrev ) )
+ {
+ print "E cvs remove: nothing known about `$filename'\n";
+ next;
+ }
+
+ if ( defined($wrev) and $wrev < 0 )
+ {
+ print "E cvs remove: file `$filename' already scheduled for removal\n";
+ next;
+ }
+
+ unless ( $wrev == $meta->{revision} )
+ {
+ # TODO : not sure if the format of this message is quite correct.
+ print "E cvs remove: Up to date check failed for `$filename'\n";
+ next;
+ }
+
+
+ my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
+
+ print "E cvs remove: scheduling `$filename' for removal\n";
+
+ print "Checked-in $dirpart\n";
+ print "$filename\n";
+ my $kopts = kopts_from_path($filename,"sha1",$meta->{filehash});
+ print "/$filepart/-1.$wrev//$kopts/\n";
+
+ $rmcount++;
+ }
+
+ if ( $rmcount == 1 )
+ {
+ print "E cvs remove: use `cvs commit' to remove this file permanently\n";
+ }
+ elsif ( $rmcount > 1 )
+ {
+ print "E cvs remove: use `cvs commit' to remove these files permanently\n";
+ }
+
+ print "ok\n";
+}
+
+# Modified filename \n
+# Response expected: no. Additional data: mode, \n, file transmission. Send
+# the server a copy of one locally modified file. filename is a file within
+# the most recent directory sent with Directory; it must not contain `/'.
+# If the user is operating on only some files in a directory, only those
+# files need to be included. This can also be sent without Entry, if there
+# is no entry for the file.
+sub req_Modified
+{
+ my ( $cmd, $data ) = @_;
+
+ my $mode = ;
+ defined $mode
+ or (print "E end of file reading mode for $data\n"), return;
+ chomp $mode;
+ my $size = ;
+ defined $size
+ or (print "E end of file reading size of $data\n"), return;
+ chomp $size;
+
+ # Grab config information
+ my $blocksize = 8192;
+ my $bytesleft = $size;
+ my $tmp;
+
+ # Get a filehandle/name to write it to
+ my ( $fh, $filename ) = tempfile( DIR => $TEMP_DIR );
+
+ # Loop over file data writing out to temporary file.
+ while ( $bytesleft )
+ {
+ $blocksize = $bytesleft if ( $bytesleft < $blocksize );
+ read STDIN, $tmp, $blocksize;
+ print $fh $tmp;
+ $bytesleft -= $blocksize;
+ }
+
+ close $fh
+ or (print "E failed to write temporary, $filename: $!\n"), return;
+
+ # Ensure we have something sensible for the file mode
+ if ( $mode =~ /u=(\w+)/ )
+ {
+ $mode = $1;
+ } else {
+ $mode = "rw";
+ }
+
+ # Save the file data in $state
+ $state->{entries}{$state->{directory}.$data}{modified_filename} = $filename;
+ $state->{entries}{$state->{directory}.$data}{modified_mode} = $mode;
+ $state->{entries}{$state->{directory}.$data}{modified_hash} = `git hash-object $filename`;
+ $state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s;
+
+ #$log->debug("req_Modified : file=$data mode=$mode size=$size");
+}
+
+# Unchanged filename \n
+# Response expected: no. Tell the server that filename has not been
+# modified in the checked out directory. The filename is a file within the
+# most recent directory sent with Directory; it must not contain `/'.
+sub req_Unchanged
+{
+ my ( $cmd, $data ) = @_;
+
+ $state->{entries}{$state->{directory}.$data}{unchanged} = 1;
+
+ #$log->debug("req_Unchanged : $data");
+}
+
+# Argument text \n
+# Response expected: no. Save argument for use in a subsequent command.
+# Arguments accumulate until an argument-using command is given, at which
+# point they are forgotten.
+# Argumentx text \n
+# Response expected: no. Append \n followed by text to the current argument
+# being saved.
+sub req_Argument
+{
+ my ( $cmd, $data ) = @_;
+
+ # Argumentx means: append to last Argument (with a newline in front)
+
+ $log->debug("$cmd : $data");
+
+ if ( $cmd eq 'Argumentx') {
+ ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" . $data;
+ } else {
+ push @{$state->{arguments}}, $data;
+ }
+}
+
+# expand-modules \n
+# Response expected: yes. Expand the modules which are specified in the
+# arguments. Returns the data in Module-expansion responses. Note that the
+# server can assume that this is checkout or export, not rtag or rdiff; the
+# latter do not access the working directory and thus have no need to
+# expand modules on the client side. Expand may not be the best word for
+# what this request does. It does not necessarily tell you all the files
+# contained in a module, for example. Basically it is a way of telling you
+# which working directories the server needs to know about in order to
+# handle a checkout of the specified modules. For example, suppose that the
+# server has a module defined by
+# aliasmodule -a 1dir
+# That is, one can check out aliasmodule and it will take 1dir in the
+# repository and check it out to 1dir in the working directory. Now suppose
+# the client already has this module checked out and is planning on using
+# the co request to update it. Without using expand-modules, the client
+# would have two bad choices: it could either send information about all
+# working directories under the current directory, which could be
+# unnecessarily slow, or it could be ignorant of the fact that aliasmodule
+# stands for 1dir, and neglect to send information for 1dir, which would
+# lead to incorrect operation. With expand-modules, the client would first
+# ask for the module to be expanded:
+sub req_expandmodules
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit();
+
+ $log->debug("req_expandmodules : " . ( defined($data) ? $data : "[NULL]" ) );
+
+ unless ( ref $state->{arguments} eq "ARRAY" )
+ {
+ print "ok\n";
+ return;
+ }
+
+ foreach my $module ( @{$state->{arguments}} )
+ {
+ $log->debug("SEND : Module-expansion $module");
+ print "Module-expansion $module\n";
+ }
+
+ print "ok\n";
+ statecleanup();
+}
+
+# co \n
+# Response expected: yes. Get files from the repository. This uses any
+# previous Argument, Directory, Entry, or Modified requests, if they have
+# been sent. Arguments to this command are module names; the client cannot
+# know what directories they correspond to except by (1) just sending the
+# co request, and then seeing what directory names the server sends back in
+# its responses, and (2) the expand-modules request.
+sub req_co
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit("co");
+
+ # Provide list of modules, if -c was used.
+ if (exists $state->{opt}{c}) {
+ my $showref = `git show-ref --heads`;
+ for my $line (split '\n', $showref) {
+ if ( $line =~ m% refs/heads/(.*)$% ) {
+ print "M $1\t$1\n";
+ }
+ }
+ print "ok\n";
+ return 1;
+ }
+
+ my $module = $state->{args}[0];
+ $state->{module} = $module;
+ my $checkout_path = $module;
+
+ # use the user specified directory if we're given it
+ $checkout_path = $state->{opt}{d} if ( exists ( $state->{opt}{d} ) );
+
+ $log->debug("req_co : " . ( defined($data) ? $data : "[NULL]" ) );
+
+ $log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'");
+
+ $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
+
+ # Grab a handle to the SQLite db and do any necessary updates
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $module, $log);
+ $updater->update();
+
+ $checkout_path =~ s|/$||; # get rid of trailing slashes
+
+ # Eclipse seems to need the Clear-sticky command
+ # to prepare the 'Entries' file for the new directory.
+ print "Clear-sticky $checkout_path/\n";
+ print $state->{CVSROOT} . "/$module/\n";
+ print "Clear-static-directory $checkout_path/\n";
+ print $state->{CVSROOT} . "/$module/\n";
+ print "Clear-sticky $checkout_path/\n"; # yes, twice
+ print $state->{CVSROOT} . "/$module/\n";
+ print "Template $checkout_path/\n";
+ print $state->{CVSROOT} . "/$module/\n";
+ print "0\n";
+
+ # instruct the client that we're checking out to $checkout_path
+ print "E cvs checkout: Updating $checkout_path\n";
+
+ my %seendirs = ();
+ my $lastdir ='';
+
+ # recursive
+ sub prepdir {
+ my ($dir, $repodir, $remotedir, $seendirs) = @_;
+ my $parent = dirname($dir);
+ $dir =~ s|/+$||;
+ $repodir =~ s|/+$||;
+ $remotedir =~ s|/+$||;
+ $parent =~ s|/+$||;
+ $log->debug("announcedir $dir, $repodir, $remotedir" );
+
+ if ($parent eq '.' || $parent eq './') {
+ $parent = '';
+ }
+ # recurse to announce unseen parents first
+ if (length($parent) && !exists($seendirs->{$parent})) {
+ prepdir($parent, $repodir, $remotedir, $seendirs);
+ }
+ # Announce that we are going to modify at the parent level
+ if ($parent) {
+ print "E cvs checkout: Updating $remotedir/$parent\n";
+ } else {
+ print "E cvs checkout: Updating $remotedir\n";
+ }
+ print "Clear-sticky $remotedir/$parent/\n";
+ print "$repodir/$parent/\n";
+
+ print "Clear-static-directory $remotedir/$dir/\n";
+ print "$repodir/$dir/\n";
+ print "Clear-sticky $remotedir/$parent/\n"; # yes, twice
+ print "$repodir/$parent/\n";
+ print "Template $remotedir/$dir/\n";
+ print "$repodir/$dir/\n";
+ print "0\n";
+
+ $seendirs->{$dir} = 1;
+ }
+
+ foreach my $git ( @{$updater->gethead} )
+ {
+ # Don't want to check out deleted files
+ next if ( $git->{filehash} eq "deleted" );
+
+ my $fullName = $git->{name};
+ ( $git->{name}, $git->{dir} ) = filenamesplit($git->{name});
+
+ if (length($git->{dir}) && $git->{dir} ne './'
+ && $git->{dir} ne $lastdir ) {
+ unless (exists($seendirs{$git->{dir}})) {
+ prepdir($git->{dir}, $state->{CVSROOT} . "/$module/",
+ $checkout_path, \%seendirs);
+ $lastdir = $git->{dir};
+ $seendirs{$git->{dir}} = 1;
+ }
+ print "E cvs checkout: Updating /$checkout_path/$git->{dir}\n";
+ }
+
+ # modification time of this file
+ print "Mod-time $git->{modified}\n";
+
+ # print some information to the client
+ if ( defined ( $git->{dir} ) and $git->{dir} ne "./" )
+ {
+ print "M U $checkout_path/$git->{dir}$git->{name}\n";
+ } else {
+ print "M U $checkout_path/$git->{name}\n";
+ }
+
+ # instruct client we're sending a file to put in this path
+ print "Created $checkout_path/" . ( defined ( $git->{dir} ) and $git->{dir} ne "./" ? $git->{dir} . "/" : "" ) . "\n";
+
+ print $state->{CVSROOT} . "/$module/" . ( defined ( $git->{dir} ) and $git->{dir} ne "./" ? $git->{dir} . "/" : "" ) . "$git->{name}\n";
+
+ # this is an "entries" line
+ my $kopts = kopts_from_path($fullName,"sha1",$git->{filehash});
+ print "/$git->{name}/1.$git->{revision}//$kopts/\n";
+ # permissions
+ print "u=$git->{mode},g=$git->{mode},o=$git->{mode}\n";
+
+ # transmit file
+ transmitfile($git->{filehash});
+ }
+
+ print "ok\n";
+
+ statecleanup();
+}
+
+# update \n
+# Response expected: yes. Actually do a cvs update command. This uses any
+# previous Argument, Directory, Entry, or Modified requests, if they have
+# been sent. The last Directory sent specifies the working directory at the
+# time of the operation. The -I option is not used--files which the client
+# can decide whether to ignore are not mentioned and the client sends the
+# Questionable request for others.
+sub req_update
+{
+ my ( $cmd, $data ) = @_;
+
+ $log->debug("req_update : " . ( defined($data) ? $data : "[NULL]" ));
+
+ argsplit("update");
+
+ #
+ # It may just be a client exploring the available heads/modules
+ # in that case, list them as top level directories and leave it
+ # at that. Eclipse uses this technique to offer you a list of
+ # projects (heads in this case) to checkout.
+ #
+ if ($state->{module} eq '') {
+ my $showref = `git show-ref --heads`;
+ print "E cvs update: Updating .\n";
+ for my $line (split '\n', $showref) {
+ if ( $line =~ m% refs/heads/(.*)$% ) {
+ print "E cvs update: New directory `$1'\n";
+ }
+ }
+ print "ok\n";
+ return 1;
+ }
+
+
+ # Grab a handle to the SQLite db and do any necessary updates
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
+
+ $updater->update();
+
+ argsfromdir($updater);
+
+ #$log->debug("update state : " . Dumper($state));
+
+ my $last_dirname = "///";
+
+ # foreach file specified on the command line ...
+ foreach my $filename ( @{$state->{args}} )
+ {
+ $filename = filecleanup($filename);
+
+ $log->debug("Processing file $filename");
+
+ unless ( $state->{globaloptions}{-Q} || $state->{globaloptions}{-q} )
+ {
+ my $cur_dirname = dirname($filename);
+ if ( $cur_dirname ne $last_dirname )
+ {
+ $last_dirname = $cur_dirname;
+ if ( $cur_dirname eq "" )
+ {
+ $cur_dirname = ".";
+ }
+ print "E cvs update: Updating $cur_dirname\n";
+ }
+ }
+
+ # if we have a -C we should pretend we never saw modified stuff
+ if ( exists ( $state->{opt}{C} ) )
+ {
+ delete $state->{entries}{$filename}{modified_hash};
+ delete $state->{entries}{$filename}{modified_filename};
+ $state->{entries}{$filename}{unchanged} = 1;
+ }
+
+ my $meta;
+ if ( defined($state->{opt}{r}) and $state->{opt}{r} =~ /^1\.(\d+)/ )
+ {
+ $meta = $updater->getmeta($filename, $1);
+ } else {
+ $meta = $updater->getmeta($filename);
+ }
+
+ # If -p was given, "print" the contents of the requested revision.
+ if ( exists ( $state->{opt}{p} ) ) {
+ if ( defined ( $meta->{revision} ) ) {
+ $log->info("Printing '$filename' revision " . $meta->{revision});
+
+ transmitfile($meta->{filehash}, { print => 1 });
+ }
+
+ next;
+ }
+
+ if ( ! defined $meta )
+ {
+ $meta = {
+ name => $filename,
+ revision => 0,
+ filehash => 'added'
+ };
+ }
+
+ my $oldmeta = $meta;
+
+ my $wrev = revparse($filename);
+
+ # If the working copy is an old revision, lets get that version too for comparison.
+ if ( defined($wrev) and $wrev != $meta->{revision} )
+ {
+ $oldmeta = $updater->getmeta($filename, $wrev);
+ }
+
+ #$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");
+
+ # Files are up to date if the working copy and repo copy have the same revision,
+ # and the working copy is unmodified _and_ the user hasn't specified -C
+ next if ( defined ( $wrev )
+ and defined($meta->{revision})
+ and $wrev == $meta->{revision}
+ and $state->{entries}{$filename}{unchanged}
+ and not exists ( $state->{opt}{C} ) );
+
+ # If the working copy and repo copy have the same revision,
+ # but the working copy is modified, tell the client it's modified
+ if ( defined ( $wrev )
+ and defined($meta->{revision})
+ and $wrev == $meta->{revision}
+ and defined($state->{entries}{$filename}{modified_hash})
+ and not exists ( $state->{opt}{C} ) )
+ {
+ $log->info("Tell the client the file is modified");
+ print "MT text M \n";
+ print "MT fname $filename\n";
+ print "MT newline\n";
+ next;
+ }
+
+ if ( $meta->{filehash} eq "deleted" )
+ {
+ my ( $filepart, $dirpart ) = filenamesplit($filename,1);
+
+ $log->info("Removing '$filename' from working copy (no longer in the repo)");
+
+ print "E cvs update: `$filename' is no longer in the repository\n";
+ # Don't want to actually _DO_ the update if -n specified
+ unless ( $state->{globaloptions}{-n} ) {
+ print "Removed $dirpart\n";
+ print "$filepart\n";
+ }
+ }
+ elsif ( not defined ( $state->{entries}{$filename}{modified_hash} )
+ or $state->{entries}{$filename}{modified_hash} eq $oldmeta->{filehash}
+ or $meta->{filehash} eq 'added' )
+ {
+ # normal update, just send the new revision (either U=Update,
+ # or A=Add, or R=Remove)
+ if ( defined($wrev) && $wrev < 0 )
+ {
+ $log->info("Tell the client the file is scheduled for removal");
+ print "MT text R \n";
+ print "MT fname $filename\n";
+ print "MT newline\n";
+ next;
+ }
+ elsif ( (!defined($wrev) || $wrev == 0) && (!defined($meta->{revision}) || $meta->{revision} == 0) )
+ {
+ $log->info("Tell the client the file is scheduled for addition");
+ print "MT text A \n";
+ print "MT fname $filename\n";
+ print "MT newline\n";
+ next;
+
+ }
+ else {
+ $log->info("Updating '$filename' to ".$meta->{revision});
+ print "MT +updated\n";
+ print "MT text U \n";
+ print "MT fname $filename\n";
+ print "MT newline\n";
+ print "MT -updated\n";
+ }
+
+ my ( $filepart, $dirpart ) = filenamesplit($filename,1);
+
+ # Don't want to actually _DO_ the update if -n specified
+ unless ( $state->{globaloptions}{-n} )
+ {
+ if ( defined ( $wrev ) )
+ {
+ # instruct client we're sending a file to put in this path as a replacement
+ print "Update-existing $dirpart\n";
+ $log->debug("Updating existing file 'Update-existing $dirpart'");
+ } else {
+ # instruct client we're sending a file to put in this path as a new file
+ print "Clear-static-directory $dirpart\n";
+ print $state->{CVSROOT} . "/$state->{module}/$dirpart\n";
+ print "Clear-sticky $dirpart\n";
+ print $state->{CVSROOT} . "/$state->{module}/$dirpart\n";
+
+ $log->debug("Creating new file 'Created $dirpart'");
+ print "Created $dirpart\n";
+ }
+ print $state->{CVSROOT} . "/$state->{module}/$filename\n";
+
+ # this is an "entries" line
+ my $kopts = kopts_from_path($filename,"sha1",$meta->{filehash});
+ $log->debug("/$filepart/1.$meta->{revision}//$kopts/");
+ print "/$filepart/1.$meta->{revision}//$kopts/\n";
+
+ # permissions
+ $log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
+ print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
+
+ # transmit file
+ transmitfile($meta->{filehash});
+ }
+ } else {
+ $log->info("Updating '$filename'");
+ my ( $filepart, $dirpart ) = filenamesplit($meta->{name},1);
+
+ my $mergeDir = setupTmpDir();
+
+ my $file_local = $filepart . ".mine";
+ my $mergedFile = "$mergeDir/$file_local";
+ system("ln","-s",$state->{entries}{$filename}{modified_filename}, $file_local);
+ my $file_old = $filepart . "." . $oldmeta->{revision};
+ transmitfile($oldmeta->{filehash}, { targetfile => $file_old });
+ my $file_new = $filepart . "." . $meta->{revision};
+ transmitfile($meta->{filehash}, { targetfile => $file_new });
+
+ # we need to merge with the local changes ( M=successful merge, C=conflict merge )
+ $log->info("Merging $file_local, $file_old, $file_new");
+ print "M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into $filename\n";
+
+ $log->debug("Temporary directory for merge is $mergeDir");
+
+ my $return = system("git", "merge-file", $file_local, $file_old, $file_new);
+ $return >>= 8;
+
+ cleanupTmpDir();
+
+ if ( $return == 0 )
+ {
+ $log->info("Merged successfully");
+ print "M M $filename\n";
+ $log->debug("Merged $dirpart");
+
+ # Don't want to actually _DO_ the update if -n specified
+ unless ( $state->{globaloptions}{-n} )
+ {
+ print "Merged $dirpart\n";
+ $log->debug($state->{CVSROOT} . "/$state->{module}/$filename");
+ print $state->{CVSROOT} . "/$state->{module}/$filename\n";
+ my $kopts = kopts_from_path("$dirpart/$filepart",
+ "file",$mergedFile);
+ $log->debug("/$filepart/1.$meta->{revision}//$kopts/");
+ print "/$filepart/1.$meta->{revision}//$kopts/\n";
+ }
+ }
+ elsif ( $return == 1 )
+ {
+ $log->info("Merged with conflicts");
+ print "E cvs update: conflicts found in $filename\n";
+ print "M C $filename\n";
+
+ # Don't want to actually _DO_ the update if -n specified
+ unless ( $state->{globaloptions}{-n} )
+ {
+ print "Merged $dirpart\n";
+ print $state->{CVSROOT} . "/$state->{module}/$filename\n";
+ my $kopts = kopts_from_path("$dirpart/$filepart",
+ "file",$mergedFile);
+ print "/$filepart/1.$meta->{revision}/+/$kopts/\n";
+ }
+ }
+ else
+ {
+ $log->warn("Merge failed");
+ next;
+ }
+
+ # Don't want to actually _DO_ the update if -n specified
+ unless ( $state->{globaloptions}{-n} )
+ {
+ # permissions
+ $log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
+ print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
+
+ # transmit file, format is single integer on a line by itself (file
+ # size) followed by the file contents
+ # TODO : we should copy files in blocks
+ my $data = `cat $mergedFile`;
+ $log->debug("File size : " . length($data));
+ print length($data) . "\n";
+ print $data;
+ }
+ }
+
+ }
+
+ print "ok\n";
+}
+
+sub req_ci
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit("ci");
+
+ #$log->debug("State : " . Dumper($state));
+
+ $log->info("req_ci : " . ( defined($data) ? $data : "[NULL]" ));
+
+ if ( $state->{method} eq 'pserver' and $state->{user} eq 'anonymous' )
+ {
+ print "error 1 anonymous user cannot commit via pserver\n";
+ cleanupWorkTree();
+ exit;
+ }
+
+ if ( -e $state->{CVSROOT} . "/index" )
+ {
+ $log->warn("file 'index' already exists in the git repository");
+ print "error 1 Index already exists in git repo\n";
+ cleanupWorkTree();
+ exit;
+ }
+
+ # Grab a handle to the SQLite db and do any necessary updates
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
+ $updater->update();
+
+ # Remember where the head was at the beginning.
+ my $parenthash = `git show-ref -s refs/heads/$state->{module}`;
+ chomp $parenthash;
+ if ($parenthash !~ /^[0-9a-f]{40}$/) {
+ print "error 1 pserver cannot find the current HEAD of module";
+ cleanupWorkTree();
+ exit;
+ }
+
+ setupWorkTree($parenthash);
+
+ $log->info("Lockless commit start, basing commit on '$work->{workDir}', index file is '$work->{index}'");
+
+ $log->info("Created index '$work->{index}' for head $state->{module} - exit status $?");
+
+ my @committedfiles = ();
+ my %oldmeta;
+
+ # foreach file specified on the command line ...
+ foreach my $filename ( @{$state->{args}} )
+ {
+ my $committedfile = $filename;
+ $filename = filecleanup($filename);
+
+ next unless ( exists $state->{entries}{$filename}{modified_filename} or not $state->{entries}{$filename}{unchanged} );
+
+ my $meta = $updater->getmeta($filename);
+ $oldmeta{$filename} = $meta;
+
+ my $wrev = revparse($filename);
+
+ my ( $filepart, $dirpart ) = filenamesplit($filename);
+
+ # do a checkout of the file if it is part of this tree
+ if ($wrev) {
+ system('git', 'checkout-index', '-f', '-u', $filename);
+ unless ($? == 0) {
+ die "Error running git-checkout-index -f -u $filename : $!";
+ }
+ }
+
+ my $addflag = 0;
+ my $rmflag = 0;
+ $rmflag = 1 if ( defined($wrev) and $wrev < 0 );
+ $addflag = 1 unless ( -e $filename );
+
+ # Do up to date checking
+ unless ( $addflag or $wrev == $meta->{revision} or ( $rmflag and -$wrev == $meta->{revision} ) )
+ {
+ # fail everything if an up to date check fails
+ print "error 1 Up to date check failed for $filename\n";
+ cleanupWorkTree();
+ exit;
+ }
+
+ push @committedfiles, $committedfile;
+ $log->info("Committing $filename");
+
+ system("mkdir","-p",$dirpart) unless ( -d $dirpart );
+
+ unless ( $rmflag )
+ {
+ $log->debug("rename $state->{entries}{$filename}{modified_filename} $filename");
+ rename $state->{entries}{$filename}{modified_filename},$filename;
+
+ # Calculate modes to remove
+ my $invmode = "";
+ foreach ( qw (r w x) ) { $invmode .= $_ unless ( $state->{entries}{$filename}{modified_mode} =~ /$_/ ); }
+
+ $log->debug("chmod u+" . $state->{entries}{$filename}{modified_mode} . "-" . $invmode . " $filename");
+ system("chmod","u+" . $state->{entries}{$filename}{modified_mode} . "-" . $invmode, $filename);
+ }
+
+ if ( $rmflag )
+ {
+ $log->info("Removing file '$filename'");
+ unlink($filename);
+ system("git", "update-index", "--remove", $filename);
+ }
+ elsif ( $addflag )
+ {
+ $log->info("Adding file '$filename'");
+ system("git", "update-index", "--add", $filename);
+ } else {
+ $log->info("Updating file '$filename'");
+ system("git", "update-index", $filename);
+ }
+ }
+
+ unless ( scalar(@committedfiles) > 0 )
+ {
+ print "E No files to commit\n";
+ print "ok\n";
+ cleanupWorkTree();
+ return;
+ }
+
+ my $treehash = `git write-tree`;
+ chomp $treehash;
+
+ $log->debug("Treehash : $treehash, Parenthash : $parenthash");
+
+ # write our commit message out if we have one ...
+ my ( $msg_fh, $msg_filename ) = tempfile( DIR => $TEMP_DIR );
+ print $msg_fh $state->{opt}{m};# if ( exists ( $state->{opt}{m} ) );
+ if ( defined ( $cfg->{gitcvs}{commitmsgannotation} ) ) {
+ if ($cfg->{gitcvs}{commitmsgannotation} !~ /^\s*$/ ) {
+ print $msg_fh "\n\n".$cfg->{gitcvs}{commitmsgannotation}."\n"
+ }
+ } else {
+ print $msg_fh "\n\nvia git-CVS emulator\n";
+ }
+ close $msg_fh;
+
+ my $commithash = `git commit-tree $treehash -p $parenthash < $msg_filename`;
+ chomp($commithash);
+ $log->info("Commit hash : $commithash");
+
+ unless ( $commithash =~ /[a-zA-Z0-9]{40}/ )
+ {
+ $log->warn("Commit failed (Invalid commit hash)");
+ print "error 1 Commit failed (unknown reason)\n";
+ cleanupWorkTree();
+ exit;
+ }
+
+ ### Emulate git-receive-pack by running hooks/update
+ my @hook = ( $ENV{GIT_DIR}.'hooks/update', "refs/heads/$state->{module}",
+ $parenthash, $commithash );
+ if( -x $hook[0] ) {
+ unless( system( @hook ) == 0 )
+ {
+ $log->warn("Commit failed (update hook declined to update ref)");
+ print "error 1 Commit failed (update hook declined)\n";
+ cleanupWorkTree();
+ exit;
+ }
+ }
+
+ ### Update the ref
+ if (system(qw(git update-ref -m), "cvsserver ci",
+ "refs/heads/$state->{module}", $commithash, $parenthash)) {
+ $log->warn("update-ref for $state->{module} failed.");
+ print "error 1 Cannot commit -- update first\n";
+ cleanupWorkTree();
+ exit;
+ }
+
+ ### Emulate git-receive-pack by running hooks/post-receive
+ my $hook = $ENV{GIT_DIR}.'hooks/post-receive';
+ if( -x $hook ) {
+ open(my $pipe, "| $hook") || die "can't fork $!";
+
+ local $SIG{PIPE} = sub { die 'pipe broke' };
+
+ print $pipe "$parenthash $commithash refs/heads/$state->{module}\n";
+
+ close $pipe || die "bad pipe: $! $?";
+ }
+
+ $updater->update();
+
+ ### Then hooks/post-update
+ $hook = $ENV{GIT_DIR}.'hooks/post-update';
+ if (-x $hook) {
+ system($hook, "refs/heads/$state->{module}");
+ }
+
+ # foreach file specified on the command line ...
+ foreach my $filename ( @committedfiles )
+ {
+ $filename = filecleanup($filename);
+
+ my $meta = $updater->getmeta($filename);
+ unless (defined $meta->{revision}) {
+ $meta->{revision} = 1;
+ }
+
+ my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
+
+ $log->debug("Checked-in $dirpart : $filename");
+
+ print "M $state->{CVSROOT}/$state->{module}/$filename,v <-- $dirpart$filepart\n";
+ if ( defined $meta->{filehash} && $meta->{filehash} eq "deleted" )
+ {
+ print "M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";
+ print "Remove-entry $dirpart\n";
+ print "$filename\n";
+ } else {
+ if ($meta->{revision} == 1) {
+ print "M initial revision: 1.1\n";
+ } else {
+ print "M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";
+ }
+ print "Checked-in $dirpart\n";
+ print "$filename\n";
+ my $kopts = kopts_from_path($filename,"sha1",$meta->{filehash});
+ print "/$filepart/1.$meta->{revision}//$kopts/\n";
+ }
+ }
+
+ cleanupWorkTree();
+ print "ok\n";
+}
+
+sub req_status
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit("status");
+
+ $log->info("req_status : " . ( defined($data) ? $data : "[NULL]" ));
+ #$log->debug("status state : " . Dumper($state));
+
+ # Grab a handle to the SQLite db and do any necessary updates
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
+ $updater->update();
+
+ # if no files were specified, we need to work out what files we should be providing status on ...
+ argsfromdir($updater);
+
+ # foreach file specified on the command line ...
+ foreach my $filename ( @{$state->{args}} )
+ {
+ $filename = filecleanup($filename);
+
+ next if exists($state->{opt}{l}) && index($filename, '/', length($state->{prependdir})) >= 0;
+
+ my $meta = $updater->getmeta($filename);
+ my $oldmeta = $meta;
+
+ my $wrev = revparse($filename);
+
+ # If the working copy is an old revision, lets get that version too for comparison.
+ if ( defined($wrev) and $wrev != $meta->{revision} )
+ {
+ $oldmeta = $updater->getmeta($filename, $wrev);
+ }
+
+ # TODO : All possible statuses aren't yet implemented
+ my $status;
+ # Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified
+ $status = "Up-to-date" if ( defined ( $wrev ) and defined($meta->{revision}) and $wrev == $meta->{revision}
+ and
+ ( ( $state->{entries}{$filename}{unchanged} and ( not defined ( $state->{entries}{$filename}{conflict} ) or $state->{entries}{$filename}{conflict} !~ /^\+=/ ) )
+ or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $meta->{filehash} ) )
+ );
+
+ # Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified
+ $status ||= "Needs Checkout" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and $meta->{revision} > $wrev
+ and
+ ( $state->{entries}{$filename}{unchanged}
+ or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $oldmeta->{filehash} ) )
+ );
+
+ # Need checkout if it exists in the repo but doesn't have a working copy
+ $status ||= "Needs Checkout" if ( not defined ( $wrev ) and defined ( $meta->{revision} ) );
+
+ # Locally modified if working copy and repo copy have the same revision but there are local changes
+ $status ||= "Locally Modified" if ( defined ( $wrev ) and defined($meta->{revision}) and $wrev == $meta->{revision} and $state->{entries}{$filename}{modified_filename} );
+
+ # Needs Merge if working copy revision is less than repo copy and there are local changes
+ $status ||= "Needs Merge" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and $meta->{revision} > $wrev and $state->{entries}{$filename}{modified_filename} );
+
+ $status ||= "Locally Added" if ( defined ( $state->{entries}{$filename}{revision} ) and not defined ( $meta->{revision} ) );
+ $status ||= "Locally Removed" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and -$wrev == $meta->{revision} );
+ $status ||= "Unresolved Conflict" if ( defined ( $state->{entries}{$filename}{conflict} ) and $state->{entries}{$filename}{conflict} =~ /^\+=/ );
+ $status ||= "File had conflicts on merge" if ( 0 );
+
+ $status ||= "Unknown";
+
+ my ($filepart) = filenamesplit($filename);
+
+ print "M ===================================================================\n";
+ print "M File: $filepart\tStatus: $status\n";
+ if ( defined($state->{entries}{$filename}{revision}) )
+ {
+ print "M Working revision:\t" . $state->{entries}{$filename}{revision} . "\n";
+ } else {
+ print "M Working revision:\tNo entry for $filename\n";
+ }
+ if ( defined($meta->{revision}) )
+ {
+ print "M Repository revision:\t1." . $meta->{revision} . "\t$state->{CVSROOT}/$state->{module}/$filename,v\n";
+ print "M Sticky Tag:\t\t(none)\n";
+ print "M Sticky Date:\t\t(none)\n";
+ print "M Sticky Options:\t\t(none)\n";
+ } else {
+ print "M Repository revision:\tNo revision control file\n";
+ }
+ print "M\n";
+ }
+
+ print "ok\n";
+}
+
+sub req_diff
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit("diff");
+
+ $log->debug("req_diff : " . ( defined($data) ? $data : "[NULL]" ));
+ #$log->debug("status state : " . Dumper($state));
+
+ my ($revision1, $revision2);
+ if ( defined ( $state->{opt}{r} ) and ref $state->{opt}{r} eq "ARRAY" )
+ {
+ $revision1 = $state->{opt}{r}[0];
+ $revision2 = $state->{opt}{r}[1];
+ } else {
+ $revision1 = $state->{opt}{r};
+ }
+
+ $revision1 =~ s/^1\.// if ( defined ( $revision1 ) );
+ $revision2 =~ s/^1\.// if ( defined ( $revision2 ) );
+
+ $log->debug("Diffing revisions " . ( defined($revision1) ? $revision1 : "[NULL]" ) . " and " . ( defined($revision2) ? $revision2 : "[NULL]" ) );
+
+ # Grab a handle to the SQLite db and do any necessary updates
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
+ $updater->update();
+
+ # if no files were specified, we need to work out what files we should be providing status on ...
+ argsfromdir($updater);
+
+ # foreach file specified on the command line ...
+ foreach my $filename ( @{$state->{args}} )
+ {
+ $filename = filecleanup($filename);
+
+ my ( $fh, $file1, $file2, $meta1, $meta2, $filediff );
+
+ my $wrev = revparse($filename);
+
+ # We need _something_ to diff against
+ next unless ( defined ( $wrev ) );
+
+ # if we have a -r switch, use it
+ if ( defined ( $revision1 ) )
+ {
+ ( undef, $file1 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
+ $meta1 = $updater->getmeta($filename, $revision1);
+ unless ( defined ( $meta1 ) and $meta1->{filehash} ne "deleted" )
+ {
+ print "E File $filename at revision 1.$revision1 doesn't exist\n";
+ next;
+ }
+ transmitfile($meta1->{filehash}, { targetfile => $file1 });
+ }
+ # otherwise we just use the working copy revision
+ else
+ {
+ ( undef, $file1 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
+ $meta1 = $updater->getmeta($filename, $wrev);
+ transmitfile($meta1->{filehash}, { targetfile => $file1 });
+ }
+
+ # if we have a second -r switch, use it too
+ if ( defined ( $revision2 ) )
+ {
+ ( undef, $file2 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
+ $meta2 = $updater->getmeta($filename, $revision2);
+
+ unless ( defined ( $meta2 ) and $meta2->{filehash} ne "deleted" )
+ {
+ print "E File $filename at revision 1.$revision2 doesn't exist\n";
+ next;
+ }
+
+ transmitfile($meta2->{filehash}, { targetfile => $file2 });
+ }
+ # otherwise we just use the working copy
+ else
+ {
+ $file2 = $state->{entries}{$filename}{modified_filename};
+ }
+
+ # if we have been given -r, and we don't have a $file2 yet, lets get one
+ if ( defined ( $revision1 ) and not defined ( $file2 ) )
+ {
+ ( undef, $file2 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
+ $meta2 = $updater->getmeta($filename, $wrev);
+ transmitfile($meta2->{filehash}, { targetfile => $file2 });
+ }
+
+ # We need to have retrieved something useful
+ next unless ( defined ( $meta1 ) );
+
+ # Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified
+ next if ( not defined ( $meta2 ) and $wrev == $meta1->{revision}
+ and
+ ( ( $state->{entries}{$filename}{unchanged} and ( not defined ( $state->{entries}{$filename}{conflict} ) or $state->{entries}{$filename}{conflict} !~ /^\+=/ ) )
+ or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $meta1->{filehash} ) )
+ );
+
+ # Apparently we only show diffs for locally modified files
+ next unless ( defined($meta2) or defined ( $state->{entries}{$filename}{modified_filename} ) );
+
+ print "M Index: $filename\n";
+ print "M ===================================================================\n";
+ print "M RCS file: $state->{CVSROOT}/$state->{module}/$filename,v\n";
+ print "M retrieving revision 1.$meta1->{revision}\n" if ( defined ( $meta1 ) );
+ print "M retrieving revision 1.$meta2->{revision}\n" if ( defined ( $meta2 ) );
+ print "M diff ";
+ foreach my $opt ( keys %{$state->{opt}} )
+ {
+ if ( ref $state->{opt}{$opt} eq "ARRAY" )
+ {
+ foreach my $value ( @{$state->{opt}{$opt}} )
+ {
+ print "-$opt $value ";
+ }
+ } else {
+ print "-$opt ";
+ print "$state->{opt}{$opt} " if ( defined ( $state->{opt}{$opt} ) );
+ }
+ }
+ print "$filename\n";
+
+ $log->info("Diffing $filename -r $meta1->{revision} -r " . ( $meta2->{revision} or "workingcopy" ));
+
+ ( $fh, $filediff ) = tempfile ( DIR => $TEMP_DIR );
+
+ if ( exists $state->{opt}{u} )
+ {
+ system("diff -u -L '$filename revision 1.$meta1->{revision}' -L '$filename " . ( defined($meta2->{revision}) ? "revision 1.$meta2->{revision}" : "working copy" ) . "' $file1 $file2 > $filediff");
+ } else {
+ system("diff $file1 $file2 > $filediff");
+ }
+
+ while ( <$fh> )
+ {
+ print "M $_";
+ }
+ close $fh;
+ }
+
+ print "ok\n";
+}
+
+sub req_log
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit("log");
+
+ $log->debug("req_log : " . ( defined($data) ? $data : "[NULL]" ));
+ #$log->debug("log state : " . Dumper($state));
+
+ my ( $minrev, $maxrev );
+ if ( defined ( $state->{opt}{r} ) and $state->{opt}{r} =~ /([\d.]+)?(::?)([\d.]+)?/ )
+ {
+ my $control = $2;
+ $minrev = $1;
+ $maxrev = $3;
+ $minrev =~ s/^1\.// if ( defined ( $minrev ) );
+ $maxrev =~ s/^1\.// if ( defined ( $maxrev ) );
+ $minrev++ if ( defined($minrev) and $control eq "::" );
+ }
+
+ # Grab a handle to the SQLite db and do any necessary updates
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
+ $updater->update();
+
+ # if no files were specified, we need to work out what files we should be providing status on ...
+ argsfromdir($updater);
+
+ # foreach file specified on the command line ...
+ foreach my $filename ( @{$state->{args}} )
+ {
+ $filename = filecleanup($filename);
+
+ my $headmeta = $updater->getmeta($filename);
+
+ my $revisions = $updater->getlog($filename);
+ my $totalrevisions = scalar(@$revisions);
+
+ if ( defined ( $minrev ) )
+ {
+ $log->debug("Removing revisions less than $minrev");
+ while ( scalar(@$revisions) > 0 and $revisions->[-1]{revision} < $minrev )
+ {
+ pop @$revisions;
+ }
+ }
+ if ( defined ( $maxrev ) )
+ {
+ $log->debug("Removing revisions greater than $maxrev");
+ while ( scalar(@$revisions) > 0 and $revisions->[0]{revision} > $maxrev )
+ {
+ shift @$revisions;
+ }
+ }
+
+ next unless ( scalar(@$revisions) );
+
+ print "M \n";
+ print "M RCS file: $state->{CVSROOT}/$state->{module}/$filename,v\n";
+ print "M Working file: $filename\n";
+ print "M head: 1.$headmeta->{revision}\n";
+ print "M branch:\n";
+ print "M locks: strict\n";
+ print "M access list:\n";
+ print "M symbolic names:\n";
+ print "M keyword substitution: kv\n";
+ print "M total revisions: $totalrevisions;\tselected revisions: " . scalar(@$revisions) . "\n";
+ print "M description:\n";
+
+ foreach my $revision ( @$revisions )
+ {
+ print "M ----------------------------\n";
+ print "M revision 1.$revision->{revision}\n";
+ # reformat the date for log output
+ $revision->{modified} = sprintf('%04d/%02d/%02d %s', $3, $DATE_LIST->{$2}, $1, $4 ) if ( $revision->{modified} =~ /(\d+)\s+(\w+)\s+(\d+)\s+(\S+)/ and defined($DATE_LIST->{$2}) );
+ $revision->{author} = cvs_author($revision->{author});
+ print "M date: $revision->{modified}; author: $revision->{author}; state: " . ( $revision->{filehash} eq "deleted" ? "dead" : "Exp" ) . "; lines: +2 -3\n";
+ my $commitmessage = $updater->commitmessage($revision->{commithash});
+ $commitmessage =~ s/^/M /mg;
+ print $commitmessage . "\n";
+ }
+ print "M =============================================================================\n";
+ }
+
+ print "ok\n";
+}
+
+sub req_annotate
+{
+ my ( $cmd, $data ) = @_;
+
+ argsplit("annotate");
+
+ $log->info("req_annotate : " . ( defined($data) ? $data : "[NULL]" ));
+ #$log->debug("status state : " . Dumper($state));
+
+ # Grab a handle to the SQLite db and do any necessary updates
+ my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
+ $updater->update();
+
+ # if no files were specified, we need to work out what files we should be providing annotate on ...
+ argsfromdir($updater);
+
+ # we'll need a temporary checkout dir
+ setupWorkTree();
+
+ $log->info("Temp checkoutdir creation successful, basing annotate session work on '$work->{workDir}', index file is '$ENV{GIT_INDEX_FILE}'");
+
+ # foreach file specified on the command line ...
+ foreach my $filename ( @{$state->{args}} )
+ {
+ $filename = filecleanup($filename);
+
+ my $meta = $updater->getmeta($filename);
+
+ next unless ( $meta->{revision} );
+
+ # get all the commits that this file was in
+ # in dense format -- aka skip dead revisions
+ my $revisions = $updater->gethistorydense($filename);
+ my $lastseenin = $revisions->[0][2];
+
+ # populate the temporary index based on the latest commit were we saw
+ # the file -- but do it cheaply without checking out any files
+ # TODO: if we got a revision from the client, use that instead
+ # to look up the commithash in sqlite (still good to default to
+ # the current head as we do now)
+ system("git", "read-tree", $lastseenin);
+ unless ($? == 0)
+ {
+ print "E error running git-read-tree $lastseenin $ENV{GIT_INDEX_FILE} $!\n";
+ return;
+ }
+ $log->info("Created index '$ENV{GIT_INDEX_FILE}' with commit $lastseenin - exit status $?");
+
+ # do a checkout of the file
+ system('git', 'checkout-index', '-f', '-u', $filename);
+ unless ($? == 0) {
+ print "E error running git-checkout-index -f -u $filename : $!\n";
+ return;
+ }
+
+ $log->info("Annotate $filename");
+
+ # Prepare a file with the commits from the linearized
+ # history that annotate should know about. This prevents
+ # git-jsannotate telling us about commits we are hiding
+ # from the client.
+
+ my $a_hints = "$work->{workDir}/.annotate_hints";
+ if (!open(ANNOTATEHINTS, '>', $a_hints)) {
+ print "E failed to open '$a_hints' for writing: $!\n";
+ return;
+ }
+ for (my $i=0; $i < @$revisions; $i++)
+ {
+ print ANNOTATEHINTS $revisions->[$i][2];
+ if ($i+1 < @$revisions) { # have we got a parent?
+ print ANNOTATEHINTS ' ' . $revisions->[$i+1][2];
+ }
+ print ANNOTATEHINTS "\n";
+ }
+
+ print ANNOTATEHINTS "\n";
+ close ANNOTATEHINTS
+ or (print "E failed to write $a_hints: $!\n"), return;
+
+ my @cmd = (qw(git annotate -l -S), $a_hints, $filename);
+ if (!open(ANNOTATE, "-|", @cmd)) {
+ print "E error invoking ". join(' ',@cmd) .": $!\n";
+ return;
+ }
+ my $metadata = {};
+ print "E Annotations for $filename\n";
+ print "E ***************\n";
+ while ( )
+ {
+ if (m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)
+ {
+ my $commithash = $1;
+ my $data = $2;
+ unless ( defined ( $metadata->{$commithash} ) )
+ {
+ $metadata->{$commithash} = $updater->getmeta($filename, $commithash);
+ $metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});
+ $metadata->{$commithash}{modified} = sprintf("%02d-%s-%02d", $1, $2, $3) if ( $metadata->{$commithash}{modified} =~ /^(\d+)\s(\w+)\s\d\d(\d\d)/ );
+ }
+ printf("M 1.%-5d (%-8s %10s): %s\n",
+ $metadata->{$commithash}{revision},
+ $metadata->{$commithash}{author},
+ $metadata->{$commithash}{modified},
+ $data
+ );
+ } else {
+ $log->warn("Error in annotate output! LINE: $_");
+ print "E Annotate error \n";
+ next;
+ }
+ }
+ close ANNOTATE;
+ }
+
+ # done; get out of the tempdir
+ cleanupWorkTree();
+
+ print "ok\n";
+
+}
+
+# This method takes the state->{arguments} array and produces two new arrays.
+# The first is $state->{args} which is everything before the '--' argument, and
+# the second is $state->{files} which is everything after it.
+sub argsplit
+{
+ $state->{args} = [];
+ $state->{files} = [];
+ $state->{opt} = {};
+
+ return unless( defined($state->{arguments}) and ref $state->{arguments} eq "ARRAY" );
+
+ my $type = shift;
+
+ if ( defined($type) )
+ {
+ my $opt = {};
+ $opt = { A => 0, N => 0, P => 0, R => 0, c => 0, f => 0, l => 0, n => 0, p => 0, s => 0, r => 1, D => 1, d => 1, k => 1, j => 1, } if ( $type eq "co" );
+ $opt = { v => 0, l => 0, R => 0 } if ( $type eq "status" );
+ $opt = { A => 0, P => 0, C => 0, d => 0, f => 0, l => 0, R => 0, p => 0, k => 1, r => 1, D => 1, j => 1, I => 1, W => 1 } if ( $type eq "update" );
+ $opt = { l => 0, R => 0, k => 1, D => 1, D => 1, r => 2 } if ( $type eq "diff" );
+ $opt = { c => 0, R => 0, l => 0, f => 0, F => 1, m => 1, r => 1 } if ( $type eq "ci" );
+ $opt = { k => 1, m => 1 } if ( $type eq "add" );
+ $opt = { f => 0, l => 0, R => 0 } if ( $type eq "remove" );
+ $opt = { l => 0, b => 0, h => 0, R => 0, t => 0, N => 0, S => 0, r => 1, d => 1, s => 1, w => 1 } if ( $type eq "log" );
+
+
+ while ( scalar ( @{$state->{arguments}} ) > 0 )
+ {
+ my $arg = shift @{$state->{arguments}};
+
+ next if ( $arg eq "--" );
+ next unless ( $arg =~ /\S/ );
+
+ # if the argument looks like a switch
+ if ( $arg =~ /^-(\w)(.*)/ )
+ {
+ # if it's a switch that takes an argument
+ if ( $opt->{$1} )
+ {
+ # If this switch has already been provided
+ if ( $opt->{$1} > 1 and exists ( $state->{opt}{$1} ) )
+ {
+ $state->{opt}{$1} = [ $state->{opt}{$1} ];
+ if ( length($2) > 0 )
+ {
+ push @{$state->{opt}{$1}},$2;
+ } else {
+ push @{$state->{opt}{$1}}, shift @{$state->{arguments}};
+ }
+ } else {
+ # if there's extra data in the arg, use that as the argument for the switch
+ if ( length($2) > 0 )
+ {
+ $state->{opt}{$1} = $2;
+ } else {
+ $state->{opt}{$1} = shift @{$state->{arguments}};
+ }
+ }
+ } else {
+ $state->{opt}{$1} = undef;
+ }
+ }
+ else
+ {
+ push @{$state->{args}}, $arg;
+ }
+ }
+ }
+ else
+ {
+ my $mode = 0;
+
+ foreach my $value ( @{$state->{arguments}} )
+ {
+ if ( $value eq "--" )
+ {
+ $mode++;
+ next;
+ }
+ push @{$state->{args}}, $value if ( $mode == 0 );
+ push @{$state->{files}}, $value if ( $mode == 1 );
+ }
+ }
+}
+
+# This method uses $state->{directory} to populate $state->{args} with a list of filenames
+sub argsfromdir
+{
+ my $updater = shift;
+
+ $state->{args} = [] if ( scalar(@{$state->{args}}) == 1 and $state->{args}[0] eq "." );
+
+ return if ( scalar ( @{$state->{args}} ) > 1 );
+
+ my @gethead = @{$updater->gethead};
+
+ # push added files
+ foreach my $file (keys %{$state->{entries}}) {
+ if ( exists $state->{entries}{$file}{revision} &&
+ $state->{entries}{$file}{revision} == 0 )
+ {
+ push @gethead, { name => $file, filehash => 'added' };
+ }
+ }
+
+ if ( scalar(@{$state->{args}}) == 1 )
+ {
+ my $arg = $state->{args}[0];
+ $arg .= $state->{prependdir} if ( defined ( $state->{prependdir} ) );
+
+ $log->info("Only one arg specified, checking for directory expansion on '$arg'");
+
+ foreach my $file ( @gethead )
+ {
+ next if ( $file->{filehash} eq "deleted" and not defined ( $state->{entries}{$file->{name}} ) );
+ next unless ( $file->{name} =~ /^$arg\// or $file->{name} eq $arg );
+ push @{$state->{args}}, $file->{name};
+ }
+
+ shift @{$state->{args}} if ( scalar(@{$state->{args}}) > 1 );
+ } else {
+ $log->info("Only one arg specified, populating file list automatically");
+
+ $state->{args} = [];
+
+ foreach my $file ( @gethead )
+ {
+ next if ( $file->{filehash} eq "deleted" and not defined ( $state->{entries}{$file->{name}} ) );
+ next unless ( $file->{name} =~ s/^$state->{prependdir}// );
+ push @{$state->{args}}, $file->{name};
+ }
+ }
+}
+
+# This method cleans up the $state variable after a command that uses arguments has run
+sub statecleanup
+{
+ $state->{files} = [];
+ $state->{args} = [];
+ $state->{arguments} = [];
+ $state->{entries} = {};
+}
+
+sub revparse
+{
+ my $filename = shift;
+
+ return undef unless ( defined ( $state->{entries}{$filename}{revision} ) );
+
+ return $1 if ( $state->{entries}{$filename}{revision} =~ /^1\.(\d+)/ );
+ return -$1 if ( $state->{entries}{$filename}{revision} =~ /^-1\.(\d+)/ );
+
+ return undef;
+}
+
+# This method takes a file hash and does a CVS "file transfer". Its
+# exact behaviour depends on a second, optional hash table argument:
+# - If $options->{targetfile}, dump the contents to that file;
+# - If $options->{print}, use M/MT to transmit the contents one line
+# at a time;
+# - Otherwise, transmit the size of the file, followed by the file
+# contents.
+sub transmitfile
+{
+ my $filehash = shift;
+ my $options = shift;
+
+ if ( defined ( $filehash ) and $filehash eq "deleted" )
+ {
+ $log->warn("filehash is 'deleted'");
+ return;
+ }
+
+ die "Need filehash" unless ( defined ( $filehash ) and $filehash =~ /^[a-zA-Z0-9]{40}$/ );
+
+ my $type = `git cat-file -t $filehash`;
+ chomp $type;
+
+ die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ( $type ) and $type eq "blob" );
+
+ my $size = `git cat-file -s $filehash`;
+ chomp $size;
+
+ $log->debug("transmitfile($filehash) size=$size, type=$type");
+
+ if ( open my $fh, '-|', "git", "cat-file", "blob", $filehash )
+ {
+ if ( defined ( $options->{targetfile} ) )
+ {
+ my $targetfile = $options->{targetfile};
+ open NEWFILE, ">", $targetfile or die("Couldn't open '$targetfile' for writing : $!");
+ print NEWFILE $_ while ( <$fh> );
+ close NEWFILE or die("Failed to write '$targetfile': $!");
+ } elsif ( defined ( $options->{print} ) && $options->{print} ) {
+ while ( <$fh> ) {
+ if( /\n\z/ ) {
+ print 'M ', $_;
+ } else {
+ print 'MT text ', $_, "\n";
+ }
+ }
+ } else {
+ print "$size\n";
+ print while ( <$fh> );
+ }
+ close $fh or die ("Couldn't close filehandle for transmitfile(): $!");
+ } else {
+ die("Couldn't execute git-cat-file");
+ }
+}
+
+# This method takes a file name, and returns ( $dirpart, $filepart ) which
+# refers to the directory portion and the file portion of the filename
+# respectively
+sub filenamesplit
+{
+ my $filename = shift;
+ my $fixforlocaldir = shift;
+
+ my ( $filepart, $dirpart ) = ( $filename, "." );
+ ( $filepart, $dirpart ) = ( $2, $1 ) if ( $filename =~ /(.*)\/(.*)/ );
+ $dirpart .= "/";
+
+ if ( $fixforlocaldir )
+ {
+ $dirpart =~ s/^$state->{prependdir}//;
+ }
+
+ return ( $filepart, $dirpart );
+}
+
+sub filecleanup
+{
+ my $filename = shift;
+
+ return undef unless(defined($filename));
+ if ( $filename =~ /^\// )
+ {
+ print "E absolute filenames '$filename' not supported by server\n";
+ return undef;
+ }
+
+ $filename =~ s/^\.\///g;
+ $filename = $state->{prependdir} . $filename;
+ return $filename;
+}
+
+sub validateGitDir
+{
+ if( !defined($state->{CVSROOT}) )
+ {
+ print "error 1 CVSROOT not specified\n";
+ cleanupWorkTree();
+ exit;
+ }
+ if( $ENV{GIT_DIR} ne ($state->{CVSROOT} . '/') )
+ {
+ print "error 1 Internally inconsistent CVSROOT\n";
+ cleanupWorkTree();
+ exit;
+ }
+}
+
+# Setup working directory in a work tree with the requested version
+# loaded in the index.
+sub setupWorkTree
+{
+ my ($ver) = @_;
+
+ validateGitDir();
+
+ if( ( defined($work->{state}) && $work->{state} != 1 ) ||
+ defined($work->{tmpDir}) )
+ {
+ $log->warn("Bad work tree state management");
+ print "error 1 Internal setup multiple work trees without cleanup\n";
+ cleanupWorkTree();
+ exit;
+ }
+
+ $work->{workDir} = tempdir ( DIR => $TEMP_DIR );
+
+ if( !defined($work->{index}) )
+ {
+ (undef, $work->{index}) = tempfile ( DIR => $TEMP_DIR, OPEN => 0 );
+ }
+
+ chdir $work->{workDir} or
+ die "Unable to chdir to $work->{workDir}\n";
+
+ $log->info("Setting up GIT_WORK_TREE as '.' in '$work->{workDir}', index file is '$work->{index}'");
+
+ $ENV{GIT_WORK_TREE} = ".";
+ $ENV{GIT_INDEX_FILE} = $work->{index};
+ $work->{state} = 2;
+
+ if($ver)
+ {
+ system("git","read-tree",$ver);
+ unless ($? == 0)
+ {
+ $log->warn("Error running git-read-tree");
+ die "Error running git-read-tree $ver in $work->{workDir} $!\n";
+ }
+ }
+ # else # req_annotate reads tree for each file
+}
+
+# Ensure current directory is in some kind of working directory,
+# with a recent version loaded in the index.
+sub ensureWorkTree
+{
+ if( defined($work->{tmpDir}) )
+ {
+ $log->warn("Bad work tree state management [ensureWorkTree()]");
+ print "error 1 Internal setup multiple dirs without cleanup\n";
+ cleanupWorkTree();
+ exit;
+ }
+ if( $work->{state} )
+ {
+ return;
+ }
+
+ validateGitDir();
+
+ if( !defined($work->{emptyDir}) )
+ {
+ $work->{emptyDir} = tempdir ( DIR => $TEMP_DIR, OPEN => 0);
+ }
+ chdir $work->{emptyDir} or
+ die "Unable to chdir to $work->{emptyDir}\n";
+
+ my $ver = `git show-ref -s refs/heads/$state->{module}`;
+ chomp $ver;
+ if ($ver !~ /^[0-9a-f]{40}$/)
+ {
+ $log->warn("Error from git show-ref -s refs/head$state->{module}");
+ print "error 1 cannot find the current HEAD of module";
+ cleanupWorkTree();
+ exit;
+ }
+
+ if( !defined($work->{index}) )
+ {
+ (undef, $work->{index}) = tempfile ( DIR => $TEMP_DIR, OPEN => 0 );
+ }
+
+ $ENV{GIT_WORK_TREE} = ".";
+ $ENV{GIT_INDEX_FILE} = $work->{index};
+ $work->{state} = 1;
+
+ system("git","read-tree",$ver);
+ unless ($? == 0)
+ {
+ die "Error running git-read-tree $ver $!\n";
+ }
+}
+
+# Cleanup working directory that is not needed any longer.
+sub cleanupWorkTree
+{
+ if( ! $work->{state} )
+ {
+ return;
+ }
+
+ chdir "/" or die "Unable to chdir '/'\n";
+
+ if( defined($work->{workDir}) )
+ {
+ rmtree( $work->{workDir} );
+ undef $work->{workDir};
+ }
+ undef $work->{state};
+}
+
+# Setup a temporary directory (not a working tree), typically for
+# merging dirty state as in req_update.
+sub setupTmpDir
+{
+ $work->{tmpDir} = tempdir ( DIR => $TEMP_DIR );
+ chdir $work->{tmpDir} or die "Unable to chdir $work->{tmpDir}\n";
+
+ return $work->{tmpDir};
+}
+
+# Clean up a previously setupTmpDir. Restore previous work tree if
+# appropriate.
+sub cleanupTmpDir
+{
+ if ( !defined($work->{tmpDir}) )
+ {
+ $log->warn("cleanup tmpdir that has not been setup");
+ die "Cleanup tmpDir that has not been setup\n";
+ }
+ if( defined($work->{state}) )
+ {
+ if( $work->{state} == 1 )
+ {
+ chdir $work->{emptyDir} or
+ die "Unable to chdir to $work->{emptyDir}\n";
+ }
+ elsif( $work->{state} == 2 )
+ {
+ chdir $work->{workDir} or
+ die "Unable to chdir to $work->{emptyDir}\n";
+ }
+ else
+ {
+ $log->warn("Inconsistent work dir state");
+ die "Inconsistent work dir state\n";
+ }
+ }
+ else
+ {
+ chdir "/" or die "Unable to chdir '/'\n";
+ }
+}
+
+# Given a path, this function returns a string containing the kopts
+# that should go into that path's Entries line. For example, a binary
+# file should get -kb.
+sub kopts_from_path
+{
+ my ($path, $srcType, $name) = @_;
+
+ if ( defined ( $cfg->{gitcvs}{usecrlfattr} ) and
+ $cfg->{gitcvs}{usecrlfattr} =~ /\s*(1|true|yes)\s*$/i )
+ {
+ my ($val) = check_attr( "text", $path );
+ if ( $val eq "unspecified" )
+ {
+ $val = check_attr( "crlf", $path );
+ }
+ if ( $val eq "unset" )
+ {
+ return "-kb"
+ }
+ elsif ( check_attr( "eol", $path ) ne "unspecified" ||
+ $val eq "set" || $val eq "input" )
+ {
+ return "";
+ }
+ else
+ {
+ $log->info("Unrecognized check_attr crlf $path : $val");
+ }
+ }
+
+ if ( defined ( $cfg->{gitcvs}{allbinary} ) )
+ {
+ if( ($cfg->{gitcvs}{allbinary} =~ /^\s*(1|true|yes)\s*$/i) )
+ {
+ return "-kb";
+ }
+ elsif( ($cfg->{gitcvs}{allbinary} =~ /^\s*guess\s*$/i) )
+ {
+ if( $srcType eq "sha1Or-k" &&
+ !defined($name) )
+ {
+ my ($ret)=$state->{entries}{$path}{options};
+ if( !defined($ret) )
+ {
+ $ret=$state->{opt}{k};
+ if(defined($ret))
+ {
+ $ret="-k$ret";
+ }
+ else
+ {
+ $ret="";
+ }
+ }
+ if( ! ($ret=~/^(|-kb|-kkv|-kkvl|-kk|-ko|-kv)$/) )
+ {
+ print "E Bad -k option\n";
+ $log->warn("Bad -k option: $ret");
+ die "Error: Bad -k option: $ret\n";
+ }
+
+ return $ret;
+ }
+ else
+ {
+ if( is_binary($srcType,$name) )
+ {
+ $log->debug("... as binary");
+ return "-kb";
+ }
+ else
+ {
+ $log->debug("... as text");
+ }
+ }
+ }
+ }
+ # Return "" to give no special treatment to any path
+ return "";
+}
+
+sub check_attr
+{
+ my ($attr,$path) = @_;
+ ensureWorkTree();
+ if ( open my $fh, '-|', "git", "check-attr", $attr, "--", $path )
+ {
+ my $val = <$fh>;
+ close $fh;
+ $val =~ s/.*: ([^:\r\n]*)\s*$/$1/;
+ return $val;
+ }
+ else
+ {
+ return undef;
+ }
+}
+
+# This should have the same heuristics as convert.c:is_binary() and related.
+# Note that the bare CR test is done by callers in convert.c.
+sub is_binary
+{
+ my ($srcType,$name) = @_;
+ $log->debug("is_binary($srcType,$name)");
+
+ # Minimize amount of interpreted code run in the inner per-character
+ # loop for large files, by totalling each character value and
+ # then analyzing the totals.
+ my @counts;
+ my $i;
+ for($i=0;$i<256;$i++)
+ {
+ $counts[$i]=0;
+ }
+
+ my $fh = open_blob_or_die($srcType,$name);
+ my $line;
+ while( defined($line=<$fh>) )
+ {
+ # Any '\0' and bare CR are considered binary.
+ if( $line =~ /\0|(\r[^\n])/ )
+ {
+ close($fh);
+ return 1;
+ }
+
+ # Count up each character in the line:
+ my $len=length($line);
+ for($i=0;$i<$len;$i++)
+ {
+ $counts[ord(substr($line,$i,1))]++;
+ }
+ }
+ close $fh;
+
+ # Don't count CR and LF as either printable/nonprintable
+ $counts[ord("\n")]=0;
+ $counts[ord("\r")]=0;
+
+ # Categorize individual character count into printable and nonprintable:
+ my $printable=0;
+ my $nonprintable=0;
+ for($i=0;$i<256;$i++)
+ {
+ if( $i < 32 &&
+ $i != ord("\b") &&
+ $i != ord("\t") &&
+ $i != 033 && # ESC
+ $i != 014 ) # FF
+ {
+ $nonprintable+=$counts[$i];
+ }
+ elsif( $i==127 ) # DEL
+ {
+ $nonprintable+=$counts[$i];
+ }
+ else
+ {
+ $printable+=$counts[$i];
+ }
+ }
+
+ return ($printable >> 7) < $nonprintable;
+}
+
+# Returns open file handle. Possible invocations:
+# - open_blob_or_die("file",$filename);
+# - open_blob_or_die("sha1",$filehash);
+sub open_blob_or_die
+{
+ my ($srcType,$name) = @_;
+ my ($fh);
+ if( $srcType eq "file" )
+ {
+ if( !open $fh,"<",$name )
+ {
+ $log->warn("Unable to open file $name: $!");
+ die "Unable to open file $name: $!\n";
+ }
+ }
+ elsif( $srcType eq "sha1" || $srcType eq "sha1Or-k" )
+ {
+ unless ( defined ( $name ) and $name =~ /^[a-zA-Z0-9]{40}$/ )
+ {
+ $log->warn("Need filehash");
+ die "Need filehash\n";
+ }
+
+ my $type = `git cat-file -t $name`;
+ chomp $type;
+
+ unless ( defined ( $type ) and $type eq "blob" )
+ {
+ $log->warn("Invalid type '$type' for '$name'");
+ die ( "Invalid type '$type' (expected 'blob')" )
+ }
+
+ my $size = `git cat-file -s $name`;
+ chomp $size;
+
+ $log->debug("open_blob_or_die($name) size=$size, type=$type");
+
+ unless( open $fh, '-|', "git", "cat-file", "blob", $name )
+ {
+ $log->warn("Unable to open sha1 $name");
+ die "Unable to open sha1 $name\n";
+ }
+ }
+ else
+ {
+ $log->warn("Unknown type of blob source: $srcType");
+ die "Unknown type of blob source: $srcType\n";
+ }
+ return $fh;
+}
+
+# Generate a CVS author name from Git author information, by taking the local
+# part of the email address and replacing characters not in the Portable
+# Filename Character Set (see IEEE Std 1003.1-2001, 3.276) by underscores. CVS
+# Login names are Unix login names, which should be restricted to this
+# character set.
+sub cvs_author
+{
+ my $author_line = shift;
+ (my $author) = $author_line =~ /<([^@>]*)/;
+
+ $author =~ s/[^-a-zA-Z0-9_.]/_/g;
+ $author =~ s/^-/_/;
+
+ $author;
+}
+
+
+sub descramble
+{
+ # This table is from src/scramble.c in the CVS source
+ my @SHIFTS = (
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+ 114,120, 53, 79, 96,109, 72,108, 70, 64, 76, 67,116, 74, 68, 87,
+ 111, 52, 75,119, 49, 34, 82, 81, 95, 65,112, 86,118,110,122,105,
+ 41, 57, 83, 43, 46,102, 40, 89, 38,103, 45, 50, 42,123, 91, 35,
+ 125, 55, 54, 66,124,126, 59, 47, 92, 71,115, 78, 88,107,106, 56,
+ 36,121,117,104,101,100, 69, 73, 99, 63, 94, 93, 39, 37, 61, 48,
+ 58,113, 32, 90, 44, 98, 60, 51, 33, 97, 62, 77, 84, 80, 85,223,
+ 225,216,187,166,229,189,222,188,141,249,148,200,184,136,248,190,
+ 199,170,181,204,138,232,218,183,255,234,220,247,213,203,226,193,
+ 174,172,228,252,217,201,131,230,197,211,145,238,161,179,160,212,
+ 207,221,254,173,202,146,224,151,140,196,205,130,135,133,143,246,
+ 192,159,244,239,185,168,215,144,139,165,180,157,147,186,214,176,
+ 227,231,219,169,175,156,206,198,129,164,150,210,154,177,134,127,
+ 182,128,158,208,162,132,167,209,149,241,153,251,237,236,171,195,
+ 243,233,253,240,194,250,191,155,142,137,245,235,163,242,178,152
+ );
+ my ($str) = @_;
+
+ # This should never happen, the same password format (A) has been
+ # used by CVS since the beginning of time
+ {
+ my $fmt = substr($str, 0, 1);
+ die "invalid password format `$fmt'" unless $fmt eq 'A';
+ }
+
+ my @str = unpack "C*", substr($str, 1);
+ my $ret = join '', map { chr $SHIFTS[$_] } @str;
+ return $ret;
+}
+
+
+package GITCVS::log;
+
+####
+#### Copyright The Open University UK - 2006.
+####
+#### Authors: Martyn Smith
+#### Martin Langhoff
+####
+####
+
+use strict;
+use warnings;
+
+=head1 NAME
+
+GITCVS::log
+
+=head1 DESCRIPTION
+
+This module provides very crude logging with a similar interface to
+Log::Log4perl
+
+=head1 METHODS
+
+=cut
+
+=head2 new
+
+Creates a new log object, optionally you can specify a filename here to
+indicate the file to log to. If no log file is specified, you can specify one
+later with method setfile, or indicate you no longer want logging with method
+nofile.
+
+Until one of these methods is called, all log calls will buffer messages ready
+to write out.
+
+=cut
+sub new
+{
+ my $class = shift;
+ my $filename = shift;
+
+ my $self = {};
+
+ bless $self, $class;
+
+ if ( defined ( $filename ) )
+ {
+ open $self->{fh}, ">>", $filename or die("Couldn't open '$filename' for writing : $!");
+ }
+
+ return $self;
+}
+
+=head2 setfile
+
+This methods takes a filename, and attempts to open that file as the log file.
+If successful, all buffered data is written out to the file, and any further
+logging is written directly to the file.
+
+=cut
+sub setfile
+{
+ my $self = shift;
+ my $filename = shift;
+
+ if ( defined ( $filename ) )
+ {
+ open $self->{fh}, ">>", $filename or die("Couldn't open '$filename' for writing : $!");
+ }
+
+ return unless ( defined ( $self->{buffer} ) and ref $self->{buffer} eq "ARRAY" );
+
+ while ( my $line = shift @{$self->{buffer}} )
+ {
+ print {$self->{fh}} $line;
+ }
+}
+
+=head2 nofile
+
+This method indicates no logging is going to be used. It flushes any entries in
+the internal buffer, and sets a flag to ensure no further data is put there.
+
+=cut
+sub nofile
+{
+ my $self = shift;
+
+ $self->{nolog} = 1;
+
+ return unless ( defined ( $self->{buffer} ) and ref $self->{buffer} eq "ARRAY" );
+
+ $self->{buffer} = [];
+}
+
+=head2 _logopen
+
+Internal method. Returns true if the log file is open, false otherwise.
+
+=cut
+sub _logopen
+{
+ my $self = shift;
+
+ return 1 if ( defined ( $self->{fh} ) and ref $self->{fh} eq "GLOB" );
+ return 0;
+}
+
+=head2 debug info warn fatal
+
+These four methods are wrappers to _log. They provide the actual interface for
+logging data.
+
+=cut
+sub debug { my $self = shift; $self->_log("debug", @_); }
+sub info { my $self = shift; $self->_log("info" , @_); }
+sub warn { my $self = shift; $self->_log("warn" , @_); }
+sub fatal { my $self = shift; $self->_log("fatal", @_); }
+
+=head2 _log
+
+This is an internal method called by the logging functions. It generates a
+timestamp and pushes the logged line either to file, or internal buffer.
+
+=cut
+sub _log
+{
+ my $self = shift;
+ my $level = shift;
+
+ return if ( $self->{nolog} );
+
+ my @time = localtime;
+ my $timestring = sprintf("%4d-%02d-%02d %02d:%02d:%02d : %-5s",
+ $time[5] + 1900,
+ $time[4] + 1,
+ $time[3],
+ $time[2],
+ $time[1],
+ $time[0],
+ uc $level,
+ );
+
+ if ( $self->_logopen )
+ {
+ print {$self->{fh}} $timestring . " - " . join(" ",@_) . "\n";
+ } else {
+ push @{$self->{buffer}}, $timestring . " - " . join(" ",@_) . "\n";
+ }
+}
+
+=head2 DESTROY
+
+This method simply closes the file handle if one is open
+
+=cut
+sub DESTROY
+{
+ my $self = shift;
+
+ if ( $self->_logopen )
+ {
+ close $self->{fh};
+ }
+}
+
+package GITCVS::updater;
+
+####
+#### Copyright The Open University UK - 2006.
+####
+#### Authors: Martyn Smith
+#### Martin Langhoff
+####
+####
+
+use strict;
+use warnings;
+use DBI;
+
+=head1 METHODS
+
+=cut
+
+=head2 new
+
+=cut
+sub new
+{
+ my $class = shift;
+ my $config = shift;
+ my $module = shift;
+ my $log = shift;
+
+ die "Need to specify a git repository" unless ( defined($config) and -d $config );
+ die "Need to specify a module" unless ( defined($module) );
+
+ $class = ref($class) || $class;
+
+ my $self = {};
+
+ bless $self, $class;
+
+ $self->{valid_tables} = {'revision' => 1,
+ 'revision_ix1' => 1,
+ 'revision_ix2' => 1,
+ 'head' => 1,
+ 'head_ix1' => 1,
+ 'properties' => 1,
+ 'commitmsgs' => 1};
+
+ $self->{module} = $module;
+ $self->{git_path} = $config . "/";
+
+ $self->{log} = $log;
+
+ die "Git repo '$self->{git_path}' doesn't exist" unless ( -d $self->{git_path} );
+
+ $self->{dbdriver} = $cfg->{gitcvs}{$state->{method}}{dbdriver} ||
+ $cfg->{gitcvs}{dbdriver} || "SQLite";
+ $self->{dbname} = $cfg->{gitcvs}{$state->{method}}{dbname} ||
+ $cfg->{gitcvs}{dbname} || "%Ggitcvs.%m.sqlite";
+ $self->{dbuser} = $cfg->{gitcvs}{$state->{method}}{dbuser} ||
+ $cfg->{gitcvs}{dbuser} || "";
+ $self->{dbpass} = $cfg->{gitcvs}{$state->{method}}{dbpass} ||
+ $cfg->{gitcvs}{dbpass} || "";
+ $self->{dbtablenameprefix} = $cfg->{gitcvs}{$state->{method}}{dbtablenameprefix} ||
+ $cfg->{gitcvs}{dbtablenameprefix} || "";
+ my %mapping = ( m => $module,
+ a => $state->{method},
+ u => getlogin || getpwuid($<) || $<,
+ G => $self->{git_path},
+ g => mangle_dirname($self->{git_path}),
+ );
+ $self->{dbname} =~ s/%([mauGg])/$mapping{$1}/eg;
+ $self->{dbuser} =~ s/%([mauGg])/$mapping{$1}/eg;
+ $self->{dbtablenameprefix} =~ s/%([mauGg])/$mapping{$1}/eg;
+ $self->{dbtablenameprefix} = mangle_tablename($self->{dbtablenameprefix});
+
+ die "Invalid char ':' in dbdriver" if $self->{dbdriver} =~ /:/;
+ die "Invalid char ';' in dbname" if $self->{dbname} =~ /;/;
+ $self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",
+ $self->{dbuser},
+ $self->{dbpass});
+ die "Error connecting to database\n" unless defined $self->{dbh};
+
+ $self->{tables} = {};
+ foreach my $table ( keys %{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )
+ {
+ $self->{tables}{$table} = 1;
+ }
+
+ # Construct the revision table if required
+ unless ( $self->{tables}{$self->tablename("revision")} )
+ {
+ my $tablename = $self->tablename("revision");
+ my $ix1name = $self->tablename("revision_ix1");
+ my $ix2name = $self->tablename("revision_ix2");
+ $self->{dbh}->do("
+ CREATE TABLE $tablename (
+ name TEXT NOT NULL,
+ revision INTEGER NOT NULL,
+ filehash TEXT NOT NULL,
+ commithash TEXT NOT NULL,
+ author TEXT NOT NULL,
+ modified TEXT NOT NULL,
+ mode TEXT NOT NULL
+ )
+ ");
+ $self->{dbh}->do("
+ CREATE INDEX $ix1name
+ ON $tablename (name,revision)
+ ");
+ $self->{dbh}->do("
+ CREATE INDEX $ix2name
+ ON $tablename (name,commithash)
+ ");
+ }
+
+ # Construct the head table if required
+ unless ( $self->{tables}{$self->tablename("head")} )
+ {
+ my $tablename = $self->tablename("head");
+ my $ix1name = $self->tablename("head_ix1");
+ $self->{dbh}->do("
+ CREATE TABLE $tablename (
+ name TEXT NOT NULL,
+ revision INTEGER NOT NULL,
+ filehash TEXT NOT NULL,
+ commithash TEXT NOT NULL,
+ author TEXT NOT NULL,
+ modified TEXT NOT NULL,
+ mode TEXT NOT NULL
+ )
+ ");
+ $self->{dbh}->do("
+ CREATE INDEX $ix1name
+ ON $tablename (name)
+ ");
+ }
+
+ # Construct the properties table if required
+ unless ( $self->{tables}{$self->tablename("properties")} )
+ {
+ my $tablename = $self->tablename("properties");
+ $self->{dbh}->do("
+ CREATE TABLE $tablename (
+ key TEXT NOT NULL PRIMARY KEY,
+ value TEXT
+ )
+ ");
+ }
+
+ # Construct the commitmsgs table if required
+ unless ( $self->{tables}{$self->tablename("commitmsgs")} )
+ {
+ my $tablename = $self->tablename("commitmsgs");
+ $self->{dbh}->do("
+ CREATE TABLE $tablename (
+ key TEXT NOT NULL PRIMARY KEY,
+ value TEXT
+ )
+ ");
+ }
+
+ return $self;
+}
+
+=head2 tablename
+
+=cut
+sub tablename
+{
+ my $self = shift;
+ my $name = shift;
+
+ if (exists $self->{valid_tables}{$name}) {
+ return $self->{dbtablenameprefix} . $name;
+ } else {
+ return undef;
+ }
+}
+
+=head2 update
+
+=cut
+sub update
+{
+ my $self = shift;
+
+ # first lets get the commit list
+ $ENV{GIT_DIR} = $self->{git_path};
+
+ my $commitsha1 = `git rev-parse $self->{module}`;
+ chomp $commitsha1;
+
+ my $commitinfo = `git cat-file commit $self->{module} 2>&1`;
+ unless ( $commitinfo =~ /tree\s+[a-zA-Z0-9]{40}/ )
+ {
+ die("Invalid module '$self->{module}'");
+ }
+
+
+ my $git_log;
+ my $lastcommit = $self->_get_prop("last_commit");
+
+ if (defined $lastcommit && $lastcommit eq $commitsha1) { # up-to-date
+ return 1;
+ }
+
+ # Start exclusive lock here...
+ $self->{dbh}->begin_work() or die "Cannot lock database for BEGIN";
+
+ # TODO: log processing is memory bound
+ # if we can parse into a 2nd file that is in reverse order
+ # we can probably do something really efficient
+ my @git_log_params = ('--pretty', '--parents', '--topo-order');
+
+ if (defined $lastcommit) {
+ push @git_log_params, "$lastcommit..$self->{module}";
+ } else {
+ push @git_log_params, $self->{module};
+ }
+ # git-rev-list is the backend / plumbing version of git-log
+ open(GITLOG, '-|', 'git', 'rev-list', @git_log_params) or die "Cannot call git-rev-list: $!";
+
+ my @commits;
+
+ my %commit = ();
+
+ while ( )
+ {
+ chomp;
+ if (m/^commit\s+(.*)$/) {
+ # on ^commit lines put the just seen commit in the stack
+ # and prime things for the next one
+ if (keys %commit) {
+ my %copy = %commit;
+ unshift @commits, \%copy;
+ %commit = ();
+ }
+ my @parents = split(m/\s+/, $1);
+ $commit{hash} = shift @parents;
+ $commit{parents} = \@parents;
+ } elsif (m/^(\w+?):\s+(.*)$/ && !exists($commit{message})) {
+ # on rfc822-like lines seen before we see any message,
+ # lowercase the entry and put it in the hash as key-value
+ $commit{lc($1)} = $2;
+ } else {
+ # message lines - skip initial empty line
+ # and trim whitespace
+ if (!exists($commit{message}) && m/^\s*$/) {
+ # define it to mark the end of headers
+ $commit{message} = '';
+ next;
+ }
+ s/^\s+//; s/\s+$//; # trim ws
+ $commit{message} .= $_ . "\n";
+ }
+ }
+ close GITLOG;
+
+ unshift @commits, \%commit if ( keys %commit );
+
+ # Now all the commits are in the @commits bucket
+ # ordered by time DESC. for each commit that needs processing,
+ # determine whether it's following the last head we've seen or if
+ # it's on its own branch, grab a file list, and add whatever's changed
+ # NOTE: $lastcommit refers to the last commit from previous run
+ # $lastpicked is the last commit we picked in this run
+ my $lastpicked;
+ my $head = {};
+ if (defined $lastcommit) {
+ $lastpicked = $lastcommit;
+ }
+
+ my $committotal = scalar(@commits);
+ my $commitcount = 0;
+
+ # Load the head table into $head (for cached lookups during the update process)
+ foreach my $file ( @{$self->gethead()} )
+ {
+ $head->{$file->{name}} = $file;
+ }
+
+ foreach my $commit ( @commits )
+ {
+ $self->{log}->debug("GITCVS::updater - Processing commit $commit->{hash} (" . (++$commitcount) . " of $committotal)");
+ if (defined $lastpicked)
+ {
+ if (!in_array($lastpicked, @{$commit->{parents}}))
+ {
+ # skip, we'll see this delta
+ # as part of a merge later
+ # warn "skipping off-track $commit->{hash}\n";
+ next;
+ } elsif (@{$commit->{parents}} > 1) {
+ # it is a merge commit, for each parent that is
+ # not $lastpicked, see if we can get a log
+ # from the merge-base to that parent to put it
+ # in the message as a merge summary.
+ my @parents = @{$commit->{parents}};
+ foreach my $parent (@parents) {
+ # git-merge-base can potentially (but rarely) throw
+ # several candidate merge bases. let's assume
+ # that the first one is the best one.
+ if ($parent eq $lastpicked) {
+ next;
+ }
+ my $base = eval {
+ safe_pipe_capture('git', 'merge-base',
+ $lastpicked, $parent);
+ };
+ # The two branches may not be related at all,
+ # in which case merge base simply fails to find
+ # any, but that's Ok.
+ next if ($@);
+
+ chomp $base;
+ if ($base) {
+ my @merged;
+ # print "want to log between $base $parent \n";
+ open(GITLOG, '-|', 'git', 'log', '--pretty=medium', "$base..$parent")
+ or die "Cannot call git-log: $!";
+ my $mergedhash;
+ while () {
+ chomp;
+ if (!defined $mergedhash) {
+ if (m/^commit\s+(.+)$/) {
+ $mergedhash = $1;
+ } else {
+ next;
+ }
+ } else {
+ # grab the first line that looks non-rfc822
+ # aka has content after leading space
+ if (m/^\s+(\S.*)$/) {
+ my $title = $1;
+ $title = substr($title,0,100); # truncate
+ unshift @merged, "$mergedhash $title";
+ undef $mergedhash;
+ }
+ }
+ }
+ close GITLOG;
+ if (@merged) {
+ $commit->{mergemsg} = $commit->{message};
+ $commit->{mergemsg} .= "\nSummary of merged commits:\n\n";
+ foreach my $summary (@merged) {
+ $commit->{mergemsg} .= "\t$summary\n";
+ }
+ $commit->{mergemsg} .= "\n\n";
+ # print "Message for $commit->{hash} \n$commit->{mergemsg}";
+ }
+ }
+ }
+ }
+ }
+
+ # convert the date to CVS-happy format
+ $commit->{date} = "$2 $1 $4 $3 $5" if ( $commit->{date} =~ /^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/ );
+
+ if ( defined ( $lastpicked ) )
+ {
+ my $filepipe = open(FILELIST, '-|', 'git', 'diff-tree', '-z', '-r', $lastpicked, $commit->{hash}) or die("Cannot call git-diff-tree : $!");
+ local ($/) = "\0";
+ while ( )
+ {
+ chomp;
+ unless ( /^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o )
+ {
+ die("Couldn't process git-diff-tree line : $_");
+ }
+ my ($mode, $hash, $change) = ($1, $2, $3);
+ my $name = ;
+ chomp($name);
+
+ # $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");
+
+ my $git_perms = "";
+ $git_perms .= "r" if ( $mode & 4 );
+ $git_perms .= "w" if ( $mode & 2 );
+ $git_perms .= "x" if ( $mode & 1 );
+ $git_perms = "rw" if ( $git_perms eq "" );
+
+ if ( $change eq "D" )
+ {
+ #$log->debug("DELETE $name");
+ $head->{$name} = {
+ name => $name,
+ revision => $head->{$name}{revision} + 1,
+ filehash => "deleted",
+ commithash => $commit->{hash},
+ modified => $commit->{date},
+ author => $commit->{author},
+ mode => $git_perms,
+ };
+ $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
+ }
+ elsif ( $change eq "M" || $change eq "T" )
+ {
+ #$log->debug("MODIFIED $name");
+ $head->{$name} = {
+ name => $name,
+ revision => $head->{$name}{revision} + 1,
+ filehash => $hash,
+ commithash => $commit->{hash},
+ modified => $commit->{date},
+ author => $commit->{author},
+ mode => $git_perms,
+ };
+ $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
+ }
+ elsif ( $change eq "A" )
+ {
+ #$log->debug("ADDED $name");
+ $head->{$name} = {
+ name => $name,
+ revision => $head->{$name}{revision} ? $head->{$name}{revision}+1 : 1,
+ filehash => $hash,
+ commithash => $commit->{hash},
+ modified => $commit->{date},
+ author => $commit->{author},
+ mode => $git_perms,
+ };
+ $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
+ }
+ else
+ {
+ $log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");
+ die;
+ }
+ }
+ close FILELIST;
+ } else {
+ # this is used to detect files removed from the repo
+ my $seen_files = {};
+
+ my $filepipe = open(FILELIST, '-|', 'git', 'ls-tree', '-z', '-r', $commit->{hash}) or die("Cannot call git-ls-tree : $!");
+ local $/ = "\0";
+ while ( )
+ {
+ chomp;
+ unless ( /^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o )
+ {
+ die("Couldn't process git-ls-tree line : $_");
+ }
+
+ my ( $git_perms, $git_type, $git_hash, $git_filename ) = ( $1, $2, $3, $4 );
+
+ $seen_files->{$git_filename} = 1;
+
+ my ( $oldhash, $oldrevision, $oldmode ) = (
+ $head->{$git_filename}{filehash},
+ $head->{$git_filename}{revision},
+ $head->{$git_filename}{mode}
+ );
+
+ if ( $git_perms =~ /^\d\d\d(\d)\d\d/o )
+ {
+ $git_perms = "";
+ $git_perms .= "r" if ( $1 & 4 );
+ $git_perms .= "w" if ( $1 & 2 );
+ $git_perms .= "x" if ( $1 & 1 );
+ } else {
+ $git_perms = "rw";
+ }
+
+ # unless the file exists with the same hash, we need to update it ...
+ unless ( defined($oldhash) and $oldhash eq $git_hash and defined($oldmode) and $oldmode eq $git_perms )
+ {
+ my $newrevision = ( $oldrevision or 0 ) + 1;
+
+ $head->{$git_filename} = {
+ name => $git_filename,
+ revision => $newrevision,
+ filehash => $git_hash,
+ commithash => $commit->{hash},
+ modified => $commit->{date},
+ author => $commit->{author},
+ mode => $git_perms,
+ };
+
+
+ $self->insert_rev($git_filename, $newrevision, $git_hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
+ }
+ }
+ close FILELIST;
+
+ # Detect deleted files
+ foreach my $file ( keys %$head )
+ {
+ unless ( exists $seen_files->{$file} or $head->{$file}{filehash} eq "deleted" )
+ {
+ $head->{$file}{revision}++;
+ $head->{$file}{filehash} = "deleted";
+ $head->{$file}{commithash} = $commit->{hash};
+ $head->{$file}{modified} = $commit->{date};
+ $head->{$file}{author} = $commit->{author};
+
+ $self->insert_rev($file, $head->{$file}{revision}, $head->{$file}{filehash}, $commit->{hash}, $commit->{date}, $commit->{author}, $head->{$file}{mode});
+ }
+ }
+ # END : "Detect deleted files"
+ }
+
+
+ if (exists $commit->{mergemsg})
+ {
+ $self->insert_mergelog($commit->{hash}, $commit->{mergemsg});
+ }
+
+ $lastpicked = $commit->{hash};
+
+ $self->_set_prop("last_commit", $commit->{hash});
+ }
+
+ $self->delete_head();
+ foreach my $file ( keys %$head )
+ {
+ $self->insert_head(
+ $file,
+ $head->{$file}{revision},
+ $head->{$file}{filehash},
+ $head->{$file}{commithash},
+ $head->{$file}{modified},
+ $head->{$file}{author},
+ $head->{$file}{mode},
+ );
+ }
+ # invalidate the gethead cache
+ $self->{gethead_cache} = undef;
+
+
+ # Ending exclusive lock here
+ $self->{dbh}->commit() or die "Failed to commit changes to SQLite";
+}
+
+sub insert_rev
+{
+ my $self = shift;
+ my $name = shift;
+ my $revision = shift;
+ my $filehash = shift;
+ my $commithash = shift;
+ my $modified = shift;
+ my $author = shift;
+ my $mode = shift;
+ my $tablename = $self->tablename("revision");
+
+ my $insert_rev = $self->{dbh}->prepare_cached("INSERT INTO $tablename (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);
+ $insert_rev->execute($name, $revision, $filehash, $commithash, $modified, $author, $mode);
+}
+
+sub insert_mergelog
+{
+ my $self = shift;
+ my $key = shift;
+ my $value = shift;
+ my $tablename = $self->tablename("commitmsgs");
+
+ my $insert_mergelog = $self->{dbh}->prepare_cached("INSERT INTO $tablename (key, value) VALUES (?,?)",{},1);
+ $insert_mergelog->execute($key, $value);
+}
+
+sub delete_head
+{
+ my $self = shift;
+ my $tablename = $self->tablename("head");
+
+ my $delete_head = $self->{dbh}->prepare_cached("DELETE FROM $tablename",{},1);
+ $delete_head->execute();
+}
+
+sub insert_head
+{
+ my $self = shift;
+ my $name = shift;
+ my $revision = shift;
+ my $filehash = shift;
+ my $commithash = shift;
+ my $modified = shift;
+ my $author = shift;
+ my $mode = shift;
+ my $tablename = $self->tablename("head");
+
+ my $insert_head = $self->{dbh}->prepare_cached("INSERT INTO $tablename (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);
+ $insert_head->execute($name, $revision, $filehash, $commithash, $modified, $author, $mode);
+}
+
+sub _headrev
+{
+ my $self = shift;
+ my $filename = shift;
+ my $tablename = $self->tablename("head");
+
+ my $db_query = $self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM $tablename WHERE name=?",{},1);
+ $db_query->execute($filename);
+ my ( $hash, $revision, $mode ) = $db_query->fetchrow_array;
+
+ return ( $hash, $revision, $mode );
+}
+
+sub _get_prop
+{
+ my $self = shift;
+ my $key = shift;
+ my $tablename = $self->tablename("properties");
+
+ my $db_query = $self->{dbh}->prepare_cached("SELECT value FROM $tablename WHERE key=?",{},1);
+ $db_query->execute($key);
+ my ( $value ) = $db_query->fetchrow_array;
+
+ return $value;
+}
+
+sub _set_prop
+{
+ my $self = shift;
+ my $key = shift;
+ my $value = shift;
+ my $tablename = $self->tablename("properties");
+
+ my $db_query = $self->{dbh}->prepare_cached("UPDATE $tablename SET value=? WHERE key=?",{},1);
+ $db_query->execute($value, $key);
+
+ unless ( $db_query->rows )
+ {
+ $db_query = $self->{dbh}->prepare_cached("INSERT INTO $tablename (key, value) VALUES (?,?)",{},1);
+ $db_query->execute($key, $value);
+ }
+
+ return $value;
+}
+
+=head2 gethead
+
+=cut
+
+sub gethead
+{
+ my $self = shift;
+ my $tablename = $self->tablename("head");
+
+ return $self->{gethead_cache} if ( defined ( $self->{gethead_cache} ) );
+
+ my $db_query = $self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM $tablename ORDER BY name ASC",{},1);
+ $db_query->execute();
+
+ my $tree = [];
+ while ( my $file = $db_query->fetchrow_hashref )
+ {
+ push @$tree, $file;
+ }
+
+ $self->{gethead_cache} = $tree;
+
+ return $tree;
+}
+
+=head2 getlog
+
+=cut
+
+sub getlog
+{
+ my $self = shift;
+ my $filename = shift;
+ my $tablename = $self->tablename("revision");
+
+ my $db_query = $self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM $tablename WHERE name=? ORDER BY revision DESC",{},1);
+ $db_query->execute($filename);
+
+ my $tree = [];
+ while ( my $file = $db_query->fetchrow_hashref )
+ {
+ push @$tree, $file;
+ }
+
+ return $tree;
+}
+
+=head2 getmeta
+
+This function takes a filename (with path) argument and returns a hashref of
+metadata for that file.
+
+=cut
+
+sub getmeta
+{
+ my $self = shift;
+ my $filename = shift;
+ my $revision = shift;
+ my $tablename_rev = $self->tablename("revision");
+ my $tablename_head = $self->tablename("head");
+
+ my $db_query;
+ if ( defined($revision) and $revision =~ /^\d+$/ )
+ {
+ $db_query = $self->{dbh}->prepare_cached("SELECT * FROM $tablename_rev WHERE name=? AND revision=?",{},1);
+ $db_query->execute($filename, $revision);
+ }
+ elsif ( defined($revision) and $revision =~ /^[a-zA-Z0-9]{40}$/ )
+ {
+ $db_query = $self->{dbh}->prepare_cached("SELECT * FROM $tablename_rev WHERE name=? AND commithash=?",{},1);
+ $db_query->execute($filename, $revision);
+ } else {
+ $db_query = $self->{dbh}->prepare_cached("SELECT * FROM $tablename_head WHERE name=?",{},1);
+ $db_query->execute($filename);
+ }
+
+ return $db_query->fetchrow_hashref;
+}
+
+=head2 commitmessage
+
+this function takes a commithash and returns the commit message for that commit
+
+=cut
+sub commitmessage
+{
+ my $self = shift;
+ my $commithash = shift;
+ my $tablename = $self->tablename("commitmsgs");
+
+ die("Need commithash") unless ( defined($commithash) and $commithash =~ /^[a-zA-Z0-9]{40}$/ );
+
+ my $db_query;
+ $db_query = $self->{dbh}->prepare_cached("SELECT value FROM $tablename WHERE key=?",{},1);
+ $db_query->execute($commithash);
+
+ my ( $message ) = $db_query->fetchrow_array;
+
+ if ( defined ( $message ) )
+ {
+ $message .= " " if ( $message =~ /\n$/ );
+ return $message;
+ }
+
+ my @lines = safe_pipe_capture("git", "cat-file", "commit", $commithash);
+ shift @lines while ( $lines[0] =~ /\S/ );
+ $message = join("",@lines);
+ $message .= " " if ( $message =~ /\n$/ );
+ return $message;
+}
+
+=head2 gethistory
+
+This function takes a filename (with path) argument and returns an arrayofarrays
+containing revision,filehash,commithash ordered by revision descending
+
+=cut
+sub gethistory
+{
+ my $self = shift;
+ my $filename = shift;
+ my $tablename = $self->tablename("revision");
+
+ my $db_query;
+ $db_query = $self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM $tablename WHERE name=? ORDER BY revision DESC",{},1);
+ $db_query->execute($filename);
+
+ return $db_query->fetchall_arrayref;
+}
+
+=head2 gethistorydense
+
+This function takes a filename (with path) argument and returns an arrayofarrays
+containing revision,filehash,commithash ordered by revision descending.
+
+This version of gethistory skips deleted entries -- so it is useful for annotate.
+The 'dense' part is a reference to a '--dense' option available for git-rev-list
+and other git tools that depend on it.
+
+=cut
+sub gethistorydense
+{
+ my $self = shift;
+ my $filename = shift;
+ my $tablename = $self->tablename("revision");
+
+ my $db_query;
+ $db_query = $self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM $tablename WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);
+ $db_query->execute($filename);
+
+ return $db_query->fetchall_arrayref;
+}
+
+=head2 in_array()
+
+from Array::PAT - mimics the in_array() function
+found in PHP. Yuck but works for small arrays.
+
+=cut
+sub in_array
+{
+ my ($check, @array) = @_;
+ my $retval = 0;
+ foreach my $test (@array){
+ if($check eq $test){
+ $retval = 1;
+ }
+ }
+ return $retval;
+}
+
+=head2 safe_pipe_capture
+
+an alternative to `command` that allows input to be passed as an array
+to work around shell problems with weird characters in arguments
+
+=cut
+sub safe_pipe_capture {
+
+ my @output;
+
+ if (my $pid = open my $child, '-|') {
+ @output = (<$child>);
+ close $child or die join(' ',@_).": $! $?";
+ } else {
+ exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
+ }
+ return wantarray ? @output : join('',@output);
+}
+
+=head2 mangle_dirname
+
+create a string from a directory name that is suitable to use as
+part of a filename, mainly by converting all chars except \w.- to _
+
+=cut
+sub mangle_dirname {
+ my $dirname = shift;
+ return unless defined $dirname;
+
+ $dirname =~ s/[^\w.-]/_/g;
+
+ return $dirname;
+}
+
+=head2 mangle_tablename
+
+create a string from a that is suitable to use as part of an SQL table
+name, mainly by converting all chars except \w to _
+
+=cut
+sub mangle_tablename {
+ my $tablename = shift;
+ return unless defined $tablename;
+
+ $tablename =~ s/[^\w_]/_/g;
+
+ return $tablename;
+}
+
+1;
diff --git a/SparkleShare/Mac/git/bin/git-receive-pack b/SparkleShare/Mac/git/bin/git-receive-pack
new file mode 120000
index 00000000..0899c299
--- /dev/null
+++ b/SparkleShare/Mac/git/bin/git-receive-pack
@@ -0,0 +1 @@
+git
\ No newline at end of file
diff --git a/SparkleShare/Mac/git/bin/git-shell b/SparkleShare/Mac/git/bin/git-shell
new file mode 100755
index 00000000..647fe452
Binary files /dev/null and b/SparkleShare/Mac/git/bin/git-shell differ
diff --git a/SparkleShare/Mac/git/bin/git-upload-archive b/SparkleShare/Mac/git/bin/git-upload-archive
new file mode 120000
index 00000000..0899c299
--- /dev/null
+++ b/SparkleShare/Mac/git/bin/git-upload-archive
@@ -0,0 +1 @@
+git
\ No newline at end of file
diff --git a/SparkleShare/Mac/git/bin/git-upload-pack b/SparkleShare/Mac/git/bin/git-upload-pack
new file mode 100755
index 00000000..3cc4e6db
Binary files /dev/null and b/SparkleShare/Mac/git/bin/git-upload-pack differ
diff --git a/SparkleShare/Mac/git/bin/gitk b/SparkleShare/Mac/git/bin/gitk
new file mode 100755
index 00000000..4cde0c49
--- /dev/null
+++ b/SparkleShare/Mac/git/bin/gitk
@@ -0,0 +1,11702 @@
+#!/bin/sh
+# Tcl ignores the next line -*- tcl -*- \
+exec wish "$0" -- "$@"
+
+# Copyright © 2005-2009 Paul Mackerras. All rights reserved.
+# This program is free software; it may be used, copied, modified
+# and distributed under the terms of the GNU General Public Licence,
+# either version 2, or (at your option) any later version.
+
+package require Tk
+
+proc gitdir {} {
+ global env
+ if {[info exists env(GIT_DIR)]} {
+ return $env(GIT_DIR)
+ } else {
+ return [exec git rev-parse --git-dir]
+ }
+}
+
+# A simple scheduler for compute-intensive stuff.
+# The aim is to make sure that event handlers for GUI actions can
+# run at least every 50-100 ms. Unfortunately fileevent handlers are
+# run before X event handlers, so reading from a fast source can
+# make the GUI completely unresponsive.
+proc run args {
+ global isonrunq runq currunq
+
+ set script $args
+ if {[info exists isonrunq($script)]} return
+ if {$runq eq {} && ![info exists currunq]} {
+ after idle dorunq
+ }
+ lappend runq [list {} $script]
+ set isonrunq($script) 1
+}
+
+proc filerun {fd script} {
+ fileevent $fd readable [list filereadable $fd $script]
+}
+
+proc filereadable {fd script} {
+ global runq currunq
+
+ fileevent $fd readable {}
+ if {$runq eq {} && ![info exists currunq]} {
+ after idle dorunq
+ }
+ lappend runq [list $fd $script]
+}
+
+proc nukefile {fd} {
+ global runq
+
+ for {set i 0} {$i < [llength $runq]} {} {
+ if {[lindex $runq $i 0] eq $fd} {
+ set runq [lreplace $runq $i $i]
+ } else {
+ incr i
+ }
+ }
+}
+
+proc dorunq {} {
+ global isonrunq runq currunq
+
+ set tstart [clock clicks -milliseconds]
+ set t0 $tstart
+ while {[llength $runq] > 0} {
+ set fd [lindex $runq 0 0]
+ set script [lindex $runq 0 1]
+ set currunq [lindex $runq 0]
+ set runq [lrange $runq 1 end]
+ set repeat [eval $script]
+ unset currunq
+ set t1 [clock clicks -milliseconds]
+ set t [expr {$t1 - $t0}]
+ if {$repeat ne {} && $repeat} {
+ if {$fd eq {} || $repeat == 2} {
+ # script returns 1 if it wants to be readded
+ # file readers return 2 if they could do more straight away
+ lappend runq [list $fd $script]
+ } else {
+ fileevent $fd readable [list filereadable $fd $script]
+ }
+ } elseif {$fd eq {}} {
+ unset isonrunq($script)
+ }
+ set t0 $t1
+ if {$t1 - $tstart >= 80} break
+ }
+ if {$runq ne {}} {
+ after idle dorunq
+ }
+}
+
+proc reg_instance {fd} {
+ global commfd leftover loginstance
+
+ set i [incr loginstance]
+ set commfd($i) $fd
+ set leftover($i) {}
+ return $i
+}
+
+proc unmerged_files {files} {
+ global nr_unmerged
+
+ # find the list of unmerged files
+ set mlist {}
+ set nr_unmerged 0
+ if {[catch {
+ set fd [open "| git ls-files -u" r]
+ } err]} {
+ show_error {} . "[mc "Couldn't get list of unmerged files:"] $err"
+ exit 1
+ }
+ while {[gets $fd line] >= 0} {
+ set i [string first "\t" $line]
+ if {$i < 0} continue
+ set fname [string range $line [expr {$i+1}] end]
+ if {[lsearch -exact $mlist $fname] >= 0} continue
+ incr nr_unmerged
+ if {$files eq {} || [path_filter $files $fname]} {
+ lappend mlist $fname
+ }
+ }
+ catch {close $fd}
+ return $mlist
+}
+
+proc parseviewargs {n arglist} {
+ global vdatemode vmergeonly vflags vdflags vrevs vfiltered vorigargs env
+ global worddiff git_version
+
+ set vdatemode($n) 0
+ set vmergeonly($n) 0
+ set glflags {}
+ set diffargs {}
+ set nextisval 0
+ set revargs {}
+ set origargs $arglist
+ set allknown 1
+ set filtered 0
+ set i -1
+ foreach arg $arglist {
+ incr i
+ if {$nextisval} {
+ lappend glflags $arg
+ set nextisval 0
+ continue
+ }
+ switch -glob -- $arg {
+ "-d" -
+ "--date-order" {
+ set vdatemode($n) 1
+ # remove from origargs in case we hit an unknown option
+ set origargs [lreplace $origargs $i $i]
+ incr i -1
+ }
+ "-[puabwcrRBMC]" -
+ "--no-renames" - "--full-index" - "--binary" - "--abbrev=*" -
+ "--find-copies-harder" - "-l*" - "--ext-diff" - "--no-ext-diff" -
+ "--src-prefix=*" - "--dst-prefix=*" - "--no-prefix" -
+ "-O*" - "--text" - "--full-diff" - "--ignore-space-at-eol" -
+ "--ignore-space-change" - "-U*" - "--unified=*" {
+ # These request or affect diff output, which we don't want.
+ # Some could be used to set our defaults for diff display.
+ lappend diffargs $arg
+ }
+ "--raw" - "--patch-with-raw" - "--patch-with-stat" -
+ "--name-only" - "--name-status" - "--color" -
+ "--log-size" - "--pretty=*" - "--decorate" - "--abbrev-commit" -
+ "--cc" - "-z" - "--header" - "--parents" - "--boundary" -
+ "--no-color" - "-g" - "--walk-reflogs" - "--no-walk" -
+ "--timestamp" - "relative-date" - "--date=*" - "--stdin" -
+ "--objects" - "--objects-edge" - "--reverse" {
+ # These cause our parsing of git log's output to fail, or else
+ # they're options we want to set ourselves, so ignore them.
+ }
+ "--color-words*" - "--word-diff=color" {
+ # These trigger a word diff in the console interface,
+ # so help the user by enabling our own support
+ if {[package vcompare $git_version "1.7.2"] >= 0} {
+ set worddiff [mc "Color words"]
+ }
+ }
+ "--word-diff*" {
+ if {[package vcompare $git_version "1.7.2"] >= 0} {
+ set worddiff [mc "Markup words"]
+ }
+ }
+ "--stat=*" - "--numstat" - "--shortstat" - "--summary" -
+ "--check" - "--exit-code" - "--quiet" - "--topo-order" -
+ "--full-history" - "--dense" - "--sparse" -
+ "--follow" - "--left-right" - "--encoding=*" {
+ # These are harmless, and some are even useful
+ lappend glflags $arg
+ }
+ "--diff-filter=*" - "--no-merges" - "--unpacked" -
+ "--max-count=*" - "--skip=*" - "--since=*" - "--after=*" -
+ "--until=*" - "--before=*" - "--max-age=*" - "--min-age=*" -
+ "--author=*" - "--committer=*" - "--grep=*" - "-[iE]" -
+ "--remove-empty" - "--first-parent" - "--cherry-pick" -
+ "-S*" - "--pickaxe-all" - "--pickaxe-regex" -
+ "--simplify-by-decoration" {
+ # These mean that we get a subset of the commits
+ set filtered 1
+ lappend glflags $arg
+ }
+ "-n" {
+ # This appears to be the only one that has a value as a
+ # separate word following it
+ set filtered 1
+ set nextisval 1
+ lappend glflags $arg
+ }
+ "--not" - "--all" {
+ lappend revargs $arg
+ }
+ "--merge" {
+ set vmergeonly($n) 1
+ # git rev-parse doesn't understand --merge
+ lappend revargs --gitk-symmetric-diff-marker MERGE_HEAD...HEAD
+ }
+ "--no-replace-objects" {
+ set env(GIT_NO_REPLACE_OBJECTS) "1"
+ }
+ "-*" {
+ # Other flag arguments including -
+ if {[string is digit -strict [string range $arg 1 end]]} {
+ set filtered 1
+ } else {
+ # a flag argument that we don't recognize;
+ # that means we can't optimize
+ set allknown 0
+ }
+ lappend glflags $arg
+ }
+ default {
+ # Non-flag arguments specify commits or ranges of commits
+ if {[string match "*...*" $arg]} {
+ lappend revargs --gitk-symmetric-diff-marker
+ }
+ lappend revargs $arg
+ }
+ }
+ }
+ set vdflags($n) $diffargs
+ set vflags($n) $glflags
+ set vrevs($n) $revargs
+ set vfiltered($n) $filtered
+ set vorigargs($n) $origargs
+ return $allknown
+}
+
+proc parseviewrevs {view revs} {
+ global vposids vnegids
+
+ if {$revs eq {}} {
+ set revs HEAD
+ }
+ if {[catch {set ids [eval exec git rev-parse $revs]} err]} {
+ # we get stdout followed by stderr in $err
+ # for an unknown rev, git rev-parse echoes it and then errors out
+ set errlines [split $err "\n"]
+ set badrev {}
+ for {set l 0} {$l < [llength $errlines]} {incr l} {
+ set line [lindex $errlines $l]
+ if {!([string length $line] == 40 && [string is xdigit $line])} {
+ if {[string match "fatal:*" $line]} {
+ if {[string match "fatal: ambiguous argument*" $line]
+ && $badrev ne {}} {
+ if {[llength $badrev] == 1} {
+ set err "unknown revision $badrev"
+ } else {
+ set err "unknown revisions: [join $badrev ", "]"
+ }
+ } else {
+ set err [join [lrange $errlines $l end] "\n"]
+ }
+ break
+ }
+ lappend badrev $line
+ }
+ }
+ error_popup "[mc "Error parsing revisions:"] $err"
+ return {}
+ }
+ set ret {}
+ set pos {}
+ set neg {}
+ set sdm 0
+ foreach id [split $ids "\n"] {
+ if {$id eq "--gitk-symmetric-diff-marker"} {
+ set sdm 4
+ } elseif {[string match "^*" $id]} {
+ if {$sdm != 1} {
+ lappend ret $id
+ if {$sdm == 3} {
+ set sdm 0
+ }
+ }
+ lappend neg [string range $id 1 end]
+ } else {
+ if {$sdm != 2} {
+ lappend ret $id
+ } else {
+ lset ret end $id...[lindex $ret end]
+ }
+ lappend pos $id
+ }
+ incr sdm -1
+ }
+ set vposids($view) $pos
+ set vnegids($view) $neg
+ return $ret
+}
+
+# Start off a git log process and arrange to read its output
+proc start_rev_list {view} {
+ global startmsecs commitidx viewcomplete curview
+ global tclencoding
+ global viewargs viewargscmd viewfiles vfilelimit
+ global showlocalchanges
+ global viewactive viewinstances vmergeonly
+ global mainheadid viewmainheadid viewmainheadid_orig
+ global vcanopt vflags vrevs vorigargs
+ global show_notes
+
+ set startmsecs [clock clicks -milliseconds]
+ set commitidx($view) 0
+ # these are set this way for the error exits
+ set viewcomplete($view) 1
+ set viewactive($view) 0
+ varcinit $view
+
+ set args $viewargs($view)
+ if {$viewargscmd($view) ne {}} {
+ if {[catch {
+ set str [exec sh -c $viewargscmd($view)]
+ } err]} {
+ error_popup "[mc "Error executing --argscmd command:"] $err"
+ return 0
+ }
+ set args [concat $args [split $str "\n"]]
+ }
+ set vcanopt($view) [parseviewargs $view $args]
+
+ set files $viewfiles($view)
+ if {$vmergeonly($view)} {
+ set files [unmerged_files $files]
+ if {$files eq {}} {
+ global nr_unmerged
+ if {$nr_unmerged == 0} {
+ error_popup [mc "No files selected: --merge specified but\
+ no files are unmerged."]
+ } else {
+ error_popup [mc "No files selected: --merge specified but\
+ no unmerged files are within file limit."]
+ }
+ return 0
+ }
+ }
+ set vfilelimit($view) $files
+
+ if {$vcanopt($view)} {
+ set revs [parseviewrevs $view $vrevs($view)]
+ if {$revs eq {}} {
+ return 0
+ }
+ set args [concat $vflags($view) $revs]
+ } else {
+ set args $vorigargs($view)
+ }
+
+ if {[catch {
+ set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
+ --parents --boundary $args "--" $files] r]
+ } err]} {
+ error_popup "[mc "Error executing git log:"] $err"
+ return 0
+ }
+ set i [reg_instance $fd]
+ set viewinstances($view) [list $i]
+ set viewmainheadid($view) $mainheadid
+ set viewmainheadid_orig($view) $mainheadid
+ if {$files ne {} && $mainheadid ne {}} {
+ get_viewmainhead $view
+ }
+ if {$showlocalchanges && $viewmainheadid($view) ne {}} {
+ interestedin $viewmainheadid($view) dodiffindex
+ }
+ fconfigure $fd -blocking 0 -translation lf -eofchar {}
+ if {$tclencoding != {}} {
+ fconfigure $fd -encoding $tclencoding
+ }
+ filerun $fd [list getcommitlines $fd $i $view 0]
+ nowbusy $view [mc "Reading"]
+ set viewcomplete($view) 0
+ set viewactive($view) 1
+ return 1
+}
+
+proc stop_instance {inst} {
+ global commfd leftover
+
+ set fd $commfd($inst)
+ catch {
+ set pid [pid $fd]
+
+ if {$::tcl_platform(platform) eq {windows}} {
+ exec kill -f $pid
+ } else {
+ exec kill $pid
+ }
+ }
+ catch {close $fd}
+ nukefile $fd
+ unset commfd($inst)
+ unset leftover($inst)
+}
+
+proc stop_backends {} {
+ global commfd
+
+ foreach inst [array names commfd] {
+ stop_instance $inst
+ }
+}
+
+proc stop_rev_list {view} {
+ global viewinstances
+
+ foreach inst $viewinstances($view) {
+ stop_instance $inst
+ }
+ set viewinstances($view) {}
+}
+
+proc reset_pending_select {selid} {
+ global pending_select mainheadid selectheadid
+
+ if {$selid ne {}} {
+ set pending_select $selid
+ } elseif {$selectheadid ne {}} {
+ set pending_select $selectheadid
+ } else {
+ set pending_select $mainheadid
+ }
+}
+
+proc getcommits {selid} {
+ global canv curview need_redisplay viewactive
+
+ initlayout
+ if {[start_rev_list $curview]} {
+ reset_pending_select $selid
+ show_status [mc "Reading commits..."]
+ set need_redisplay 1
+ } else {
+ show_status [mc "No commits selected"]
+ }
+}
+
+proc updatecommits {} {
+ global curview vcanopt vorigargs vfilelimit viewinstances
+ global viewactive viewcomplete tclencoding
+ global startmsecs showneartags showlocalchanges
+ global mainheadid viewmainheadid viewmainheadid_orig pending_select
+ global isworktree
+ global varcid vposids vnegids vflags vrevs
+ global show_notes
+
+ set isworktree [expr {[exec git rev-parse --is-inside-work-tree] == "true"}]
+ rereadrefs
+ set view $curview
+ if {$mainheadid ne $viewmainheadid_orig($view)} {
+ if {$showlocalchanges} {
+ dohidelocalchanges
+ }
+ set viewmainheadid($view) $mainheadid
+ set viewmainheadid_orig($view) $mainheadid
+ if {$vfilelimit($view) ne {}} {
+ get_viewmainhead $view
+ }
+ }
+ if {$showlocalchanges} {
+ doshowlocalchanges
+ }
+ if {$vcanopt($view)} {
+ set oldpos $vposids($view)
+ set oldneg $vnegids($view)
+ set revs [parseviewrevs $view $vrevs($view)]
+ if {$revs eq {}} {
+ return
+ }
+ # note: getting the delta when negative refs change is hard,
+ # and could require multiple git log invocations, so in that
+ # case we ask git log for all the commits (not just the delta)
+ if {$oldneg eq $vnegids($view)} {
+ set newrevs {}
+ set npos 0
+ # take out positive refs that we asked for before or
+ # that we have already seen
+ foreach rev $revs {
+ if {[string length $rev] == 40} {
+ if {[lsearch -exact $oldpos $rev] < 0
+ && ![info exists varcid($view,$rev)]} {
+ lappend newrevs $rev
+ incr npos
+ }
+ } else {
+ lappend $newrevs $rev
+ }
+ }
+ if {$npos == 0} return
+ set revs $newrevs
+ set vposids($view) [lsort -unique [concat $oldpos $vposids($view)]]
+ }
+ set args [concat $vflags($view) $revs --not $oldpos]
+ } else {
+ set args $vorigargs($view)
+ }
+ if {[catch {
+ set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
+ --parents --boundary $args "--" $vfilelimit($view)] r]
+ } err]} {
+ error_popup "[mc "Error executing git log:"] $err"
+ return
+ }
+ if {$viewactive($view) == 0} {
+ set startmsecs [clock clicks -milliseconds]
+ }
+ set i [reg_instance $fd]
+ lappend viewinstances($view) $i
+ fconfigure $fd -blocking 0 -translation lf -eofchar {}
+ if {$tclencoding != {}} {
+ fconfigure $fd -encoding $tclencoding
+ }
+ filerun $fd [list getcommitlines $fd $i $view 1]
+ incr viewactive($view)
+ set viewcomplete($view) 0
+ reset_pending_select {}
+ nowbusy $view [mc "Reading"]
+ if {$showneartags} {
+ getallcommits
+ }
+}
+
+proc reloadcommits {} {
+ global curview viewcomplete selectedline currentid thickerline
+ global showneartags treediffs commitinterest cached_commitrow
+ global targetid
+
+ set selid {}
+ if {$selectedline ne {}} {
+ set selid $currentid
+ }
+
+ if {!$viewcomplete($curview)} {
+ stop_rev_list $curview
+ }
+ resetvarcs $curview
+ set selectedline {}
+ catch {unset currentid}
+ catch {unset thickerline}
+ catch {unset treediffs}
+ readrefs
+ changedrefs
+ if {$showneartags} {
+ getallcommits
+ }
+ clear_display
+ catch {unset commitinterest}
+ catch {unset cached_commitrow}
+ catch {unset targetid}
+ setcanvscroll
+ getcommits $selid
+ return 0
+}
+
+# This makes a string representation of a positive integer which
+# sorts as a string in numerical order
+proc strrep {n} {
+ if {$n < 16} {
+ return [format "%x" $n]
+ } elseif {$n < 256} {
+ return [format "x%.2x" $n]
+ } elseif {$n < 65536} {
+ return [format "y%.4x" $n]
+ }
+ return [format "z%.8x" $n]
+}
+
+# Procedures used in reordering commits from git log (without
+# --topo-order) into the order for display.
+
+proc varcinit {view} {
+ global varcstart vupptr vdownptr vleftptr vbackptr varctok varcrow
+ global vtokmod varcmod vrowmod varcix vlastins
+
+ set varcstart($view) {{}}
+ set vupptr($view) {0}
+ set vdownptr($view) {0}
+ set vleftptr($view) {0}
+ set vbackptr($view) {0}
+ set varctok($view) {{}}
+ set varcrow($view) {{}}
+ set vtokmod($view) {}
+ set varcmod($view) 0
+ set vrowmod($view) 0
+ set varcix($view) {{}}
+ set vlastins($view) {0}
+}
+
+proc resetvarcs {view} {
+ global varcid varccommits parents children vseedcount ordertok
+
+ foreach vid [array names varcid $view,*] {
+ unset varcid($vid)
+ unset children($vid)
+ unset parents($vid)
+ }
+ # some commits might have children but haven't been seen yet
+ foreach vid [array names children $view,*] {
+ unset children($vid)
+ }
+ foreach va [array names varccommits $view,*] {
+ unset varccommits($va)
+ }
+ foreach vd [array names vseedcount $view,*] {
+ unset vseedcount($vd)
+ }
+ catch {unset ordertok}
+}
+
+# returns a list of the commits with no children
+proc seeds {v} {
+ global vdownptr vleftptr varcstart
+
+ set ret {}
+ set a [lindex $vdownptr($v) 0]
+ while {$a != 0} {
+ lappend ret [lindex $varcstart($v) $a]
+ set a [lindex $vleftptr($v) $a]
+ }
+ return $ret
+}
+
+proc newvarc {view id} {
+ global varcid varctok parents children vdatemode
+ global vupptr vdownptr vleftptr vbackptr varcrow varcix varcstart
+ global commitdata commitinfo vseedcount varccommits vlastins
+
+ set a [llength $varctok($view)]
+ set vid $view,$id
+ if {[llength $children($vid)] == 0 || $vdatemode($view)} {
+ if {![info exists commitinfo($id)]} {
+ parsecommit $id $commitdata($id) 1
+ }
+ set cdate [lindex $commitinfo($id) 4]
+ if {![string is integer -strict $cdate]} {
+ set cdate 0
+ }
+ if {![info exists vseedcount($view,$cdate)]} {
+ set vseedcount($view,$cdate) -1
+ }
+ set c [incr vseedcount($view,$cdate)]
+ set cdate [expr {$cdate ^ 0xffffffff}]
+ set tok "s[strrep $cdate][strrep $c]"
+ } else {
+ set tok {}
+ }
+ set ka 0
+ if {[llength $children($vid)] > 0} {
+ set kid [lindex $children($vid) end]
+ set k $varcid($view,$kid)
+ if {[string compare [lindex $varctok($view) $k] $tok] > 0} {
+ set ki $kid
+ set ka $k
+ set tok [lindex $varctok($view) $k]
+ }
+ }
+ if {$ka != 0} {
+ set i [lsearch -exact $parents($view,$ki) $id]
+ set j [expr {[llength $parents($view,$ki)] - 1 - $i}]
+ append tok [strrep $j]
+ }
+ set c [lindex $vlastins($view) $ka]
+ if {$c == 0 || [string compare $tok [lindex $varctok($view) $c]] < 0} {
+ set c $ka
+ set b [lindex $vdownptr($view) $ka]
+ } else {
+ set b [lindex $vleftptr($view) $c]
+ }
+ while {$b != 0 && [string compare $tok [lindex $varctok($view) $b]] >= 0} {
+ set c $b
+ set b [lindex $vleftptr($view) $c]
+ }
+ if {$c == $ka} {
+ lset vdownptr($view) $ka $a
+ lappend vbackptr($view) 0
+ } else {
+ lset vleftptr($view) $c $a
+ lappend vbackptr($view) $c
+ }
+ lset vlastins($view) $ka $a
+ lappend vupptr($view) $ka
+ lappend vleftptr($view) $b
+ if {$b != 0} {
+ lset vbackptr($view) $b $a
+ }
+ lappend varctok($view) $tok
+ lappend varcstart($view) $id
+ lappend vdownptr($view) 0
+ lappend varcrow($view) {}
+ lappend varcix($view) {}
+ set varccommits($view,$a) {}
+ lappend vlastins($view) 0
+ return $a
+}
+
+proc splitvarc {p v} {
+ global varcid varcstart varccommits varctok vtokmod
+ global vupptr vdownptr vleftptr vbackptr varcix varcrow vlastins
+
+ set oa $varcid($v,$p)
+ set otok [lindex $varctok($v) $oa]
+ set ac $varccommits($v,$oa)
+ set i [lsearch -exact $varccommits($v,$oa) $p]
+ if {$i <= 0} return
+ set na [llength $varctok($v)]
+ # "%" sorts before "0"...
+ set tok "$otok%[strrep $i]"
+ lappend varctok($v) $tok
+ lappend varcrow($v) {}
+ lappend varcix($v) {}
+ set varccommits($v,$oa) [lrange $ac 0 [expr {$i - 1}]]
+ set varccommits($v,$na) [lrange $ac $i end]
+ lappend varcstart($v) $p
+ foreach id $varccommits($v,$na) {
+ set varcid($v,$id) $na
+ }
+ lappend vdownptr($v) [lindex $vdownptr($v) $oa]
+ lappend vlastins($v) [lindex $vlastins($v) $oa]
+ lset vdownptr($v) $oa $na
+ lset vlastins($v) $oa 0
+ lappend vupptr($v) $oa
+ lappend vleftptr($v) 0
+ lappend vbackptr($v) 0
+ for {set b [lindex $vdownptr($v) $na]} {$b != 0} {set b [lindex $vleftptr($v) $b]} {
+ lset vupptr($v) $b $na
+ }
+ if {[string compare $otok $vtokmod($v)] <= 0} {
+ modify_arc $v $oa
+ }
+}
+
+proc renumbervarc {a v} {
+ global parents children varctok varcstart varccommits
+ global vupptr vdownptr vleftptr vbackptr vlastins varcid vtokmod vdatemode
+
+ set t1 [clock clicks -milliseconds]
+ set todo {}
+ set isrelated($a) 1
+ set kidchanged($a) 1
+ set ntot 0
+ while {$a != 0} {
+ if {[info exists isrelated($a)]} {
+ lappend todo $a
+ set id [lindex $varccommits($v,$a) end]
+ foreach p $parents($v,$id) {
+ if {[info exists varcid($v,$p)]} {
+ set isrelated($varcid($v,$p)) 1
+ }
+ }
+ }
+ incr ntot
+ set b [lindex $vdownptr($v) $a]
+ if {$b == 0} {
+ while {$a != 0} {
+ set b [lindex $vleftptr($v) $a]
+ if {$b != 0} break
+ set a [lindex $vupptr($v) $a]
+ }
+ }
+ set a $b
+ }
+ foreach a $todo {
+ if {![info exists kidchanged($a)]} continue
+ set id [lindex $varcstart($v) $a]
+ if {[llength $children($v,$id)] > 1} {
+ set children($v,$id) [lsort -command [list vtokcmp $v] \
+ $children($v,$id)]
+ }
+ set oldtok [lindex $varctok($v) $a]
+ if {!$vdatemode($v)} {
+ set tok {}
+ } else {
+ set tok $oldtok
+ }
+ set ka 0
+ set kid [last_real_child $v,$id]
+ if {$kid ne {}} {
+ set k $varcid($v,$kid)
+ if {[string compare [lindex $varctok($v) $k] $tok] > 0} {
+ set ki $kid
+ set ka $k
+ set tok [lindex $varctok($v) $k]
+ }
+ }
+ if {$ka != 0} {
+ set i [lsearch -exact $parents($v,$ki) $id]
+ set j [expr {[llength $parents($v,$ki)] - 1 - $i}]
+ append tok [strrep $j]
+ }
+ if {$tok eq $oldtok} {
+ continue
+ }
+ set id [lindex $varccommits($v,$a) end]
+ foreach p $parents($v,$id) {
+ if {[info exists varcid($v,$p)]} {
+ set kidchanged($varcid($v,$p)) 1
+ } else {
+ set sortkids($p) 1
+ }
+ }
+ lset varctok($v) $a $tok
+ set b [lindex $vupptr($v) $a]
+ if {$b != $ka} {
+ if {[string compare [lindex $varctok($v) $ka] $vtokmod($v)] < 0} {
+ modify_arc $v $ka
+ }
+ if {[string compare [lindex $varctok($v) $b] $vtokmod($v)] < 0} {
+ modify_arc $v $b
+ }
+ set c [lindex $vbackptr($v) $a]
+ set d [lindex $vleftptr($v) $a]
+ if {$c == 0} {
+ lset vdownptr($v) $b $d
+ } else {
+ lset vleftptr($v) $c $d
+ }
+ if {$d != 0} {
+ lset vbackptr($v) $d $c
+ }
+ if {[lindex $vlastins($v) $b] == $a} {
+ lset vlastins($v) $b $c
+ }
+ lset vupptr($v) $a $ka
+ set c [lindex $vlastins($v) $ka]
+ if {$c == 0 || \
+ [string compare $tok [lindex $varctok($v) $c]] < 0} {
+ set c $ka
+ set b [lindex $vdownptr($v) $ka]
+ } else {
+ set b [lindex $vleftptr($v) $c]
+ }
+ while {$b != 0 && \
+ [string compare $tok [lindex $varctok($v) $b]] >= 0} {
+ set c $b
+ set b [lindex $vleftptr($v) $c]
+ }
+ if {$c == $ka} {
+ lset vdownptr($v) $ka $a
+ lset vbackptr($v) $a 0
+ } else {
+ lset vleftptr($v) $c $a
+ lset vbackptr($v) $a $c
+ }
+ lset vleftptr($v) $a $b
+ if {$b != 0} {
+ lset vbackptr($v) $b $a
+ }
+ lset vlastins($v) $ka $a
+ }
+ }
+ foreach id [array names sortkids] {
+ if {[llength $children($v,$id)] > 1} {
+ set children($v,$id) [lsort -command [list vtokcmp $v] \
+ $children($v,$id)]
+ }
+ }
+ set t2 [clock clicks -milliseconds]
+ #puts "renumbervarc did [llength $todo] of $ntot arcs in [expr {$t2-$t1}]ms"
+}
+
+# Fix up the graph after we have found out that in view $v,
+# $p (a commit that we have already seen) is actually the parent
+# of the last commit in arc $a.
+proc fix_reversal {p a v} {
+ global varcid varcstart varctok vupptr
+
+ set pa $varcid($v,$p)
+ if {$p ne [lindex $varcstart($v) $pa]} {
+ splitvarc $p $v
+ set pa $varcid($v,$p)
+ }
+ # seeds always need to be renumbered
+ if {[lindex $vupptr($v) $pa] == 0 ||
+ [string compare [lindex $varctok($v) $a] \
+ [lindex $varctok($v) $pa]] > 0} {
+ renumbervarc $pa $v
+ }
+}
+
+proc insertrow {id p v} {
+ global cmitlisted children parents varcid varctok vtokmod
+ global varccommits ordertok commitidx numcommits curview
+ global targetid targetrow
+
+ readcommit $id
+ set vid $v,$id
+ set cmitlisted($vid) 1
+ set children($vid) {}
+ set parents($vid) [list $p]
+ set a [newvarc $v $id]
+ set varcid($vid) $a
+ if {[string compare [lindex $varctok($v) $a] $vtokmod($v)] < 0} {
+ modify_arc $v $a
+ }
+ lappend varccommits($v,$a) $id
+ set vp $v,$p
+ if {[llength [lappend children($vp) $id]] > 1} {
+ set children($vp) [lsort -command [list vtokcmp $v] $children($vp)]
+ catch {unset ordertok}
+ }
+ fix_reversal $p $a $v
+ incr commitidx($v)
+ if {$v == $curview} {
+ set numcommits $commitidx($v)
+ setcanvscroll
+ if {[info exists targetid]} {
+ if {![comes_before $targetid $p]} {
+ incr targetrow
+ }
+ }
+ }
+}
+
+proc insertfakerow {id p} {
+ global varcid varccommits parents children cmitlisted
+ global commitidx varctok vtokmod targetid targetrow curview numcommits
+
+ set v $curview
+ set a $varcid($v,$p)
+ set i [lsearch -exact $varccommits($v,$a) $p]
+ if {$i < 0} {
+ puts "oops: insertfakerow can't find [shortids $p] on arc $a"
+ return
+ }
+ set children($v,$id) {}
+ set parents($v,$id) [list $p]
+ set varcid($v,$id) $a
+ lappend children($v,$p) $id
+ set cmitlisted($v,$id) 1
+ set numcommits [incr commitidx($v)]
+ # note we deliberately don't update varcstart($v) even if $i == 0
+ set varccommits($v,$a) [linsert $varccommits($v,$a) $i $id]
+ modify_arc $v $a $i
+ if {[info exists targetid]} {
+ if {![comes_before $targetid $p]} {
+ incr targetrow
+ }
+ }
+ setcanvscroll
+ drawvisible
+}
+
+proc removefakerow {id} {
+ global varcid varccommits parents children commitidx
+ global varctok vtokmod cmitlisted currentid selectedline
+ global targetid curview numcommits
+
+ set v $curview
+ if {[llength $parents($v,$id)] != 1} {
+ puts "oops: removefakerow [shortids $id] has [llength $parents($v,$id)] parents"
+ return
+ }
+ set p [lindex $parents($v,$id) 0]
+ set a $varcid($v,$id)
+ set i [lsearch -exact $varccommits($v,$a) $id]
+ if {$i < 0} {
+ puts "oops: removefakerow can't find [shortids $id] on arc $a"
+ return
+ }
+ unset varcid($v,$id)
+ set varccommits($v,$a) [lreplace $varccommits($v,$a) $i $i]
+ unset parents($v,$id)
+ unset children($v,$id)
+ unset cmitlisted($v,$id)
+ set numcommits [incr commitidx($v) -1]
+ set j [lsearch -exact $children($v,$p) $id]
+ if {$j >= 0} {
+ set children($v,$p) [lreplace $children($v,$p) $j $j]
+ }
+ modify_arc $v $a $i
+ if {[info exist currentid] && $id eq $currentid} {
+ unset currentid
+ set selectedline {}
+ }
+ if {[info exists targetid] && $targetid eq $id} {
+ set targetid $p
+ }
+ setcanvscroll
+ drawvisible
+}
+
+proc real_children {vp} {
+ global children nullid nullid2
+
+ set kids {}
+ foreach id $children($vp) {
+ if {$id ne $nullid && $id ne $nullid2} {
+ lappend kids $id
+ }
+ }
+ return $kids
+}
+
+proc first_real_child {vp} {
+ global children nullid nullid2
+
+ foreach id $children($vp) {
+ if {$id ne $nullid && $id ne $nullid2} {
+ return $id
+ }
+ }
+ return {}
+}
+
+proc last_real_child {vp} {
+ global children nullid nullid2
+
+ set kids $children($vp)
+ for {set i [llength $kids]} {[incr i -1] >= 0} {} {
+ set id [lindex $kids $i]
+ if {$id ne $nullid && $id ne $nullid2} {
+ return $id
+ }
+ }
+ return {}
+}
+
+proc vtokcmp {v a b} {
+ global varctok varcid
+
+ return [string compare [lindex $varctok($v) $varcid($v,$a)] \
+ [lindex $varctok($v) $varcid($v,$b)]]
+}
+
+# This assumes that if lim is not given, the caller has checked that
+# arc a's token is less than $vtokmod($v)
+proc modify_arc {v a {lim {}}} {
+ global varctok vtokmod varcmod varcrow vupptr curview vrowmod varccommits
+
+ if {$lim ne {}} {
+ set c [string compare [lindex $varctok($v) $a] $vtokmod($v)]
+ if {$c > 0} return
+ if {$c == 0} {
+ set r [lindex $varcrow($v) $a]
+ if {$r ne {} && $vrowmod($v) <= $r + $lim} return
+ }
+ }
+ set vtokmod($v) [lindex $varctok($v) $a]
+ set varcmod($v) $a
+ if {$v == $curview} {
+ while {$a != 0 && [lindex $varcrow($v) $a] eq {}} {
+ set a [lindex $vupptr($v) $a]
+ set lim {}
+ }
+ set r 0
+ if {$a != 0} {
+ if {$lim eq {}} {
+ set lim [llength $varccommits($v,$a)]
+ }
+ set r [expr {[lindex $varcrow($v) $a] + $lim}]
+ }
+ set vrowmod($v) $r
+ undolayout $r
+ }
+}
+
+proc update_arcrows {v} {
+ global vtokmod varcmod vrowmod varcrow commitidx currentid selectedline
+ global varcid vrownum varcorder varcix varccommits
+ global vupptr vdownptr vleftptr varctok
+ global displayorder parentlist curview cached_commitrow
+
+ if {$vrowmod($v) == $commitidx($v)} return
+ if {$v == $curview} {
+ if {[llength $displayorder] > $vrowmod($v)} {
+ set displayorder [lrange $displayorder 0 [expr {$vrowmod($v) - 1}]]
+ set parentlist [lrange $parentlist 0 [expr {$vrowmod($v) - 1}]]
+ }
+ catch {unset cached_commitrow}
+ }
+ set narctot [expr {[llength $varctok($v)] - 1}]
+ set a $varcmod($v)
+ while {$a != 0 && [lindex $varcix($v) $a] eq {}} {
+ # go up the tree until we find something that has a row number,
+ # or we get to a seed
+ set a [lindex $vupptr($v) $a]
+ }
+ if {$a == 0} {
+ set a [lindex $vdownptr($v) 0]
+ if {$a == 0} return
+ set vrownum($v) {0}
+ set varcorder($v) [list $a]
+ lset varcix($v) $a 0
+ lset varcrow($v) $a 0
+ set arcn 0
+ set row 0
+ } else {
+ set arcn [lindex $varcix($v) $a]
+ if {[llength $vrownum($v)] > $arcn + 1} {
+ set vrownum($v) [lrange $vrownum($v) 0 $arcn]
+ set varcorder($v) [lrange $varcorder($v) 0 $arcn]
+ }
+ set row [lindex $varcrow($v) $a]
+ }
+ while {1} {
+ set p $a
+ incr row [llength $varccommits($v,$a)]
+ # go down if possible
+ set b [lindex $vdownptr($v) $a]
+ if {$b == 0} {
+ # if not, go left, or go up until we can go left
+ while {$a != 0} {
+ set b [lindex $vleftptr($v) $a]
+ if {$b != 0} break
+ set a [lindex $vupptr($v) $a]
+ }
+ if {$a == 0} break
+ }
+ set a $b
+ incr arcn
+ lappend vrownum($v) $row
+ lappend varcorder($v) $a
+ lset varcix($v) $a $arcn
+ lset varcrow($v) $a $row
+ }
+ set vtokmod($v) [lindex $varctok($v) $p]
+ set varcmod($v) $p
+ set vrowmod($v) $row
+ if {[info exists currentid]} {
+ set selectedline [rowofcommit $currentid]
+ }
+}
+
+# Test whether view $v contains commit $id
+proc commitinview {id v} {
+ global varcid
+
+ return [info exists varcid($v,$id)]
+}
+
+# Return the row number for commit $id in the current view
+proc rowofcommit {id} {
+ global varcid varccommits varcrow curview cached_commitrow
+ global varctok vtokmod
+
+ set v $curview
+ if {![info exists varcid($v,$id)]} {
+ puts "oops rowofcommit no arc for [shortids $id]"
+ return {}
+ }
+ set a $varcid($v,$id)
+ if {[string compare [lindex $varctok($v) $a] $vtokmod($v)] >= 0} {
+ update_arcrows $v
+ }
+ if {[info exists cached_commitrow($id)]} {
+ return $cached_commitrow($id)
+ }
+ set i [lsearch -exact $varccommits($v,$a) $id]
+ if {$i < 0} {
+ puts "oops didn't find commit [shortids $id] in arc $a"
+ return {}
+ }
+ incr i [lindex $varcrow($v) $a]
+ set cached_commitrow($id) $i
+ return $i
+}
+
+# Returns 1 if a is on an earlier row than b, otherwise 0
+proc comes_before {a b} {
+ global varcid varctok curview
+
+ set v $curview
+ if {$a eq $b || ![info exists varcid($v,$a)] || \
+ ![info exists varcid($v,$b)]} {
+ return 0
+ }
+ if {$varcid($v,$a) != $varcid($v,$b)} {
+ return [expr {[string compare [lindex $varctok($v) $varcid($v,$a)] \
+ [lindex $varctok($v) $varcid($v,$b)]] < 0}]
+ }
+ return [expr {[rowofcommit $a] < [rowofcommit $b]}]
+}
+
+proc bsearch {l elt} {
+ if {[llength $l] == 0 || $elt <= [lindex $l 0]} {
+ return 0
+ }
+ set lo 0
+ set hi [llength $l]
+ while {$hi - $lo > 1} {
+ set mid [expr {int(($lo + $hi) / 2)}]
+ set t [lindex $l $mid]
+ if {$elt < $t} {
+ set hi $mid
+ } elseif {$elt > $t} {
+ set lo $mid
+ } else {
+ return $mid
+ }
+ }
+ return $lo
+}
+
+# Make sure rows $start..$end-1 are valid in displayorder and parentlist
+proc make_disporder {start end} {
+ global vrownum curview commitidx displayorder parentlist
+ global varccommits varcorder parents vrowmod varcrow
+ global d_valid_start d_valid_end
+
+ if {$end > $vrowmod($curview)} {
+ update_arcrows $curview
+ }
+ set ai [bsearch $vrownum($curview) $start]
+ set start [lindex $vrownum($curview) $ai]
+ set narc [llength $vrownum($curview)]
+ for {set r $start} {$ai < $narc && $r < $end} {incr ai} {
+ set a [lindex $varcorder($curview) $ai]
+ set l [llength $displayorder]
+ set al [llength $varccommits($curview,$a)]
+ if {$l < $r + $al} {
+ if {$l < $r} {
+ set pad [ntimes [expr {$r - $l}] {}]
+ set displayorder [concat $displayorder $pad]
+ set parentlist [concat $parentlist $pad]
+ } elseif {$l > $r} {
+ set displayorder [lrange $displayorder 0 [expr {$r - 1}]]
+ set parentlist [lrange $parentlist 0 [expr {$r - 1}]]
+ }
+ foreach id $varccommits($curview,$a) {
+ lappend displayorder $id
+ lappend parentlist $parents($curview,$id)
+ }
+ } elseif {[lindex $displayorder [expr {$r + $al - 1}]] eq {}} {
+ set i $r
+ foreach id $varccommits($curview,$a) {
+ lset displayorder $i $id
+ lset parentlist $i $parents($curview,$id)
+ incr i
+ }
+ }
+ incr r $al
+ }
+}
+
+proc commitonrow {row} {
+ global displayorder
+
+ set id [lindex $displayorder $row]
+ if {$id eq {}} {
+ make_disporder $row [expr {$row + 1}]
+ set id [lindex $displayorder $row]
+ }
+ return $id
+}
+
+proc closevarcs {v} {
+ global varctok varccommits varcid parents children
+ global cmitlisted commitidx vtokmod
+
+ set missing_parents 0
+ set scripts {}
+ set narcs [llength $varctok($v)]
+ for {set a 1} {$a < $narcs} {incr a} {
+ set id [lindex $varccommits($v,$a) end]
+ foreach p $parents($v,$id) {
+ if {[info exists varcid($v,$p)]} continue
+ # add p as a new commit
+ incr missing_parents
+ set cmitlisted($v,$p) 0
+ set parents($v,$p) {}
+ if {[llength $children($v,$p)] == 1 &&
+ [llength $parents($v,$id)] == 1} {
+ set b $a
+ } else {
+ set b [newvarc $v $p]
+ }
+ set varcid($v,$p) $b
+ if {[string compare [lindex $varctok($v) $b] $vtokmod($v)] < 0} {
+ modify_arc $v $b
+ }
+ lappend varccommits($v,$b) $p
+ incr commitidx($v)
+ set scripts [check_interest $p $scripts]
+ }
+ }
+ if {$missing_parents > 0} {
+ foreach s $scripts {
+ eval $s
+ }
+ }
+}
+
+# Use $rwid as a substitute for $id, i.e. reparent $id's children to $rwid
+# Assumes we already have an arc for $rwid.
+proc rewrite_commit {v id rwid} {
+ global children parents varcid varctok vtokmod varccommits
+
+ foreach ch $children($v,$id) {
+ # make $rwid be $ch's parent in place of $id
+ set i [lsearch -exact $parents($v,$ch) $id]
+ if {$i < 0} {
+ puts "oops rewrite_commit didn't find $id in parent list for $ch"
+ }
+ set parents($v,$ch) [lreplace $parents($v,$ch) $i $i $rwid]
+ # add $ch to $rwid's children and sort the list if necessary
+ if {[llength [lappend children($v,$rwid) $ch]] > 1} {
+ set children($v,$rwid) [lsort -command [list vtokcmp $v] \
+ $children($v,$rwid)]
+ }
+ # fix the graph after joining $id to $rwid
+ set a $varcid($v,$ch)
+ fix_reversal $rwid $a $v
+ # parentlist is wrong for the last element of arc $a
+ # even if displayorder is right, hence the 3rd arg here
+ modify_arc $v $a [expr {[llength $varccommits($v,$a)] - 1}]
+ }
+}
+
+# Mechanism for registering a command to be executed when we come
+# across a particular commit. To handle the case when only the
+# prefix of the commit is known, the commitinterest array is now
+# indexed by the first 4 characters of the ID. Each element is a
+# list of id, cmd pairs.
+proc interestedin {id cmd} {
+ global commitinterest
+
+ lappend commitinterest([string range $id 0 3]) $id $cmd
+}
+
+proc check_interest {id scripts} {
+ global commitinterest
+
+ set prefix [string range $id 0 3]
+ if {[info exists commitinterest($prefix)]} {
+ set newlist {}
+ foreach {i script} $commitinterest($prefix) {
+ if {[string match "$i*" $id]} {
+ lappend scripts [string map [list "%I" $id "%P" $i] $script]
+ } else {
+ lappend newlist $i $script
+ }
+ }
+ if {$newlist ne {}} {
+ set commitinterest($prefix) $newlist
+ } else {
+ unset commitinterest($prefix)
+ }
+ }
+ return $scripts
+}
+
+proc getcommitlines {fd inst view updating} {
+ global cmitlisted leftover
+ global commitidx commitdata vdatemode
+ global parents children curview hlview
+ global idpending ordertok
+ global varccommits varcid varctok vtokmod vfilelimit
+
+ set stuff [read $fd 500000]
+ # git log doesn't terminate the last commit with a null...
+ if {$stuff == {} && $leftover($inst) ne {} && [eof $fd]} {
+ set stuff "\0"
+ }
+ if {$stuff == {}} {
+ if {![eof $fd]} {
+ return 1
+ }
+ global commfd viewcomplete viewactive viewname
+ global viewinstances
+ unset commfd($inst)
+ set i [lsearch -exact $viewinstances($view) $inst]
+ if {$i >= 0} {
+ set viewinstances($view) [lreplace $viewinstances($view) $i $i]
+ }
+ # set it blocking so we wait for the process to terminate
+ fconfigure $fd -blocking 1
+ if {[catch {close $fd} err]} {
+ set fv {}
+ if {$view != $curview} {
+ set fv " for the \"$viewname($view)\" view"
+ }
+ if {[string range $err 0 4] == "usage"} {
+ set err "Gitk: error reading commits$fv:\
+ bad arguments to git log."
+ if {$viewname($view) eq "Command line"} {
+ append err \
+ " (Note: arguments to gitk are passed to git log\
+ to allow selection of commits to be displayed.)"
+ }
+ } else {
+ set err "Error reading commits$fv: $err"
+ }
+ error_popup $err
+ }
+ if {[incr viewactive($view) -1] <= 0} {
+ set viewcomplete($view) 1
+ # Check if we have seen any ids listed as parents that haven't
+ # appeared in the list
+ closevarcs $view
+ notbusy $view
+ }
+ if {$view == $curview} {
+ run chewcommits
+ }
+ return 0
+ }
+ set start 0
+ set gotsome 0
+ set scripts {}
+ while 1 {
+ set i [string first "\0" $stuff $start]
+ if {$i < 0} {
+ append leftover($inst) [string range $stuff $start end]
+ break
+ }
+ if {$start == 0} {
+ set cmit $leftover($inst)
+ append cmit [string range $stuff 0 [expr {$i - 1}]]
+ set leftover($inst) {}
+ } else {
+ set cmit [string range $stuff $start [expr {$i - 1}]]
+ }
+ set start [expr {$i + 1}]
+ set j [string first "\n" $cmit]
+ set ok 0
+ set listed 1
+ if {$j >= 0 && [string match "commit *" $cmit]} {
+ set ids [string range $cmit 7 [expr {$j - 1}]]
+ if {[string match {[-^<>]*} $ids]} {
+ switch -- [string index $ids 0] {
+ "-" {set listed 0}
+ "^" {set listed 2}
+ "<" {set listed 3}
+ ">" {set listed 4}
+ }
+ set ids [string range $ids 1 end]
+ }
+ set ok 1
+ foreach id $ids {
+ if {[string length $id] != 40} {
+ set ok 0
+ break
+ }
+ }
+ }
+ if {!$ok} {
+ set shortcmit $cmit
+ if {[string length $shortcmit] > 80} {
+ set shortcmit "[string range $shortcmit 0 80]..."
+ }
+ error_popup "[mc "Can't parse git log output:"] {$shortcmit}"
+ exit 1
+ }
+ set id [lindex $ids 0]
+ set vid $view,$id
+
+ if {!$listed && $updating && ![info exists varcid($vid)] &&
+ $vfilelimit($view) ne {}} {
+ # git log doesn't rewrite parents for unlisted commits
+ # when doing path limiting, so work around that here
+ # by working out the rewritten parent with git rev-list
+ # and if we already know about it, using the rewritten
+ # parent as a substitute parent for $id's children.
+ if {![catch {
+ set rwid [exec git rev-list --first-parent --max-count=1 \
+ $id -- $vfilelimit($view)]
+ }]} {
+ if {$rwid ne {} && [info exists varcid($view,$rwid)]} {
+ # use $rwid in place of $id
+ rewrite_commit $view $id $rwid
+ continue
+ }
+ }
+ }
+
+ set a 0
+ if {[info exists varcid($vid)]} {
+ if {$cmitlisted($vid) || !$listed} continue
+ set a $varcid($vid)
+ }
+ if {$listed} {
+ set olds [lrange $ids 1 end]
+ } else {
+ set olds {}
+ }
+ set commitdata($id) [string range $cmit [expr {$j + 1}] end]
+ set cmitlisted($vid) $listed
+ set parents($vid) $olds
+ if {![info exists children($vid)]} {
+ set children($vid) {}
+ } elseif {$a == 0 && [llength $children($vid)] == 1} {
+ set k [lindex $children($vid) 0]
+ if {[llength $parents($view,$k)] == 1 &&
+ (!$vdatemode($view) ||
+ $varcid($view,$k) == [llength $varctok($view)] - 1)} {
+ set a $varcid($view,$k)
+ }
+ }
+ if {$a == 0} {
+ # new arc
+ set a [newvarc $view $id]
+ }
+ if {[string compare [lindex $varctok($view) $a] $vtokmod($view)] < 0} {
+ modify_arc $view $a
+ }
+ if {![info exists varcid($vid)]} {
+ set varcid($vid) $a
+ lappend varccommits($view,$a) $id
+ incr commitidx($view)
+ }
+
+ set i 0
+ foreach p $olds {
+ if {$i == 0 || [lsearch -exact $olds $p] >= $i} {
+ set vp $view,$p
+ if {[llength [lappend children($vp) $id]] > 1 &&
+ [vtokcmp $view [lindex $children($vp) end-1] $id] > 0} {
+ set children($vp) [lsort -command [list vtokcmp $view] \
+ $children($vp)]
+ catch {unset ordertok}
+ }
+ if {[info exists varcid($view,$p)]} {
+ fix_reversal $p $a $view
+ }
+ }
+ incr i
+ }
+
+ set scripts [check_interest $id $scripts]
+ set gotsome 1
+ }
+ if {$gotsome} {
+ global numcommits hlview
+
+ if {$view == $curview} {
+ set numcommits $commitidx($view)
+ run chewcommits
+ }
+ if {[info exists hlview] && $view == $hlview} {
+ # we never actually get here...
+ run vhighlightmore
+ }
+ foreach s $scripts {
+ eval $s
+ }
+ }
+ return 2
+}
+
+proc chewcommits {} {
+ global curview hlview viewcomplete
+ global pending_select
+
+ layoutmore
+ if {$viewcomplete($curview)} {
+ global commitidx varctok
+ global numcommits startmsecs
+
+ if {[info exists pending_select]} {
+ update
+ reset_pending_select {}
+
+ if {[commitinview $pending_select $curview]} {
+ selectline [rowofcommit $pending_select] 1
+ } else {
+ set row [first_real_row]
+ selectline $row 1
+ }
+ }
+ if {$commitidx($curview) > 0} {
+ #set ms [expr {[clock clicks -milliseconds] - $startmsecs}]
+ #puts "overall $ms ms for $numcommits commits"
+ #puts "[llength $varctok($view)] arcs, $commitidx($view) commits"
+ } else {
+ show_status [mc "No commits selected"]
+ }
+ notbusy layout
+ }
+ return 0
+}
+
+proc do_readcommit {id} {
+ global tclencoding
+
+ # Invoke git-log to handle automatic encoding conversion
+ set fd [open [concat | git log --no-color --pretty=raw -1 $id] r]
+ # Read the results using i18n.logoutputencoding
+ fconfigure $fd -translation lf -eofchar {}
+ if {$tclencoding != {}} {
+ fconfigure $fd -encoding $tclencoding
+ }
+ set contents [read $fd]
+ close $fd
+ # Remove the heading line
+ regsub {^commit [0-9a-f]+\n} $contents {} contents
+
+ return $contents
+}
+
+proc readcommit {id} {
+ if {[catch {set contents [do_readcommit $id]}]} return
+ parsecommit $id $contents 1
+}
+
+proc parsecommit {id contents listed} {
+ global commitinfo cdate
+
+ set inhdr 1
+ set comment {}
+ set headline {}
+ set auname {}
+ set audate {}
+ set comname {}
+ set comdate {}
+ set hdrend [string first "\n\n" $contents]
+ if {$hdrend < 0} {
+ # should never happen...
+ set hdrend [string length $contents]
+ }
+ set header [string range $contents 0 [expr {$hdrend - 1}]]
+ set comment [string range $contents [expr {$hdrend + 2}] end]
+ foreach line [split $header "\n"] {
+ set line [split $line " "]
+ set tag [lindex $line 0]
+ if {$tag == "author"} {
+ set audate [lindex $line end-1]
+ set auname [join [lrange $line 1 end-2] " "]
+ } elseif {$tag == "committer"} {
+ set comdate [lindex $line end-1]
+ set comname [join [lrange $line 1 end-2] " "]
+ }
+ }
+ set headline {}
+ # take the first non-blank line of the comment as the headline
+ set headline [string trimleft $comment]
+ set i [string first "\n" $headline]
+ if {$i >= 0} {
+ set headline [string range $headline 0 $i]
+ }
+ set headline [string trimright $headline]
+ set i [string first "\r" $headline]
+ if {$i >= 0} {
+ set headline [string trimright [string range $headline 0 $i]]
+ }
+ if {!$listed} {
+ # git log indents the comment by 4 spaces;
+ # if we got this via git cat-file, add the indentation
+ set newcomment {}
+ foreach line [split $comment "\n"] {
+ append newcomment " "
+ append newcomment $line
+ append newcomment "\n"
+ }
+ set comment $newcomment
+ }
+ if {$comdate != {}} {
+ set cdate($id) $comdate
+ }
+ set commitinfo($id) [list $headline $auname $audate \
+ $comname $comdate $comment]
+}
+
+proc getcommit {id} {
+ global commitdata commitinfo
+
+ if {[info exists commitdata($id)]} {
+ parsecommit $id $commitdata($id) 1
+ } else {
+ readcommit $id
+ if {![info exists commitinfo($id)]} {
+ set commitinfo($id) [list [mc "No commit information available"]]
+ }
+ }
+ return 1
+}
+
+# Expand an abbreviated commit ID to a list of full 40-char IDs that match
+# and are present in the current view.
+# This is fairly slow...
+proc longid {prefix} {
+ global varcid curview
+
+ set ids {}
+ foreach match [array names varcid "$curview,$prefix*"] {
+ lappend ids [lindex [split $match ","] 1]
+ }
+ return $ids
+}
+
+proc readrefs {} {
+ global tagids idtags headids idheads tagobjid
+ global otherrefids idotherrefs mainhead mainheadid
+ global selecthead selectheadid
+ global hideremotes
+
+ foreach v {tagids idtags headids idheads otherrefids idotherrefs} {
+ catch {unset $v}
+ }
+ set refd [open [list | git show-ref -d] r]
+ while {[gets $refd line] >= 0} {
+ if {[string index $line 40] ne " "} continue
+ set id [string range $line 0 39]
+ set ref [string range $line 41 end]
+ if {![string match "refs/*" $ref]} continue
+ set name [string range $ref 5 end]
+ if {[string match "remotes/*" $name]} {
+ if {![string match "*/HEAD" $name] && !$hideremotes} {
+ set headids($name) $id
+ lappend idheads($id) $name
+ }
+ } elseif {[string match "heads/*" $name]} {
+ set name [string range $name 6 end]
+ set headids($name) $id
+ lappend idheads($id) $name
+ } elseif {[string match "tags/*" $name]} {
+ # this lets refs/tags/foo^{} overwrite refs/tags/foo,
+ # which is what we want since the former is the commit ID
+ set name [string range $name 5 end]
+ if {[string match "*^{}" $name]} {
+ set name [string range $name 0 end-3]
+ } else {
+ set tagobjid($name) $id
+ }
+ set tagids($name) $id
+ lappend idtags($id) $name
+ } else {
+ set otherrefids($name) $id
+ lappend idotherrefs($id) $name
+ }
+ }
+ catch {close $refd}
+ set mainhead {}
+ set mainheadid {}
+ catch {
+ set mainheadid [exec git rev-parse HEAD]
+ set thehead [exec git symbolic-ref HEAD]
+ if {[string match "refs/heads/*" $thehead]} {
+ set mainhead [string range $thehead 11 end]
+ }
+ }
+ set selectheadid {}
+ if {$selecthead ne {}} {
+ catch {
+ set selectheadid [exec git rev-parse --verify $selecthead]
+ }
+ }
+}
+
+# skip over fake commits
+proc first_real_row {} {
+ global nullid nullid2 numcommits
+
+ for {set row 0} {$row < $numcommits} {incr row} {
+ set id [commitonrow $row]
+ if {$id ne $nullid && $id ne $nullid2} {
+ break
+ }
+ }
+ return $row
+}
+
+# update things for a head moved to a child of its previous location
+proc movehead {id name} {
+ global headids idheads
+
+ removehead $headids($name) $name
+ set headids($name) $id
+ lappend idheads($id) $name
+}
+
+# update things when a head has been removed
+proc removehead {id name} {
+ global headids idheads
+
+ if {$idheads($id) eq $name} {
+ unset idheads($id)
+ } else {
+ set i [lsearch -exact $idheads($id) $name]
+ if {$i >= 0} {
+ set idheads($id) [lreplace $idheads($id) $i $i]
+ }
+ }
+ unset headids($name)
+}
+
+proc ttk_toplevel {w args} {
+ global use_ttk
+ eval [linsert $args 0 ::toplevel $w]
+ if {$use_ttk} {
+ place [ttk::frame $w._toplevel_background] -x 0 -y 0 -relwidth 1 -relheight 1
+ }
+ return $w
+}
+
+proc make_transient {window origin} {
+ global have_tk85
+
+ # In MacOS Tk 8.4 transient appears to work by setting
+ # overrideredirect, which is utterly useless, since the
+ # windows get no border, and are not even kept above
+ # the parent.
+ if {!$have_tk85 && [tk windowingsystem] eq {aqua}} return
+
+ wm transient $window $origin
+
+ # Windows fails to place transient windows normally, so
+ # schedule a callback to center them on the parent.
+ if {[tk windowingsystem] eq {win32}} {
+ after idle [list tk::PlaceWindow $window widget $origin]
+ }
+}
+
+proc show_error {w top msg {mc mc}} {
+ global NS
+ if {![info exists NS]} {set NS ""}
+ if {[wm state $top] eq "withdrawn"} { wm deiconify $top }
+ message $w.m -text $msg -justify center -aspect 400
+ pack $w.m -side top -fill x -padx 20 -pady 20
+ ${NS}::button $w.ok -default active -text [$mc OK] -command "destroy $top"
+ pack $w.ok -side bottom -fill x
+ bind $top "grab $top; focus $top"
+ bind $top "destroy $top"
+ bind $top "destroy $top"
+ bind $top "destroy $top"
+ tkwait window $top
+}
+
+proc error_popup {msg {owner .}} {
+ if {[tk windowingsystem] eq "win32"} {
+ tk_messageBox -icon error -type ok -title [wm title .] \
+ -parent $owner -message $msg
+ } else {
+ set w .error
+ ttk_toplevel $w
+ make_transient $w $owner
+ show_error $w $w $msg
+ }
+}
+
+proc confirm_popup {msg {owner .}} {
+ global confirm_ok NS
+ set confirm_ok 0
+ set w .confirm
+ ttk_toplevel $w
+ make_transient $w $owner
+ message $w.m -text $msg -justify center -aspect 400
+ pack $w.m -side top -fill x -padx 20 -pady 20
+ ${NS}::button $w.ok -text [mc OK] -command "set confirm_ok 1; destroy $w"
+ pack $w.ok -side left -fill x
+ ${NS}::button $w.cancel -text [mc Cancel] -command "destroy $w"
+ pack $w.cancel -side right -fill x
+ bind $w "grab $w; focus $w"
+ bind $w "set confirm_ok 1; destroy $w"
+ bind $w "set confirm_ok 1; destroy $w"
+ bind $w "destroy $w"
+ tk::PlaceWindow $w widget $owner
+ tkwait window $w
+ return $confirm_ok
+}
+
+proc setoptions {} {
+ if {[tk windowingsystem] ne "win32"} {
+ option add *Panedwindow.showHandle 1 startupFile
+ option add *Panedwindow.sashRelief raised startupFile
+ if {[tk windowingsystem] ne "aqua"} {
+ option add *Menu.font uifont startupFile
+ }
+ } else {
+ option add *Menu.TearOff 0 startupFile
+ }
+ option add *Button.font uifont startupFile
+ option add *Checkbutton.font uifont startupFile
+ option add *Radiobutton.font uifont startupFile
+ option add *Menubutton.font uifont startupFile
+ option add *Label.font uifont startupFile
+ option add *Message.font uifont startupFile
+ option add *Entry.font textfont startupFile
+ option add *Text.font textfont startupFile
+ option add *Labelframe.font uifont startupFile
+ option add *Spinbox.font textfont startupFile
+ option add *Listbox.font mainfont startupFile
+}
+
+# Make a menu and submenus.
+# m is the window name for the menu, items is the list of menu items to add.
+# Each item is a list {mc label type description options...}
+# mc is ignored; it's so we can put mc there to alert xgettext
+# label is the string that appears in the menu
+# type is cascade, command or radiobutton (should add checkbutton)
+# description depends on type; it's the sublist for cascade, the
+# command to invoke for command, or {variable value} for radiobutton
+proc makemenu {m items} {
+ menu $m
+ if {[tk windowingsystem] eq {aqua}} {
+ set Meta1 Cmd
+ } else {
+ set Meta1 Ctrl
+ }
+ foreach i $items {
+ set name [mc [lindex $i 1]]
+ set type [lindex $i 2]
+ set thing [lindex $i 3]
+ set params [list $type]
+ if {$name ne {}} {
+ set u [string first "&" [string map {&& x} $name]]
+ lappend params -label [string map {&& & & {}} $name]
+ if {$u >= 0} {
+ lappend params -underline $u
+ }
+ }
+ switch -- $type {
+ "cascade" {
+ set submenu [string tolower [string map {& ""} [lindex $i 1]]]
+ lappend params -menu $m.$submenu
+ }
+ "command" {
+ lappend params -command $thing
+ }
+ "radiobutton" {
+ lappend params -variable [lindex $thing 0] \
+ -value [lindex $thing 1]
+ }
+ }
+ set tail [lrange $i 4 end]
+ regsub -all {\yMeta1\y} $tail $Meta1 tail
+ eval $m add $params $tail
+ if {$type eq "cascade"} {
+ makemenu $m.$submenu $thing
+ }
+ }
+}
+
+# translate string and remove ampersands
+proc mca {str} {
+ return [string map {&& & & {}} [mc $str]]
+}
+
+proc makedroplist {w varname args} {
+ global use_ttk
+ if {$use_ttk} {
+ set width 0
+ foreach label $args {
+ set cx [string length $label]
+ if {$cx > $width} {set width $cx}
+ }
+ set gm [ttk::combobox $w -width $width -state readonly\
+ -textvariable $varname -values $args]
+ } else {
+ set gm [eval [linsert $args 0 tk_optionMenu $w $varname]]
+ }
+ return $gm
+}
+
+proc makewindow {} {
+ global canv canv2 canv3 linespc charspc ctext cflist cscroll
+ global tabstop
+ global findtype findtypemenu findloc findstring fstring geometry
+ global entries sha1entry sha1string sha1but
+ global diffcontextstring diffcontext
+ global ignorespace
+ global maincursor textcursor curtextcursor
+ global rowctxmenu fakerowmenu mergemax wrapcomment
+ global highlight_files gdttype
+ global searchstring sstring
+ global bgcolor fgcolor bglist fglist diffcolors selectbgcolor
+ global headctxmenu progresscanv progressitem progresscoords statusw
+ global fprogitem fprogcoord lastprogupdate progupdatepending
+ global rprogitem rprogcoord rownumsel numcommits
+ global have_tk85 use_ttk NS
+ global git_version
+ global worddiff
+
+ # The "mc" arguments here are purely so that xgettext
+ # sees the following string as needing to be translated
+ set file {
+ mc "File" cascade {
+ {mc "Update" command updatecommits -accelerator F5}
+ {mc "Reload" command reloadcommits -accelerator Meta1-F5}
+ {mc "Reread references" command rereadrefs}
+ {mc "List references" command showrefs -accelerator F2}
+ {xx "" separator}
+ {mc "Start git gui" command {exec git gui &}}
+ {xx "" separator}
+ {mc "Quit" command doquit -accelerator Meta1-Q}
+ }}
+ set edit {
+ mc "Edit" cascade {
+ {mc "Preferences" command doprefs}
+ }}
+ set view {
+ mc "View" cascade {
+ {mc "New view..." command {newview 0} -accelerator Shift-F4}
+ {mc "Edit view..." command editview -state disabled -accelerator F4}
+ {mc "Delete view" command delview -state disabled}
+ {xx "" separator}
+ {mc "All files" radiobutton {selectedview 0} -command {showview 0}}
+ }}
+ if {[tk windowingsystem] ne "aqua"} {
+ set help {
+ mc "Help" cascade {
+ {mc "About gitk" command about}
+ {mc "Key bindings" command keys}
+ }}
+ set bar [list $file $edit $view $help]
+ } else {
+ proc ::tk::mac::ShowPreferences {} {doprefs}
+ proc ::tk::mac::Quit {} {doquit}
+ lset file end [lreplace [lindex $file end] end-1 end]
+ set apple {
+ xx "Apple" cascade {
+ {mc "About gitk" command about}
+ {xx "" separator}
+ }}
+ set help {
+ mc "Help" cascade {
+ {mc "Key bindings" command keys}
+ }}
+ set bar [list $apple $file $view $help]
+ }
+ makemenu .bar $bar
+ . configure -menu .bar
+
+ if {$use_ttk} {
+ # cover the non-themed toplevel with a themed frame.
+ place [ttk::frame ._main_background] -x 0 -y 0 -relwidth 1 -relheight 1
+ }
+
+ # the gui has upper and lower half, parts of a paned window.
+ ${NS}::panedwindow .ctop -orient vertical
+
+ # possibly use assumed geometry
+ if {![info exists geometry(pwsash0)]} {
+ set geometry(topheight) [expr {15 * $linespc}]
+ set geometry(topwidth) [expr {80 * $charspc}]
+ set geometry(botheight) [expr {15 * $linespc}]
+ set geometry(botwidth) [expr {50 * $charspc}]
+ set geometry(pwsash0) [list [expr {40 * $charspc}] 2]
+ set geometry(pwsash1) [list [expr {60 * $charspc}] 2]
+ }
+
+ # the upper half will have a paned window, a scroll bar to the right, and some stuff below
+ ${NS}::frame .tf -height $geometry(topheight) -width $geometry(topwidth)
+ ${NS}::frame .tf.histframe
+ ${NS}::panedwindow .tf.histframe.pwclist -orient horizontal
+ if {!$use_ttk} {
+ .tf.histframe.pwclist configure -sashpad 0 -handlesize 4
+ }
+
+ # create three canvases
+ set cscroll .tf.histframe.csb
+ set canv .tf.histframe.pwclist.canv
+ canvas $canv \
+ -selectbackground $selectbgcolor \
+ -background $bgcolor -bd 0 \
+ -yscrollincr $linespc -yscrollcommand "scrollcanv $cscroll"
+ .tf.histframe.pwclist add $canv
+ set canv2 .tf.histframe.pwclist.canv2
+ canvas $canv2 \
+ -selectbackground $selectbgcolor \
+ -background $bgcolor -bd 0 -yscrollincr $linespc
+ .tf.histframe.pwclist add $canv2
+ set canv3 .tf.histframe.pwclist.canv3
+ canvas $canv3 \
+ -selectbackground $selectbgcolor \
+ -background $bgcolor -bd 0 -yscrollincr $linespc
+ .tf.histframe.pwclist add $canv3
+ if {$use_ttk} {
+ bind .tf.histframe.pwclist