Skip to content

Revised: Open in Xcode - #7369

Closed
msztech wants to merge 6 commits into
desktop:developmentfrom
msztech:upstream-master
Closed

msztech wants to merge 6 commits into
desktop:developmentfrom
msztech:upstream-master

Conversation

@msztech

@msztech msztech commented Apr 20, 2019

Copy link
Copy Markdown
Contributor

Overview

Adding support for Xcode as an external editor on Mac OS. PR from Issue #4825

Description

Now, Xcode can be used to open a path or a file. To do so, users will set Xcode as the default editor in Preferences->Advanced->External Editor and select Xcode (which will appear as a menu option if it's installed in the system). After the setup, users can right-click on a repository menu item or a file and select 'open in Xcode'

Release notes

  • Add Xcode support as a default editor option for Mac OS users.

Notes:

  • This is a revision from PR 7150
  • This feature is only supported on Mac OS.

@niik

Shunzhe added 3 commits April 20, 2019 16:10
Revised the open in Xcode feature according to the guide on external editors. Now, users can select Xcode as the default editor in perferences and open up a repo or a file with Xcode.
@msztech msztech mentioned this pull request Apr 20, 2019
@billygriffin

Copy link
Copy Markdown
Contributor

Thanks @msztech! I'll defer to @niik or someone else on @desktop/engineering on the review of this, but just wanted to thank you for reworking your original PR to use our conventions. I'm assuming there may be some weirdness around XCode not being able to cleanly open a directory and curious to see how that plays out.

@billygriffin billygriffin added the ready-for-review Pull Requests that are ready to be reviewed by the maintainers label Apr 22, 2019
@msztech

msztech commented Apr 22, 2019

Copy link
Copy Markdown
Contributor Author

Thanks @billygriffin!

Yes. Xcode shows an error message when it cannot find a project file in the path. I’m definitely willing to further revise this if there’s any work arounds.

@iAmWillShepherd iAmWillShepherd self-assigned this May 2, 2019
@iAmWillShepherd

Copy link
Copy Markdown
Contributor

Verified this works for Xcode Projects and does not work for non Xcode projects (folders with no xcodeproj file present). I think this is OK since this makes the experience better for folks using Xcode and users can easily switch editors if they get the error I got below.

Non-Xcode Project
2019-05-03 09 48 36

Xcode Project
2019-05-03 09 53 43

iAmWillShepherd
iAmWillShepherd previously approved these changes May 3, 2019

@iAmWillShepherd iAmWillShepherd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although this does not work for non-Xcode projects, I think that is fine given the type of development that happens in this IDE.

@iAmWillShepherd

Copy link
Copy Markdown
Contributor

Thanks for getting this implemented, @msztech 💟

@msztech

msztech commented May 3, 2019

Copy link
Copy Markdown
Contributor Author

Thank you! I’m glad to be able to contribute to this project! @iAmWillShepherd

@iAmWillShepherd

iAmWillShepherd commented May 3, 2019 •

Copy link
Copy Markdown
Contributor

@msztech, sorry to have to ask for this, but are you able to also add a check if there is a xcodeproj file in the directory? I now see you asked this, but never got a response and I apologize for that. We sometimes miss things like that. Adding that check should help prevent older versions of Xcode from failing when users don't have the latest version.

Should I check if the folder contains a Xcode project when rendering UI? (So hide the option to open in Xcode if there's no project files)

☝️ I like this approach

@msztech

msztech commented May 3, 2019 •

Copy link
Copy Markdown
Contributor Author

@iAmWillShepherd Sure! I can definitely add the check so that if there's the file (Xcode project or Xcode workspace project), invoke Xcode; if there's not, open the Desktop dialog to show an error message.

I'll push the edition to this PR ASAP.

@msztech

msztech commented May 3, 2019

Copy link
Copy Markdown
Contributor Author

@iAmWillShepherd Is there any included libraries in Desktop that work with files? like listing all the files in one directory?

@iAmWillShepherd

Copy link
Copy Markdown
Contributor

Yep, you can use FS. Here's an example of it being used in Desktop.

const files = fs.readdirSync(licensesDir)

You'd want to use the async version however, so you may want to do something like: const files = await fs.readdir().

@msztech

msztech commented May 3, 2019 •

Copy link
Copy Markdown
Contributor Author

Hi @iAmWillShepherd, I have written a function to check whether an Xcode file exists in a path. But the yarn compiler always shows Not all code paths return a value.. I have tried to add return statements in every possible cases I can think of. Could you give me some suggestions on this piece of code? Thanks in advance!

/*
  Check if a path contains an Xcode file.
*/
async function hasXcodeFile(fullPath: string): Promise<boolean> {
  try {
    await fs.readdir(fullPath, (err, files) => {
      files.forEach(filePath => {
        if (
          filePath.indexOf('xcodeproj') != -1 ||
          filePath.indexOf('xcworkspaces') != -1
        ) {
          return true
        }
      })
      return false
    })
    return false
  } finally { return false }
  return false
}

@shiftkey

shiftkey commented May 6, 2019

Copy link
Copy Markdown
Member

@msztech I'd recommend using glob rather than the fs APIs directly as it has great built-in support for wildcards and exploring nested directories. Here's a rough patch of the changes that I think you'll need to add:

diff --git a/app/package.json b/app/package.json
index 6da749cdb..8373dccbc 100644
--- a/app/package.json
+++ b/app/package.json
@@ -34,6 +34,7 @@
     "fs-admin": "^0.3.0",
     "fs-extra": "^6.0.0",
     "fuzzaldrin-plus": "^0.6.0",
+    "glob": "^7.1.3",
     "keytar": "^4.4.1",
     "memoize-one": "^4.0.3",
     "moment": "^2.24.0",
diff --git a/app/src/lib/file-system.ts b/app/src/lib/file-system.ts
index a696107c6..60d0950e7 100644
--- a/app/src/lib/file-system.ts
+++ b/app/src/lib/file-system.ts
@@ -1,6 +1,7 @@
 import * as FSE from 'fs-extra'
 import * as Os from 'os'
 import * as Path from 'path'
+import * as glob from 'glob'
 import { Disposable } from 'event-kit'
 import { Tailer } from './tailer'
 
@@ -112,3 +113,24 @@ export async function readPartialFile(
       .on('end', () => resolve(Buffer.concat(chunks, total)))
   })
 }
+
+/**
+ * Find files matching a given pattern on disk.
+ *
+ * Wraps the `glob` library to return a promise.
+ */
+export async function findFilesMatching(
+  pattern: string,
+  cwd: string
+): Promise<ReadonlyArray<string>> {
+  return new Promise<ReadonlyArray<string>>((resolve, reject) => {
+    glob(pattern, { cwd }, (error, files) => {
+      if (error != null) {
+        reject(error)
+        return
+      }
+
+      resolve(files)
+    })
+  })
+}
diff --git a/app/yarn.lock b/app/yarn.lock
index 22500b6e1..451c05a07 100644
--- a/app/yarn.lock
+++ b/app/yarn.lock
@@ -627,6 +627,18 @@ glob@^7.0.5:
     once "^1.3.0"
     path-is-absolute "^1.0.0"
 
+glob@^7.1.3:
+  version "7.1.3"
+  resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.3.tgz#3960832d3f1574108342dafd3a67b332c0969df1"
+  integrity sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==
+  dependencies:
+    fs.realpath "^1.0.0"
+    inflight "^1.0.4"
+    inherits "2"
+    minimatch "^3.0.4"
+    once "^1.3.0"
+    path-is-absolute "^1.0.0"
+
 graceful-fs@^4.1.2, graceful-fs@^4.1.6:
   version "4.1.11"
   resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658"

And findFilesMatching could be used like this when launching the editor:

diff --git a/app/src/lib/editors/launch.ts b/app/src/lib/editors/launch.ts
index 544774946..5d5be7aa1 100644
--- a/app/src/lib/editors/launch.ts
+++ b/app/src/lib/editors/launch.ts
@@ -1,6 +1,8 @@
 import { spawn } from 'child_process'
 import { pathExists } from 'fs-extra'
 import { ExternalEditorError, FoundEditor } from './shared'
+import { ExternalEditor as Darwin } from './darwin'
+import { findFilesMatching } from '../file-system'
 
 /**
  * Open a given file or folder in the desired external editor.
@@ -12,6 +14,15 @@ export async function launchExternalEditor(
   fullPath: string,
   editor: FoundEditor
 ): Promise<void> {
+  if (editor.editor === Darwin.Xcode) {
+    const projectFiles = await findFilesMatching('*.xcodeproj', fullPath)
+    const workspaces = await findFilesMatching('*.xcworkspaces', fullPath)
+
+    if (projectFiles.length === 0 || workspaces.length === 0) {
+      // TODO: we shouldn't launch Xcode here, right?
+    }
+  }
+
   const editorPath = editor.path
   const exists = await pathExists(editorPath)
   if (!exists) {

You might want to do the check at a different stage in the workflow, which is fine. But ☝️ would be a convenient spot to test the function and ensure it's working as expected.

@shiftkey
shiftkey dismissed iAmWillShepherd’s stale review May 6, 2019 13:29

Looks like we have a discussion about improving the detection of XCode-specific files

@iAmWillShepherd

Copy link
Copy Markdown
Contributor

But the yarn compiler always shows Not all code paths return a value.. I have tried to add return statements in every possible cases I can think of. Could you give me some suggestions on this piece of code?

What @shiftkey suggested is right, but I still wanted to answer your question as to why your function wouldn't compile.

The problem is your function signature is defined as string -> Promise<boolean>

async function hasXcodeFile(fullPath: string): Promise<boolean>

But, FS.readdir is a function that returns void because it uses a callback for async flow.

Screen Shot 2019-05-06 at 9 19 16 AM

Notice how callback has the signature, (NodeJS.ErrnoException, string[]) -> void?

The function that was passed in does not match that signature, however.

files.forEach(filePath => {
  if (
    filePath.indexOf('xcodeproj') != -1 ||
    filePath.indexOf('xcworkspaces') != -1
  ) {
    return true
  }
})

return false

In this case, the function Array.prototype.forEach has the signature ((string, number, string[]) -> void, any) -> void.

Screen Shot 2019-05-06 at 9 26 44 AM

But, the callback being passed to Array##forEach has the signature string -> boolean which violates what this function expects.

If you change the function you're passing to Array##forEach to the following, your current type error will go away.

files.forEach(filePath => {
  if (
    filePath.indexOf('xcodeproj') != -1 ||
    filePath.indexOf('xcworkspaces') != -1
  ) {
    return
  }
})

I think the underlying problem is that we use async/await for asynchronous flow while Node uses callbacks and mixing the two ways of doing things can be confusing. There is a function defined in a library called Util that can help turn a callback-based signature into promise-based one.

async function hasXcodeFile(fullPath: string): Promise<boolean> {
  // convert callback to promise
  const promisifiedReaddir = util.promisify(fs.readdir)

  try {
    // now we can use async/await semantics
    const files = await promisifiedReaddir(fullPath)

    // return true if any path includes 'xcodeproj' or 'xcworkspaces'
    return files.some(
      path => path.includes('xcodeproj') || path.includes('xcworkspaces')
    )
  } catch {
    // somethign went wrong, bail with default value
    return false
  }
}

I hope that provides a bit of insight into why the TS compiler was complaining. It didn't really have much to do with your code paths not returning a value, but not return the proper type of value.

@shiftkey

Copy link
Copy Markdown
Member

Dropping ready-for-review because it seems like there are more changes here based on the comment in #7369 (comment) and subsequent discussion about how to achieve it.

@shiftkey shiftkey removed the ready-for-review Pull Requests that are ready to be reviewed by the maintainers label May 13, 2019
@iAmWillShepherd

Copy link
Copy Markdown
Contributor

👋 @msztech

I've noticed this PR has been quiet for a few weeks. I understand that things may come up, so I wanted to checkin to see if you're still interested in getting this PR into Desktop. I'm going to close this PR for now, but feel free to re-open if you'd like to get Xcode support into Desktop 👍

@msztech

msztech commented Sep 3, 2019 •

Copy link
Copy Markdown
Contributor Author

@iAmWillShepherd Will create another PR in the original issue #4825 this week. Sorry I was working on projects in the summer so didn't get a time to work on this.

@msztech
msztech deleted the upstream-master branch September 3, 2019 02:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants